-1

I'm trying to generate 4 random numbers without duplicates, using a loop, but I get an ArrayIndexOutOfBoundsException. Can someone please explain why?

// SECRET ANSWER
int secret[] = new int[4];
for (int i = 0; i < secret.length; i++) {
    secret[i] = (int) (Math.random() * 6 + 1);

    if (secret[i] == secret[i + 1] || secret[i] == secret[i + 2] || secret[i] == secret[i + 3]) {
        secret[i] = (int) (Math.random() * 6 + 1);
    }

    if (secret[i + 1] == secret[i + 2] || secret[i + 1] == secret[i + 3]) {
        secret[i] = (int) (Math.random() * 6 + 1);
    }

    if (secret[i + 2] == secret[i + 3]) {
        secret[i] = (int) (Math.random() * 6 + 1);
    }
}
bcsb1001
  • 2,834
  • 3
  • 24
  • 35
  • If you have an array of length four and you access an index greater than three, then you get an index out of bounds error. Do you see anywhere in your code that might be happening? – astidham2003 Oct 30 '17 at 03:19

3 Answers3

0

So, imagine situation when you are on the last element in the array. You try to get I+1, I+2, I+3 elements which do not exist. You need to change limit to length - 3 or do something similar

Valentun
  • 1,661
  • 12
  • 23
0

you mentioned array size 4 and you are trying to increase it that's why u are getting that exception.you can store only fixed size of elements in the array. It doesn't grow its size at runtime. To overcome this problem, use collection framework.

Shiv
  • 13
  • 7
0

In the second iteration of the for loop, i is 1. The first two conditions in your 'or' chain are false, so the third is evaluated, which causes secret[i + 3] to be accessed. i + 3 is 4, but secret only has indexes 0 to 3. Your algorithm makes no sense.

This generates an array of 4 distinct, random numbers in the range [1..6]:

Random rand = new Random();
int[] secret = rand.ints(1, 7).distinct().limit(4).toArray();

Although, if you must use for loops, you should check all elements before the current index using a nested for loop, as this is all you need to check. You should also use a while loop to make sure you keep generating random numbers until you get one that hasn't been generated yet.

For example:

int[] secret = new int[4];
for (int i = 0; i < secret.length; i++) {
    int n;
    boolean distinct;
    do {
        distinct = true;
        n = (int) (Math.random() * 6 + 1);
        for (int j = 0; j < i; j++) {
            if (secret[j] == n) {
                distinct = false;
            }
        }
    } while (!distinct);
    secret[i] = n;
}
bcsb1001
  • 2,834
  • 3
  • 24
  • 35