private void CreatePuzzleGrid(SudokuPuzzle puzzle, int maxBlanks) { var puzzleGrid = CopyGrid(puzzle.puzzleGrid); int numBlanks = maxBlanks; bool found = false; // // Start with number of blanks as specified in policy // If multiple solutions are found, decrease the number of blank // cells until a single solution is found while (!found && numBlanks > 0) { int numRetries = 10; int retries = 0; while (retries < numRetries && !found) { var rng = new Random(Guid.NewGuid().GetHashCode()); var backupGrid = CopyGrid(puzzleGrid); int numRemainingBlanks = numBlanks; while (numRemainingBlanks > 0) { int row = rng.Next(9); int col = rng.Next(9); while (puzzleGrid[row, col] == 0) { row = rng.Next(9); col = rng.Next(9); } puzzleGrid[row, col] = 0; numRemainingBlanks--; } var copy = CopyGrid(puzzleGrid); puzzle.NumSolutions = _solver.SolveGrid(copy); if (puzzle.NumSolutions > 1) { Console.WriteLine($"Too many solutions: {puzzle.NumSolutions}"); } else if (puzzle.NumSolutions == 0) { Console.WriteLine("No solution found"); } if (puzzle.NumSolutions != 1) { puzzleGrid = backupGrid; } else { found = true; } retries++; } numBlanks--; } puzzle.puzzleGrid = CopyGrid(puzzleGrid); }