my problem is I want my program to make four unique random choices in range of numbers between 0 to 3 I tried to do it in random class but I could not, , if you could help by code it will be great,my program will be something like this to make it clear
my range
0 1 2 3 randomly chosen number 3
0 1 2 randomly chosen number 1
0 2 randomly chosen number 2
0 it will choose 0 and then the program closes
You could fill an (if you don't need too many numbers)
ArrayList<Integer>
with numbers ranging from 0 - 3. Then you get a random index usingRandom.nextInt(list.size())
, get the number from the list andremoveAt
the entry at your index.If you have your range in sometype of array, then just use a random over the length of the array.
For example if you have an int array called
range
. Then you could use:You're effectively looking for a random permutation of the integers from
0
ton-1
.You could put the numbers from
0
ton-1
into anArrayList
, then callCollections.shuffle()
on that list, and then fetch the numbers from the list one by one:Collectons.shuffle()
guarantees that all permutations occur with equal likelihood.If you wish, you could encapsulate this into an
Iterable
:When you iterate over an instance of this class, it produces a random permutation:
On one particular run, this printed out
1 0 2 3
.