Keigh-Jhöe Tatú - 11 months ago 48

Java Question

I'm trying to get the secret code from 1 - 40, not to repeat any numbers. How am I able to compare each of them and not get any duplicates?

I have extensively looked through Java documentation and asked my lectures and I can't get a working answer. I understand the concept, what I'm meant to do, but just can't get the coding right.

Here is my code:

`public static void main(String[] args) {`

int[] secret = new int[5];

//int[] secret = {0,0,0,0,0};

int[][] num = new int[3][5];

int correctL1 = 0;

int correctL2 = 0;

int correctL3 = 0;

for (int i = 0; i<5; i++){ // to get secret numbers.

secret[i] = (int) ((Math.random() * (40 - 1)) + 1);

}

System.out.println(Arrays.toString(secret));

}

I have tried putting this into the loop to get another number but it's still giving me duplicates.

`if(((secret[i] == secret[0]) || (secret[i] == secret[1]) ||`

(secret[i] == secret[2]) || (secret[i] == secret[3]) ||

(secret[i] == secret[4])) || (secret[i] != 0)) {

secret[i] = ((int) ((Math.random() * (40 - 1)) + 1));

}

Answer Source

In Java 8, you can use `Random#ints`

to easily generate an array of distinct random numbers:

```
int[] secret = new Random().ints(1, 40).distinct().limit(5).toArray();
```

Otherwise, you can generate a `Set<Integer>`

by using a `while`

loop:

```
Set<Integer> secret = new HashSet<>();
Random gen = new Random();
while (secret.size() < 5) {
secret.add(gen.nextInt(40 - 1) + 1);
}
```