問題描述
基本上,假設我有一個可以容納 10 個數字的 int 數組.這意味著我可以在每個索引中存儲 0-9(每個數字只能存儲一次).
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).
如果我運行下面的代碼:
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]
但是如何在每次運行代碼時隨機分配數字?例如,我希望數組看起來像:
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]
推薦答案
將其設為 List
而不是數組,并使用 Collections.shuffle() 對其進行隨機播放.您可以在洗牌后從列表中構建 int[].
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.
如果你真的想直接進行隨機播放,請搜索Fisher-Yates Shuffle".
If you really want to do the shuffle directly, search for "Fisher-Yates Shuffle".
以下是使用列表技術的示例:
Here is an example of using the List technique:
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]);
}
}
}
這篇關于如何在給定范圍內創建一個隨機打亂數字的 int 數組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!