Here is an example class which creates a random permutation using the approach Dan Dyer suggested. It ensures that each .next() calls gives a new number up to the number given in the constructor. After that it wraps around and gives the same sequence again.
This can be useful for shuffling a playlist.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RandomPermutation{
private List<Integer> list;
private int index;
/**
* Create a random permutation the sequence of numbers 0, 1, ... , n - 1.
* @param n Range specifier, must be positive
*/
public RandomPermutation(int n) {
if (n <= 1) {
throw new IllegalArgumentException(
"Positive number expected, got: " + n);
}
list = new ArrayList<Integer>();
newList(n);
}
/**
* Creates a new list
*/
public void newList(int n) {
index = -1;
list.clear();
for (int i = 0; i < n; i++) {
list.add(i);
}
Collections.shuffle(list);
}
/**
* Retrieve the next integer in sequence.
*/
public int next() {
index = (index + 1) % list.size();
return list.get(index);
}
}
Btw. do not use the approach Snake used.
It is not only because it will freeze once all numbers have been used. That can be fixed.
The problem is more that the procedure runs slower and slower as more and more numbers are in the listIdontWantAnymore. With just 6 numbers it's not a problem, but it can cause quite a significant slowdown if the range is large. Consider choosing between 10000 numbers. After 9900 numbers have been chosen there is a 1% chance of hitting a good number. after 9990 numbers there is a 0.1% chance of hitting a good number and etc.
Here is an example of how you can use the class:
static RandomPermutation randomPerm = new RandomPermutation(7)
int NextRandomNumber() {
return randomPerm.next() + 1;
}