互联网上有许多不同的指令来进行随机排列,但它们都使用库。有没有办法在不使用任何内置库的情况下进行随机排列?我知道如何使用Math.random()
. 生成随机排列是否与Math.random()
?洗牌对我来说看起来很复杂。
我的目标是,如果我通过“java randompermutation 3”运行程序,则程序返回 1,2,3 或 1,3,2,或 3,1,2,或 3,2,1,或 2,3 ,1, 或 2,1,3
互联网上有许多不同的指令来进行随机排列,但它们都使用库。有没有办法在不使用任何内置库的情况下进行随机排列?我知道如何使用Math.random()
. 生成随机排列是否与Math.random()
?洗牌对我来说看起来很复杂。
我的目标是,如果我通过“java randompermutation 3”运行程序,则程序返回 1,2,3 或 1,3,2,或 3,1,2,或 3,2,1,或 2,3 ,1, 或 2,1,3
你能做如下所示的例子吗
public class Main {
public static void main(String[] args) throws Exception {
Integer[] input = new Integer[] { 1, 2, 3 };
Integer[] shuffleInput = shuffle(input);
for (int i=0; i<shuffleInput.length; i++) {
System.out.print(shuffleInput[i]);
}
}
public static Integer[] shuffle(Integer[] input) {
Integer[] inputCopy = input.clone();;
Integer[] output = new Integer[input.length];
for (int i=0; i<output.length; i++) {
// Find and get a random element
int randPicker = (int)(System.currentTimeMillis() % inputCopy.length);
output[i] = inputCopy[randPicker];
// Remove selected element from copy
Integer[] aux = new Integer[inputCopy.length - 1];
System.arraycopy(inputCopy, 0, aux, 0, randPicker);
if (inputCopy.length != randPicker) {
System.arraycopy(inputCopy, randPicker + 1, aux, randPicker, inputCopy.length - randPicker - 1);
}
inputCopy = aux;
}
return output;
}
}
此代码将Integer
任意大小的列表作为输入,并返回包含混合值的列表。
如果列表总是 3 个数字,它可能是一个更简单的版本。
已编辑:此版本不使用Math.random()
或任何其他java.util
.
一种对数组进行排序的算法是基于选择排序的,称为选择混洗。遍历数组并为每个索引选择一个随机索引并交换这两个索引。由于这看起来有点像家庭作业,我将避免给出任何实际代码,但这是一个解决方案。