Java - generate Random range of specific numbers without duplication of those numbers - how to?
Sounds simple enough...but I've been plugging away at this, trying to find the one and all solution.
For a range of numbers, say 1-12, I want to generate a random sequence within that range, and include 1 and 12.
I don't want duplicate numbers though.
So I would want something like this - 3,1,8,6,5,4 ..and so on, every number from 1-12.
Then I want to put these random numbers into an Array
and use that array to 'randomly' select and display some items (like inventory pulled from database) on a jsp page.
The problem with what I've tried thus far, is that there are a lot of duplicate numbers being generated...or, not ALL of the numbers are chosen.
Is there a simple solution to this problem?
Edit
Test#1 using Collections
and shuffle()
method -
ArrayList<Integer> list = new ArrayList<Integer>(10);
for(int i = 0; i < 10; i++)
{
list.add(i);
}
Collections.shuffle(list);
String[] randomNumbers = (String[])list.toArray();
for(int i = 0; i < 10; i++)
{
out.print(randomNumbers[i]+"<br>");
}
The result was a sequence with duplicate values -
chose = 3
chose = 8
chose = 7
chose = 5
chose = 1
chose = 4
chose = 6
chose = 4
chose = 7
chose = 12
Test #2 - using Random math class
int max = 12;
int min = 1;
int randomNumber = 0;
String str_randomNumber = "";
for(int i=0; i<10; i++) {
//int choice = 1 + Math.abs(rand.nextInt(11));
int choice = min + (int)(Math.random() * ((max - min) + 1));
out.print("chose = "+choice+"<br>");
}
The result was just like using Collections.shuffle()
.
Solution 1:
You can fill an array with all values from 1 to 12 and then shuffle them (see e.g. Why does Collections.shuffle() fail for my array?)
Solution 2:
You can put all numbers from 1 to 12 in order into array and then use some shuffling algorithm to randomize the order of them e.g. http://www.leepoint.net/notes-java/algorithms/random/random-shuffling.html.