[英]Generate Random Numbers In A Range with All Numbers Being Hit
我想從0-9范圍生成隨機整數,並將其放入大小為100的數組中。 這很容易,但是對於如何確保在數組中,在0-9范圍內的每個整數至少出現一次,我一無所知。
順便說一下,這都是使用java的。
到目前為止,這是我所得到的(編碼中的數字有所不同,因為我想問一個更簡單的問題):
public static int[] extendTo1024(int[] key) {
int[] extendedKey = new int[1024];
Random random = new Random();
for(int i = 0; i < 1024; i++) {
int rand = random.nextInt(64) + 1;
extendedKey[i] = bitKey[rand];
}
return extendedKey;
}
有什么幫助嗎? 先感謝您!
ArrayList<Integer> al = new ArrayList<Integer>();
//make sure the array contains all occurences of 0-9
for (int i = 0; i < 10; i++) {
al.add(i, i);
}
//generate random number for the remaining 90
for (int i = 10; i < 100; i++) {
int random = (int) (Math.random() * 10);
al.add(i, random);
}
//shuffle the random numbers to make sure that the first 10 are randomly placed
Collections.shuffle(al);
//Convert it back to array (In case you need it to be array not ArrayList)
Integer[] randomNums = al.toArray(new Integer[100]);
//result
for (int i : randomNums) {
System.out.println(i);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.