0

I need to generate 4 unduplicated numbers from certain range. Is there effective way to do that?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Denis Lolik
  • 299
  • 1
  • 4
  • 11

3 Answers3

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