Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random unique number in java

Tags:

java

random

queue

I'm trying to get a a list of random number and put it in queue without any repetition of the random number.

        int number = 40;

        for (int j = 0; j<number; j++)
        {
            int pick = random.nextInt(number);
            myQueue.add(Integer.toString(pick));
        }
        System.out.println("the queue size: "+myQueue.size());
        Iterator it = myQueue.iterator();
        while(it.hasNext()){
                String iteratorValue = (String)it.next();
                System.out.println("queue next value: "+iteratorValue);
        }

with the above code, I got some repetition of the random number

anyone know how to do it??

like image 800
Newbie Newbae Avatar asked May 22 '26 13:05

Newbie Newbae


1 Answers

How about this:

List<String> list = new ArrayList<String>(number);

for (int i = 0; i < number; i++)
    list.add(Integer.toString(i));

Collections.shuffle(list);

myQueue.addAll(list);

"Adding unique random numbers" in some range is equivalent to adding all of the numbers in the range and then shuffling the result.

like image 82
arshajii Avatar answered May 25 '26 03:05

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!