I need to generate 4 unduplicated numbers from certain range. Is there effective way to do that?
Asked
Active
Viewed 103 times
0
-
2What's your R&D says? Have you tried to search it on SO first and then on Google? – Paresh Mayani Jan 30 '14 at 10:44
-
If you need to get the number from sequence you can use Atomic Integer or need to write some code – Kick Jan 30 '14 at 10:45
-
possible duplicate of http://stackoverflow.com/questions/4040001/creating-random-numbers-with-no-duplicates – dev2d Jan 30 '14 at 10:49
3 Answers
1
If your range is [x, y], generate any 4 numbers in [x, y-3].
There can be duplicated in these 4 numbers, that's OK.
Sort them. Say they are: a1 <= a2 <= a3 <= a4. Now use the
numbers b1=a1, b2=a2+1, b3=a3+2, b4=a4+3 as if they were
the generated ones. They are in [x, y] and are not duplicated.

peter.petrov
- 38,363
- 16
- 94
- 159
1
Here is the simplest way to do it.
final int LIMIT = 100;
final int COUNT = 4;
Set<Integer> randomNumbers = new HashSet<Integer>(COUNT);
while(randomNumbers.size() < COUNT) {
randomNumbers.add(new Random().nextInt(LIMIT));
}

Srikanth
- 2,014
- 19
- 22
-
Theoretically this may never complete, your loop. At least it is non-deterministic i.e. you don't know after how many steps it will complete. – peter.petrov Jan 30 '14 at 10:50
0
ArrayList<Integer> numbers= new ArrayList<Integer>();
int from = 2, to = 100;
for(int i=from;i<=to;i++)
{
numbers.add(i);
}
Collections.shuffle(numbers);
pick first four number from arrayList.

Sunny
- 14,522
- 15
- 84
- 129
-
This is good if your range length is not too big. But if you have 10000000 numbers in it, it is not really nice to load them in memory just to shuffle them. – peter.petrov Jan 30 '14 at 11:00
-
I think so. Depends on how exactly the `Collections.shuffle(numbers)` is implemented. Should be OK, yes. – peter.petrov Jan 30 '14 at 11:05