|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import numpy as np |
|
import pandas as pd |
|
import random |
|
import sys |
|
import os |
|
from tqdm import tqdm |
|
|
|
class SudokuGeneratorV2_1: |
|
""" |
|
A class to generate a Sudoku dataset that includes symmetric variations |
|
but removes only literal duplicates. |
|
""" |
|
def __init__(self, num_base_solutions: int, difficulty: float): |
|
if not (0.1 <= difficulty <= 0.99): |
|
raise ValueError("Difficulty must be between 0.1 and 0.99") |
|
|
|
self.num_base_solutions = num_base_solutions |
|
self.difficulty = difficulty |
|
|
|
def _find_empty(self, grid): |
|
"""Finds the next empty cell (value 0) in the grid.""" |
|
for i in range(9): |
|
for j in range(9): |
|
if grid[i, j] == 0: |
|
return (i, j) |
|
return None |
|
|
|
def _is_valid(self, grid, pos, num): |
|
"""Checks if placing a number in a position is valid.""" |
|
row, col = pos |
|
|
|
if num in grid[row, :] or num in grid[:, col]: |
|
return False |
|
box_x, box_y = col // 3, row // 3 |
|
if num in grid[box_y*3:box_y*3+3, box_x*3:box_x*3+3]: |
|
return False |
|
return True |
|
|
|
def _backtrack_solve(self, grid): |
|
"""A randomized backtracking solver to generate a filled grid.""" |
|
find = self._find_empty(grid) |
|
if not find: |
|
return True |
|
else: |
|
row, col = find |
|
|
|
nums = list(range(1, 10)) |
|
random.shuffle(nums) |
|
for num in nums: |
|
if self._is_valid(grid, (row, col), num): |
|
grid[row, col] = num |
|
if self._backtrack_solve(grid): |
|
return True |
|
grid[row, col] = 0 |
|
return False |
|
|
|
def _get_symmetries(self, grid): |
|
"""Generates all 8 symmetries of a grid (4 rotations and their mirrors).""" |
|
symmetries = [] |
|
current_grid = grid.copy() |
|
for _ in range(4): |
|
symmetries.append(current_grid) |
|
symmetries.append(np.flipud(current_grid)) |
|
current_grid = np.rot90(current_grid) |
|
return symmetries |
|
|
|
def _create_puzzle_from_solution(self, solution_grid): |
|
"""Removes a percentage of cells from a solved grid to create a puzzle.""" |
|
puzzle = solution_grid.copy().flatten() |
|
num_to_remove = int(81 * self.difficulty) |
|
indices = list(range(81)) |
|
random.shuffle(indices) |
|
puzzle[indices[:num_to_remove]] = 0 |
|
return puzzle.reshape((9, 9)) |
|
|
|
def generate_and_save(self, output_path: str): |
|
"""Main orchestrator method.""" |
|
print("--- Sudoku Generator V2.1 ---") |
|
|
|
|
|
print(f"Generating {self.num_base_solutions} random base solutions...") |
|
base_solutions = [] |
|
|
|
seen_base_strings = set() |
|
with tqdm(total=self.num_base_solutions, desc="Generating Bases") as pbar: |
|
while len(base_solutions) < self.num_base_solutions: |
|
grid = np.zeros((9, 9), dtype=int) |
|
self._backtrack_solve(grid) |
|
grid_str = "".join(map(str, grid.flatten())) |
|
if grid_str not in seen_base_strings: |
|
seen_base_strings.add(grid_str) |
|
base_solutions.append(grid) |
|
pbar.update(1) |
|
|
|
|
|
print("Applying all 8 symmetries to each base solution to create the full candidate set...") |
|
all_candidate_solutions = [] |
|
for grid in tqdm(base_solutions, desc="Applying Symmetries"): |
|
all_candidate_solutions.extend(self._get_symmetries(grid)) |
|
print(f"Generated {len(all_candidate_solutions)} total solutions (including potential literal duplicates).") |
|
|
|
|
|
print("Removing literal duplicates, keeping all rotations and mirrors...") |
|
final_solutions = [] |
|
seen_literal_strings = set() |
|
|
|
grid_to_string = lambda g: "".join(map(str, g.flatten())) |
|
|
|
for grid in tqdm(all_candidate_solutions, desc="Deduplicating Literals"): |
|
grid_str = grid_to_string(grid) |
|
if grid_str not in seen_literal_strings: |
|
seen_literal_strings.add(grid_str) |
|
final_solutions.append(grid) |
|
|
|
print(f"Found {len(final_solutions)} unique grids after removing literal duplicates.") |
|
print(f"({len(all_candidate_solutions) - len(final_solutions)} literal duplicates were removed).") |
|
|
|
|
|
print(f"Creating a puzzle for each of the {len(final_solutions)} final grids...") |
|
puzzles_and_solutions = [] |
|
for solution_grid in tqdm(final_solutions, desc="Creating Puzzles"): |
|
puzzle_grid = self._create_puzzle_from_solution(solution_grid) |
|
puzzles_and_solutions.append({ |
|
'quizzes': grid_to_string(puzzle_grid), |
|
'solutions': grid_to_string(solution_grid) |
|
}) |
|
|
|
|
|
print(f"\nSaving {len(puzzles_and_solutions)} puzzles to '{output_path}'...") |
|
df = pd.DataFrame(puzzles_and_solutions) |
|
|
|
df = df.sample(frac=1).reset_index(drop=True) |
|
df.to_csv(output_path, index=False) |
|
|
|
print("\n--- Generation Complete ---") |
|
print(f"Final dataset contains {len(df)} puzzles.") |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
|
|
|
|
|
|
NUM_BASE_SOLUTIONS = 200 |
|
|
|
|
|
DIFFICULTY = 0.7 |
|
|
|
|
|
OUTPUT_FILE = 'sudoku.csv' |
|
|
|
|
|
if os.path.exists(OUTPUT_FILE): |
|
overwrite = input(f"WARNING: '{OUTPUT_FILE}' already exists. Overwrite? (y/n): ").lower() |
|
if overwrite != 'y': |
|
print("Generation cancelled by user.") |
|
sys.exit(0) |
|
|
|
generator = SudokuGeneratorV2_1( |
|
num_base_solutions=NUM_BASE_SOLUTIONS, |
|
difficulty=DIFFICULTY |
|
) |
|
generator.generate_and_save(OUTPUT_FILE) |