random unique number in java

2019-01-28 22:11发布

问题:

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??

回答1:

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.



回答2:

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 A. R. S., 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.



回答3:

If there is a small range of the random numbers, then you can simply generate list with available values and use Collections.shuffle on the list.