Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - generate random numbers with no repeat [duplicate]

Tags:

java

random

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

like image 251
Yogesh Avatar asked Oct 11 '11 11:10

Yogesh


2 Answers

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);
like image 149
Till Helge Avatar answered Sep 25 '22 11:09

Till Helge


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;
        }
    }
}
like image 31
Michele Avatar answered Sep 24 '22 11:09

Michele