7

can anyone please tell me how to generate random numbers with no repeat example

random (10) should(may) return 3,4,2,1,7,6,5,8,9,10 with no repeat

Thanks

Jimmy
  • 16,123
  • 39
  • 133
  • 213
Yogesh
  • 1,206
  • 4
  • 22
  • 50
  • it will help you: http://stackoverflow.com/questions/4040001/java-creating-random-numbers-with-no-duplicates – Thiru Oct 11 '11 at 11:12

4 Answers4

27

I would suggest adding the numbers to an ArrayList<Integer> and then use Collections.shuffle() to randomize their order. Something like this:

ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 1; i <= 10; ++i) number.add(i);
Collections.shuffle(number);
Till Helge
  • 9,253
  • 2
  • 40
  • 56
  • liked it! a question, if i execute Collection.Shuffle twice or thrice will it provide different order? – Yogesh Oct 11 '11 at 11:23
  • I'm pretty sure that it will. I can't find a reason why it shouldn't. Easy enough to check though, eh? ;) – Till Helge Oct 11 '11 at 11:25
4

Make a list of generated numbers, when your newly generated number is already in this list you make a new random number.

Random rng = new Random(); // Ideally just create one instance globally
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < numbersNeeded; i++)
{
    while(true)
    {
        Integer next = rng.nextInt(max) + 1;
        if (!generated.contains(next))
        {
            // Done for this iteration
            generated.add(next);
            break;
        }
    }
}
Michele
  • 6,126
  • 2
  • 41
  • 45
2

My two cents

public Collection<Integer> getRandomSubset(int max,int count){
    if(count > max){
        throw new IllegalArgumentException();
    }
    ArrayList<Integer> list = new ArrayList<Integer>();
    for(int i =  0 ; i < count ;i++){
        list.add(i);
    }       
    Collections.shuffle(list);
    return list.subList(0, count);
}
Nikolay Ivanov
  • 8,897
  • 3
  • 31
  • 34
-2

If there are only a few numbers, less than 100, I think I solution could be create a boolean array and once you get a number, set the position of the array to true. I don't think that it takes long time until all the numbers appear. Hope it helps!

Cheers!

Guido
  • 39
  • 4