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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With