目录
洗牌算法
算法实现思路如下:
按照下标从大到小的顺序遍历数组,记下标为i
遍历时生成范围[0, i]的随机数j,交换下标i与下标j的数组元素
public static void shuffle(int[] nums) {
Random rnd = new Random();
for (int i = nums.length - 1; i > 0; i--) {
int j = rnd.nextInt(i + 1);
//swap index i, j
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
java实现洗牌算法——详解Collections.shuffle()
public class HelloWorldMainApplication {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
//将52个数字放入一个List中
for(int i=0;i<52;i++){
list.add(i);
}
Collections.shuffle(list); //随机打乱list数据
//按要求输出
String[] flowers = {"桃", "砖", "梅", "心"};
String[] numbers = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
for(int i=0;i<52;i++){
System.out.print(flowers[list.get(i)%4] + numbers[list.get(i)/4] + " ");
if(i%13==12){
System.out.print('\n');
}
}
}
}