In my Android app, I need to pick two random integers from a specified range. The below code works, but it’s not really picking a random integer, it’s shuffling the ints. And the thing that bugs me is that I have to specify the max int as one less than is actually the max value because of the randomNum2= (int)it.next(); bit in the code. If I put the correct number (currently 127) as the max, then I get the error java.util.NoSuchElementException because it’s looking for 128 as the next iteration. Before I was using rand = new Random(); But the problem there is the two random ints may end up being the same, and I need them to be unique. So can anyone suggest a better method for getting TWO random numbers from a min/max integer range? Here’s my code:
randomNum1 = rand.nextInt(max - min + 1) + min;
randomNum2 = rand.nextInt(max - min + 1) + min;
int min = 1;
int max = 126;
int randomNum1;
int randomNum2;
List<Integer> choicesL;
public void randomTwo() {
choicesL = new LinkedList<Integer>();
for (int i = min; i <= max; i++) {
choicesL.add(i);
}
Collections.shuffle(choicesL);
Iterator<Integer> it = choicesL.iterator();
while (it.hasNext())
{
randomNum1= (int)it.next();
randomNum2= (int)it.next();
}
}
You can use your old code but with a loop while.
EDIT
There are many ways to look for a random number. I don’t know if you know this but below this there are lots of statistical studies. If you need a fast way to calculate random numbers this is great. But you have to know that after a big time an user can know how is the distribution of your random numbers. If you want to improve your code maybe you can check:
http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
http://en.wikipedia.org/wiki/Ziggurat_algorithm
And of course I supose that there are much more theory on the net