File size: 7,392 Bytes
da3b8d4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
# 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) |