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

1

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

liked it! a question, if i execute Collection.Shuffle twice or thrice will it provide different order?
I'm pretty sure that it will. I can't find a reason why it shouldn't. Easy enough to check though, eh? ;)
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;
        }
    }
}

1 Comment

unfortunately this method doesn't scale very well
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);
}

1 Comment

I like the subList() enhancement in this solution - great for dealing out a hand of cards from a deck
-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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.