java android - 生成不重复的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7724999/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:08:18  来源:igfitidea点击:

android - generate random numbers with no repeat

javarandom

提问by Yogesh

can anyone please tell me how to generate random numbers with no repeat example

谁能告诉我如何生成没有重复示例的随机数

random (10) should(may) return 3,4,2,1,7,6,5,8,9,10 with no repeat

随机(10)应该(可能)返回 3,4,2,1,7,6,5,8,9,10 不重复

Thanks

谢谢

回答by Till Helge

I would suggest adding the numbers to an ArrayList<Integer>and then use Collections.shuffle()to randomize their order. Something like this:

我建议将数字添加到 anArrayList<Integer>然后用于Collections.shuffle()随机化它们的顺序。像这样的东西:

ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 1; i <= 10; ++i) number.add(i);
Collections.shuffle(number);

回答by Michele

Make a list of generated numbers, when your newly generated number is already in this list you make a new random number.

列出生成的数字,当您新生成的数字已在此列表中时,您将创建一个新的随机数。

Random rng = new Random(); // Ideally just create one instance globally
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < numbersNeeded; i++)
{
    while(true)
    {
        Integer next = rng.nextInt(max) + 1;
        if (!generated.contains(next))
        {
            // Done for this iteration
            generated.add(next);
            break;
        }
    }
}

回答by Nikolay Ivanov

My two cents

我的两分钱

public Collection<Integer> getRandomSubset(int max,int count){
    if(count > max){
        throw new IllegalArgumentException();
    }
    ArrayList<Integer> list = new ArrayList<Integer>();
    for(int i =  0 ; i < count ;i++){
        list.add(i);
    }       
    Collections.shuffle(list);
    return list.subList(0, count);
}

回答by Guido

If there are only a few numbers, less than 100, I think I solution could be create a boolean array and once you get a number, set the position of the array to true. I don't think that it takes long time until all the numbers appear. Hope it helps!

如果只有几个数字,小于 100,我想我的解决方案可能是创建一个布尔数组,一旦你得到一个数字,将数组的位置设置为 true。我不认为需要很长时间才能出现所有数字。希望能帮助到你!

Cheers!

干杯!