0

I have recently started making a sudoku solver. The solver itself is done and works great but i have found one issue. My solver is based on a 2D array that stores the sudoku game board numbers. The array looks like this....

The 12's represent empty spaces that need numbers in them.

private static int[][] currentPuzzle = new int[][] {
        { 12, 12, 6, 12, 12, 12, 12, 12, 12 },
        { 12, 12, 12, 12, 3, 6, 5, 12, 12 },
        { 2, 3, 8, 12, 12, 4, 12, 12, 12 },
        { 8, 7, 12, 12, 12, 12, 12, 12, 5 },
        { 12, 12, 3, 12, 9, 12, 2, 12, 12 },
        { 4, 12, 12, 12, 12, 12, 12, 6, 8 },
        { 12, 12, 12, 4, 12, 12, 8, 1, 9 },
        { 12, 12, 9, 3, 7, 12, 12, 12, 12 },
        { 12, 12, 12, 12, 12, 12, 6, 12, 12 } };

The problem is that my program reads the sudoku board integers from a game using the reflection java api. The method returns the sudoku board as a 1D array that looks like this....

The 12's represent empty spaces that need numbers in them.

private static int[] currentPuzzle = new int[] { 12, 12, 6, 12, 12, 12, 12,
        12, 12, 12, 12, 12, 12, 3, 6, 5, 12, 12, 2, 3, 8, 12, 12, 4, 12,
        12, 12, 8, 7, 12, 12, 12, 12, 12, 12, 5, 12, 12, 3, 12, 9, 12, 2,
        12, 12, 4, 12, 12, 12, 12, 12, 12, 6, 8, 12, 12, 12, 4, 12, 12, 8,
        1, 9, 12, 12, 9, 3, 7, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 6,
        12, 12 };

I need to convert the 1D array version(the second array shown above) of the board into the a 2D array version(the first array shown above) format. The new 2D array must have 9 rows with 9 columns.

Do you guys have any ideas?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523

2 Answers2

0

You'll want to use a nested loop to fill the 2D array, and at every point access the correct location in the 1D array:

int[][] result = new int[9][];
for(int x = 0;x < 9;x++) {
    result[x] = new int[9];
    for(int y = 0;y < 9;y++) {
        result[x][y] = currentPuzzle[9*x+y];
    }
}

You also want to think about what is X and what is Y and in what order the 1D array is ordered. This code might produce a Sudoku that's flipped around the diagonal.

Ghostkeeper
  • 2,830
  • 1
  • 15
  • 27
0

Sure - it looks like this should be very easy. As long as you know that it will alays have 81 entries, you can use this:

public static int[][] convertArray(int[] oldArray) {
    int[][] newArray = new int[9][9];
    for(int i = 0; i < 8; i++) {
        for(int k = 0; k < 8; k++) {
            newArray[i][k] = oldArray[(i * 9) + k]
        }
    }
    return newArray;
}

The idea is that you create a new 2D array, and then the outside forloop controls which row you are putting the numbers in, and the inside forloop controls which column.

Alex K
  • 8,269
  • 9
  • 39
  • 57