Lesson 29. Capstone: Sudoku rules

 

Sudoku is a logic puzzle that takes place on a 9 × 9 grid (see en.wikipedia.org/wiki/Sudoku). Each square can contain a digit from 1 through 9. The number zero indicates an empty square.

The grid is divided into nine subregions that are 3 × 3 each. When placing a digit, it must adhere to certain constraints. The digit being placed may not already appear in any of the following:

  • The horizontal row it’s placed in
  • The vertical column it’s placed in
  • The 3 × 3 subregion it’s placed in

Use a fixed-size (9 × 9) array to hold the Sudoku grid. If a function or method needs to modify the array, remember that you need to pass the array with a pointer.

Implement a method to set a digit at a specific location. This method should return an error if placing the digit breaks one of the rules.

Also implement a method to clear a digit from a square. This method need not adhere to these constraints, as several squares may be empty (zero).

Sudoku puzzles begin with some digits already set. Write a constructor function to prepare the Sudoku puzzle, and use a composite literal to specify the initial values. Here’s an example:

s := NewSudoku([rows][columns]int8{
    {5, 3, 0, 0, 7, 0, 0, 0, 0},
    {6, 0, 0, 1, 9, 5, 0, 0, 0},
    {0, 9, 8, 0, 0, 0, 0, 6, 0},
    {8, 0, 0, 0, 6, 0, 0, 0, 3},
    {4, 0, 0, 8, 0, 3, 0, 0, 1},
    {7, 0, 0, 0, 2, 0, 0, 0, 6},
    {0, 6, 0, 0, 0, 0, 2, 8, 0},
    {0, 0, 0, 4, 1, 9, 0, 0, 5},
    {0, 0, 0, 0, 8, 0, 0, 7, 9},
})