mercredi 5 août 2015

how to generate unique random numbers with a specific range

i want to generate 255 unique random numbers within this range (0-255). so that the array will not contain duplicate records

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

but i get only first 20 0r 30 items with values and the rest of the array items equals zero.




Aucun commentaire:

Enregistrer un commentaire