简体   繁体   English

生成范围内所有数字均被击中的随机数

[英]Generate Random Numbers In A Range with All Numbers Being Hit

I want to generate random integers from range 0-9 and put it in an array of size 100 . 我想从0-9范围生成随机整数,并将其放入大小为100的数组中。 That's easy but I'm clueless on how to make sure that in the array, I have at least one occurrence of every integer in the range 0-9. 这很容易,但是对于如何确保在数组中,在0-9范围内的每个整数至少出现一次,我一无所知。

This is all using java by the way. 顺便说一下,这都是使用java的。

This is what I've got so far (the numbers are different in my coding because I wanted to ask a simpler question): 到目前为止,这是我所得到的(编码中的数字有所不同,因为我想问一个更简单的问题):

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;
}

Any help? 有什么帮助吗? Thank you in advance! 先感谢您!

  1. Fill the first 10 elements with numbers 0-9 用数字0-9填充前10个元素
  2. Fill the rest with random numbers 用随机数填充其余部分
  3. Shuffle the array 随机排列
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM