I am generating an array of 6 ints within a range of 1- 54 (similar to lotto numbers). However, when trying to detect duplicates, my code is not executing. I tried to debug by simply printing "WE HAVE FOUND A DUPLICATE" if my conditional logic would catch a duplicate. Of course, it doesn't print the desired output:
18-33-39-41-41-45
I want to detect the duplicate so that I can generate another random number that is not equal to the discovered duplicate. I don't want to just increment/decrement the duplicate's value just to get another number, I want to actually generate another value between 1&54 that is not equal to the duplicate.
Here is my code:
public class Main {
public static void main(String[] args) {
Random rand = new Random();
int[] luckyArray = new int[6];
//build array
for (int i = 0; i < luckyArray.length; i++) {
int luckyNumber = rand.nextInt(54) + 1;
luckyArray[i] = luckyNumber;
}
//detect duplicates in the array
for (int i = 0; i < luckyArray.length; i++) {
if (i > 0 && luckyArray[i] == luckyArray[i - 1]) {
System.out.print("WE HAVE FOUND A DUPLICATE!");
/* while (luckyArray[i - 1] == luckyArray[i]) {
luckyArray[i] = rand.nextInt(54) + 1;
}*/
}
}
//sort the array before printing
Arrays.sort(luckyArray);
for (int t = 0; t < luckyArray.length; t++) {
if (t != 5) {
System.out.print(luckyArray[t] + "-");
} else System.out.print(luckyArray[t]);
}
}
}
I expected to compare the current index [i]
to that of its previous [i-1]
and if/when they are equal, produce a new value for the current index.
Thanks in advance!