Ejemplo n.º 1
0
// Just testing that we can create a solver and call Solve().
// Tests that involves solving boards is implemented in puzzle/solver_test.go
func TestBacktrack(t *testing.T) {
	for _, v := range []string{"easy", "medium", "hard"} {
		board, err := puzzle.Generate(v)
		assert.NotNil(t, board)
		assert.NoError(t, err)

		solvedBoard := NewSolver(board).Solve()
		assert.NotNil(t, solvedBoard)
	}
}
Ejemplo n.º 2
0
func main() {
	flag.StringVar(
		&generateFlag,
		"generate",
		"",
		"Generate a Sudoku board, accepts inputs: 'easy', 'medium' 'hard'",
	)
	flag.BoolVar(
		&printDifficuly,
		"print-difficulty",
		false,
		"Prints the difficulty of the input board",
	)
	flag.Parse()

	// Generate a Sudoku board and print it to stdout
	if len(generateFlag) > 0 {
		for {
			// generate a random board
			board, err := puzzle.Generate(generateFlag)
			if err != nil {
				log.Fatalln(err)
			}

			// make sure it can be solved
			// the backtrack algorithm is used to solve the board since it's
			// faster (in most cases) than DLX to detect unsolvable boards
			solvedBoard := backtrack.NewSolver(board).Solve()
			if solvedBoard.Solved() {
				fmt.Println(strings.Replace(board.String(), "0", "_", -1))
				return
			}
		}
	}

	// Read Sudoku board from stdin
	b, err := ioutil.ReadAll(bufio.NewReader(os.Stdin))
	if err != nil {
		log.Fatalln(err)
	}

	// Build the board
	board, err := puzzle.New(b)
	if err != nil {
		log.Fatalln(err)
	}

	// Just print the difficulty of the board if the caller asks for it
	if printDifficuly {
		fmt.Println(board.Difficulty())
		return
	}

	// Solve the board
	dlx := dlx.NewSolver(board)
	solvedBoard := dlx.Solve()
	if !solvedBoard.Solved() {
		log.Fatalln(errUnsolvable)
	}

	fmt.Println(solvedBoard)
}