java - 如何在给定范围内创建一个带有随机混洗数字的 int 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15196363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java - How do I create an int array with randomly shuffled numbers in a given range
提问by Patricia Shanahan
Basically, let's say I have an int array that can hold 10 numbers. Which mean I can store 0-9 in each of the index.(each number only once).
基本上,假设我有一个可以容纳 10 个数字的 int 数组。这意味着我可以在每个索引中存储 0-9。(每个数字只有一次)。
If I run the code below:
如果我运行下面的代码:
int[] num = new int[10];
for(int i=0;i<10;i++){
num[i]=i;
}
my array would look like this: [0],[1],.....,[8],[9]
我的数组看起来像这样:[0],[1],.....,[8],[9]
But how do I randomize the number assignment each time I run the code? For example, I want the array to look something like: [8],[1],[0].....[6],[3]
但是如何在每次运行代码时随机分配数字?例如,我希望数组看起来像:[8],[1],[0].....[6],[3]
回答by Patricia Shanahan
Make it a List<Integer>
instead of an array, and use Collections.shuffle() to shuffle it. You can build the int[] from the List after shuffling.
使它成为一个List<Integer>
而不是一个数组,并使用 Collections.shuffle() 对其进行洗牌。您可以在改组后从 List 构建 int[] 。
If you really want to do the shuffle directly, search for "Fisher-Yates Shuffle".
如果您真的想直接进行洗牌,请搜索“Fisher-Yates Shuffle”。
Here is an example of using the List technique:
下面是一个使用 List 技术的例子:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String args[]) {
List<Integer> dataList = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
dataList.add(i);
}
Collections.shuffle(dataList);
int[] num = new int[dataList.size()];
for (int i = 0; i < dataList.size(); i++) {
num[i] = dataList.get(i);
}
for (int i = 0; i < num.length; i++) {
System.out.println(num[i]);
}
}
}
回答by KitKat
Collections class has an efficient method for shuffling:
Collections 类有一个有效的 shuffle 方法:
private static Random random;
/**
* Code from method java.util.Collections.shuffle();
*/
public static void shuffle(int[] array) {
if (random == null) random = new Random();
int count = array.length;
for (int i = count; i > 1; i--) {
swap(array, i - 1, random.nextInt(i));
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}