Recursive solution to Sudoku generator

后端 未结 6 961
青春惊慌失措
青春惊慌失措 2020-12-19 05:14

I\'m trying to code an algorithm that creates a legal Sudoku board in either Java or Javascript. Neither work, and I\'m not entirely sure why.

Essentially, the prob

6条回答
  •  渐次进展
    2020-12-19 06:19

    Java:

    1. You should initialize your board variable, you may want to initialize it in a constructor:

      public class SudokuGenerator {
      
          public static final int BOARD_WIDTH = 9;
          public static final int BOARD_HEIGHT = 9;
      
          public SudokuGenerator() {
              board = new int[BOARD_WIDTH][BOARD_HEIGHT];
          }
      }
      
    2. I believe that your loop iterator in the function nextBoard it is wrong:

      for(int i=1;i<10;i++){ ... }

      I think that you want to iterate from 0 to 9.

    3. In the function nextBoard, you also need to check the variable:

      int[] toCheck = {1,2,3,4,5,6,7,8,9};

      You get an java.lang.ArrayIndexOutOfBoundsException, you should initialize it from 0 to 8, otherwise you try to access the board row number 9 and you get a runtime error.

    4. Another problem that you need to solve is that x is being set to nine in nextBoard() function. Call the function nextBoard(int x, int y) "manually" with these parameteres: nextBoard(7,3) and you will understand why x is being set to nine. Check specifically the values of the variable nextX.

    I believe it will really help you if you use a debugger to check this kind of errors, here you have a nice tutorial with a video explanation(in case your are using the Eclipse IDE).

    Hope it helps.

提交回复
热议问题