java - Identifying duplicates before adding them into an array -


i attempting write program, consists of array, filled 50 random numbers, between values 1-999. before random number added array, must check number not duplicate , not in array.

i seem close correct output, reason, repeatedly number 0 first element in array, , number ever duplicated. know why is, , if able provide suitable fix?

once duplicate found, needs printed output, , replaced new unique random number.

thanks in advance.

import java.util.*; public class random50 { public static void main (string[] args) {     final int max_size = 50;     int[] r50 = new int[max_size];     boolean duplicates = false;      random rand = new random();      (int i=0; i<r50.length; i++)     {            (int j=i+1;j<r50.length;j++)         {             r50[i] = rand.nextint(1000);              if (j!=i && r50[i] == r50[j])             {                 duplicates = true;                 system.out.println("dupe: " + r50[i]);                 r50[i] = rand.nextint(1000);             }          }     }      system.out.println(arrays.tostring(r50)); } 

}

j greater i, because initialize j i+1. means values of r50 referenced j 0, duplicates.

for example, if = 20, in second loop, j start @ 21. r50[21], r50[22], etc... 0, because haven't set them yet, possible duplicate of r50[i] , r50[j] 0.

edit: if point of j iterate through previous elements of array, you'll want

   (int i=0; i<r50.length; i++)     {            r50[i] = rand.nextint(1000); //set before j loop         (int j = 0; j < i; j++)         {             while (r50[i] == r50[j]) //while loop, in case of multiple duplicates             {                 duplicates = true;  //still not sure why want boolean                 system.out.println("dupe: " + r50[i]);                 r50[i] = rand.nextint(1000);             }     } } 

though still won't work perfectly, because might set r50 earlier value, after checked it. example, if made sure r50[20] isn't equal values of j through 10, , equal r50[11] (when j = 11), might accidentally change value of j less (for example, r50[5]).

i think neatest way is, duncan , rajeev have,

hashset numbers = new hashset(); random rand = new random();  while(numbers.size() < max_size) {     numbers.add(rand.nextint(1000)); } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -