Reputation: 1231
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();
randomNum1 = rand.nextInt(max - min + 1) + min;
randomNum2 = rand.nextInt(max - min + 1) + min;
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:
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();
}
}
Upvotes: 0
Views: 312
Reputation: 2782
You can use your old code but with a loop while.
rand = new Random();
randomNum1 = rand.nextInt(max - min + 1) + min;
randomNum2 = rand.nextInt(max - min + 1) + min;
while (randomNum2==randomNum1){
randomNum2 = rand.nextInt(max - min + 1) + min;
}
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
Upvotes: 1
Reputation: 178431
You can use a Set
and keep inserting elements until the set is of size 2.
For small number of elements (comparing to the size of the range) this should be much more efficient then populating + shuffling a list.
int max = 126;
int min = 1;
int size = 2;
Set<Integer> set = new HashSet<Integer>();
Random r = new Random();
while (set.size() != size) {
set.add(r.nextInt(max - min + 1) + min);
}
System.out.println(set);
Note: This is a generic answer that will work for all needed sizes (assuming of course size <= max - min
)
Upvotes: 0