lundi 2 février 2015

Storing non-duplicated numbers in an array

Overview: My program has to store 20, non-duplicated randomly generated numbers from a range of 1 to 100 in an array. Problem: If I find a match(duplicated #) in the inner for loop, I flag the boolean variable. Here is what I don't know how to do. After the for loop, if the boolean hasn't been flagged, I want to add the random number to the array. I also want to increment x (until I have 20 non-duplicated numbers stored) but only if I add the element to the array.



public void duplication(){
int max = 100; // max value for range
int min = 1; // min value for range
boolean duplicate = false;
Random rand = new Random();

for (int x = 0; x < 20; x++){
//initiates array that stores 20 values
int[] all = new int[20];
//generates # from 1-100
int randomNum = rand.nextInt((max - min) + 1) + min;
all[x] = randomNum;
//iterates through array
for (int i : all) {
//if there's a match (duplicate) flag boolean
if (i == randomNum){
duplicate = true;
}
else {
duplicate = false;
}
}
}
//if boolean hasn't been flagged
if (duplicate=false){
//store to array
}
}




Aucun commentaire:

Enregistrer un commentaire