I want to pick 8 random integers in the range 0-7.
int one = (int) (Math.random()*0)+7;
int two = (int) (Math.random()*0)+7;
// ...
int eight = (int) (Math.random()*0)+7;
However, no duplicate numbers are allowed. How can I improve this code to establish this?
I'm not sure if this violates your requirements, but you could just go like this:
Alternatively, you can skip the
shuffle
and just grab a random element out of the list every time you want a random number from 0-7. EG:Follow the below snippet and change the maxLimit and noOfItems according to your preference to get desired result.
Here the Set contains unique integers under specified limit.
Another way is to fill up an array / collection with all possibilities and pick from those. Each picked item is removed from the allowed array and put into the output array until you have picked all items.
This way you skip double picks and the execution is linear.
Something like this:
If you need to generate numbers from
min
tomax
(including both), you can writerandom.nextInt(max - min + 1) + min
There are only 8 integers from 0-7 and so what you are really asking is for the numbers from 0-7 in a random order.
The quickest way to do this both coding and execution is to shuffle a set of integers.
If you want to write a shuffle algorithm yourself you can do so by so swapping every item (bar the last) in an array with a random index. The reason you don't do the last is because it biases the outcome. See Fisher Yates Shuffle
Just because I couldn't resist here is a java implementation of Fisher Yates: