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 co
You're effectively looking for a random permutation of the integers from 0
to n-1
.
You could put the numbers from 0
to n-1
into an ArrayList
, then call Collections.shuffle() on that list, and then fetch the numbers from the list one by one:
final int n = 4;
final ArrayList arr = new ArrayList(n);
for (int i = 0; i < n; i++) {
arr.add(i);
}
Collections.shuffle(arr);
for (Integer val : arr) {
System.out.println(val);
}
Collectons.shuffle()
guarantees that all permutations occur with equal likelihood.
If you wish, you could encapsulate this into an Iterable:
public class ChooseUnique implements Iterable {
private final ArrayList arr;
public ChooseUnique(int n) {
arr = new ArrayList(n);
for (int i = 0; i < n; i++) {
arr.add(i);
}
Collections.shuffle(arr);
}
public Iterator iterator() {
return arr.iterator();
}
}
When you iterate over an instance of this class, it produces a random permutation:
ChooseUnique ch = new ChooseUnique(4);
for (int val : ch) {
System.out.println(val);
}
On one particular run, this printed out 1 0 2 3
.