java - how to generate unique random numbers with a specific range -


i want generate 255 unique random numbers within range (0-255). array not contain duplicate records

short [] array =new short[255]; random rand = new random(); boolean   flag=false; (int i=0;i<array.length;i++){     int random_integer = rand.nextint(255-0) + 0;     (int j=0;j<i;j++){         if ((short)random_integer==array[j]){             flag=true;         }     }     if (flag==false){         array[i]=(short)random_integer;       } } (int i=0;i<array.length;i++){     system.out.println(array[i]); }  

but first 20 0r 30 items values , rest of array items equals zero.

solution 1:

i read jon skeet's comment, of course, easiest solution:

list<integer> list = new arraylist<>(); (int i=0; i<list.size(); i++) {      list.add(i); } //and here point. java have implemented collections.shuffle(list); 

solution 2 (picking on solution):

you need generate number each cell, , check if number exists:

 short [] array =new short[255];  random rand = new random();   (int i=0; i<array.length; i++) {      int random_integer = -1;       //generate integer while exists in array      while(exists(random_integer, array)) {          random_integer = rand.nextint(255);      }       array[i] = random_integer; } 

and now, let's check whether exists:

public boolean exists(int number, int[] array) {     if (number == -1)         return true;       (int i=0; i<array.length; i++) {         if (number == array[i])             return true;     }     return false; } 

of course, can use hashmap example, speed exists() method, i.e. lower complexity o(n) o(1);


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -