diff --git a/src/class14/ArrayTest4.java b/src/class14/ArrayTest4.java new file mode 100644 index 0000000..3cba58f --- /dev/null +++ b/src/class14/ArrayTest4.java @@ -0,0 +1,40 @@ +package class14; + +import java.util.Arrays; + +// ... existing code ... +public class ArrayTest4 { + public static void main(String[] args) { + String[] pokers = start(); + String[] shuffledPokers = shufflePokers(pokers); + System.out.println(Arrays.toString(shuffledPokers)); + } + + public static String[] start() { // 创建一个数组,用来模拟一个扑克牌 + String[] pokers = new String[54]; + String[] colors = {"♠", "♥", "♣", "♦"}; + String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"}; + int i = 0; + for (String number : numbers) { + for (String color : colors) { + pokers[i] = color + number; + i++; + } + } + pokers[i] = "小王"; + pokers[i + 1] = "大王"; + System.out.println(Arrays.toString(pokers)); + return pokers; + } + + public static String[] shufflePokers(String[] pokers) { + // 使用 Fisher-Yates 洗牌算法 + for (int i = pokers.length - 1; i > 0; i--) { + int index = (int) (Math.random() * (i + 1)); + String temp = pokers[i]; + pokers[i] = pokers[index]; + pokers[index] = temp; + } + return pokers; + } +}