Ryan Dorman
Ryan Dorman

Reputation: 317

I can't get numbers in a 2D array to add for a Sudoku solver

I have a 9x9 array for a Sudoku solver and I'm trying to get each 3x3 box to add to 45 and check the value to ensure the numbers are correct. My first for loop works and adds to 45 but for some reason the next one doesn't and I can't figure out why. I have confirmed that the numbers in the area should add to 45 as well. Suggestions?

int sum = 0;
int sum2 = 0;

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        sum += grid[i][j];}}

for (int i = 0; i > 2 && i < 6; i++) {
    for (int j = 0; j < 3; j++) {
        sum2 += grid[i][j];}}

System.out.println(sum); //prints 45 currently
System.out.println(sum2); //prints 0 currently

Upvotes: 1

Views: 225

Answers (1)

Michael Laszlo
Michael Laszlo

Reputation: 12239

This loop isn't going to get executed even once:

for (int i = 0; i > 2 && i < 6; i++)

That's because i is initially zero, which contradicts i > 2 && i < 6, so the test fails and we immediately exit the loop.

What you mean is:

for (int i = 3; i > 2 && i < 6; i++)

But if you want to check each 3x3 box, you probably want to iterate over all nine boxes:

int boxSums[][] = new int[3][3];
for (int iStart = 0; iStart < 9; iStart += 3) {
    for (int jStart = 0; jStart < 9; jStart += 3) {
        int sum = 0;
        for (int i = iStart; i < iStart + 3; i++) {
            for (int j = jStart; j < jStart + 3; j++) {
                sum += grid[i][j];
            }
         }
         boxSums[iStart / 3][jStart / 3] = sum;
     }
}

Better yet, you can iterate over the grid elements and calculate the box indices for each one. This lets you add up the rows and columns at the same time. Also, you can get by with two nested loops instead of four:

int boxSums[][] = new int[3][3],
        rowSums[] = new int[9],
        columnSums[] = new int[9];
for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
        int value = grid[i][j];
        boxSums[i / 3][j / 3] += value;
        rowSums[i] += value;
        columnSums[j] += value;
    }
}

Upvotes: 3

Related Questions