android - generate random numbers with no repeat [duplicate]
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
Thanks
I would suggest adding the numbers to an ArrayList<Integer>
and then use Collections.shuffle()
to randomize their order. Something like this:
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 1; i <= 10; ++i) number.add(i);
Collections.shuffle(number);
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;
}
}
}
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);
}
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!
Cheers!
精彩评论