java - Implentation of a Selection Shuffle in Java
问题描述
public static void selectionShuffle(int[] values) {
Random rand = new Random();
for(int i = values.length; i > 0; i--) {
int r = rand.nextInt(i);
swap(values, r, i);
}
//updated answer to include below method
public static void swap(int[]a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
I am writing a card game and need to randomly sort the cards in place, I got an ArrayOutOfBoundsException when I ran the above code, with the compiler complaining particularly about the reassignment from values[i] = values[r]
. To be clear, this is , not intended to be a selection sort but instead a selection shuffle. Any help is appreciated!
解决方案
Integer
或者,您可以尝试 Collections.shuffle() 但如果您必须首先使用包装类而不是原始类型,它会更方便int
。
整数 [] 版本:
public static void selectionShuffle(Integer[] values) {
Collections.shuffle(Arrays.asList(values));
}
int[] 版本:
public static void selectionShuffle(int[] values) {
Integer[] boxedArr = Arrays.stream(values).boxed().toArray( Integer[]::new );
Collections.shuffle(Arrays.asList(boxedArr));
for(int i=0 ; i<values.length ; i++){
values[i] = boxedArr[i];
}
}
推荐阅读
- powershell - 对包含给定短语的字符串应用过滤器并返回之后发生的所有内容
- javascript - 根据另一个单词数组对一组单词进行排序
- c# - CodeDOM:命名参数
- node.js - node.js @sendgrid/mail 错误:未经授权
- kubernetes - kube-apiserver healthz 调用中检查了什么?
- css - 当我知道值不是空白时,Asp.net 参数显示为空
- eclipse-emf - 如何在同一工作空间中而不是在运行时 Eclipse 环境中从 Ecore 元模型实例化模型?
- jquery - 单击链接时删除超链接
- r - 模拟适用于 n= 100 但不适用于 n = 300
- php - Mysql如何将多个Where子句添加到单个表中