简体   繁体   中英

random unique number in java

I'm trying to get aa 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??

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.

Create a Set and add you numbers to it as you generate them. The each time you generate a new number check if the Set already contains that value. Continue generating new numbers and checking the set until you find one that is not already there.

Something along these lines... (Note that Set.add(...) returns false if the value is already in the Set, so the do-while loop continues until a unique number is generated.)

   int number = 40;
   Set mySet = new HashSet();
   for (int j = 0; j<number; j++)
   {
       Integer pick;

       do{
           pick = random.nextInt(number);
       } while(!mySet.add(pick));
       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);
   }

Though as mentioned in by ARS, you don't seem to be looking for a random unique number, but rather a randomly shuffled list of all numbers between 0 and 40. If that is the case, use his/her solution as it is a better way to achieve that goal.

如果有一小部分随机数,那么您可以简单地生成包含可用值的列表,并使用列表中的Collections.shuffle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM