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},
})

The starting digits are fixed in place and may not be overwritten or cleared. Modify your program so that it can identify which digits are fixed and which are penciled in. Add a validation that causes set and clear to return an error for any of the fixed digits. The digits that are initially zero may be set, overwritten, and cleared.

You don’t need to write a Sudoku solver for this exercise, but be sure to test that all the rules are implemented correctly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset