Generating Unique Random Numbers in Java -


i'm trying random numbers between 0 , 100. want them unique, not repeated in sequence. example if got 5 numbers, should 82,12,53,64,32 , not 82,12,53,12,32 used this, generates same numbers in sequence.

random rand = new random(); selected = rand.nextint(100); 

  • add each number in range sequentially in list structure.
  • shuffle it.
  • take first 'n'.

here simple implementation. print 3 unique random numbers range 1-10.

import java.util.arraylist; import java.util.collections;  public class uniquerandomnumbers {      public static void main(string[] args) {         arraylist<integer> list = new arraylist<integer>();         (int i=1; i<11; i++) {             list.add(new integer(i));         }         collections.shuffle(list);         (int i=0; i<3; i++) {             system.out.println(list.get(i));         }     } } 

the first part of fix original approach, mark byers pointed out in answer deleted, use single random instance.

that causing numbers identical. random instance seeded current time in milliseconds. particular seed value, 'random' instance return exact same sequence of pseudo random numbers.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -