Sodoku_Puzzle_Generator / Generate_sudokuCSV_V2.1.py
MartialTerran's picture
Create Generate_sudokuCSV_V2.1.py
da3b8d4 verified
raw
history blame
7.39 kB
# Generate_sudokuCSV_V2.1.py
#
# Description:
# This script generates a high-quality, diverse dataset of Sudoku puzzles and their solutions.
#
# Key Logic of V2.1:
# 1. **Generates Unique Base Solutions:** Uses a randomized backtracking algorithm to
# create a set of unique solved grids.
# 2. **Intentionally Creates Symmetries:** For each unique base grid, it generates all 8
# of its symmetries (rotations and mirrors) and adds them to the dataset.
# 3. **Removes ONLY Literal Duplicates:** After generating all grids, it performs a
# deduplication step that ONLY removes grids that are 100% identical, block-for-block.
# This ensures that rotated and mirrored versions of a grid are KEPT in the final set.
# 4. **Creates Puzzles:** A unique puzzle with a different pattern of empty cells is
# created for each final, unique grid.
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
# Check row, column, and 3x3 box
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)) # Horizontal mirror
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 ---")
# --- Step 1: Generate unique base solutions ---
print(f"Generating {self.num_base_solutions} random base solutions...")
base_solutions = []
# Use a simple set of strings to avoid generating duplicate bases upfront
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)
# --- Step 2: Expand base solutions with all 8 symmetries ---
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).")
# --- Step 3: Deduplicate ONLY literal, block-for-block 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).")
# --- Step 4: Create a puzzle for each unique solution ---
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)
})
# --- Step 5: Save to CSV ---
print(f"\nSaving {len(puzzles_and_solutions)} puzzles to '{output_path}'...")
df = pd.DataFrame(puzzles_and_solutions)
# Shuffle the final dataset so symmetric puzzles aren't clumped together
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__':
# --- Configuration ---
# Number of unique base solutions to generate before applying symmetries.
# The final dataset size will be approximately this number * 8.
NUM_BASE_SOLUTIONS = 200
# The fraction of cells to be empty in the puzzle.
DIFFICULTY = 0.7
# The output file name.
OUTPUT_FILE = 'sudoku.csv'
# --- Execution ---
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)