MartialTerran commited on
Commit
da3b8d4
·
verified ·
1 Parent(s): 6f277e5

Create Generate_sudokuCSV_V2.1.py

Browse files
Files changed (1) hide show
  1. Generate_sudokuCSV_V2.1.py +180 -0
Generate_sudokuCSV_V2.1.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Generate_sudokuCSV_V2.1.py
3
+ #
4
+ # Description:
5
+ # This script generates a high-quality, diverse dataset of Sudoku puzzles and their solutions.
6
+ #
7
+ # Key Logic of V2.1:
8
+ # 1. **Generates Unique Base Solutions:** Uses a randomized backtracking algorithm to
9
+ # create a set of unique solved grids.
10
+ # 2. **Intentionally Creates Symmetries:** For each unique base grid, it generates all 8
11
+ # of its symmetries (rotations and mirrors) and adds them to the dataset.
12
+ # 3. **Removes ONLY Literal Duplicates:** After generating all grids, it performs a
13
+ # deduplication step that ONLY removes grids that are 100% identical, block-for-block.
14
+ # This ensures that rotated and mirrored versions of a grid are KEPT in the final set.
15
+ # 4. **Creates Puzzles:** A unique puzzle with a different pattern of empty cells is
16
+ # created for each final, unique grid.
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+ import random
21
+ import sys
22
+ import os
23
+ from tqdm import tqdm
24
+
25
+ class SudokuGeneratorV2_1:
26
+ """
27
+ A class to generate a Sudoku dataset that includes symmetric variations
28
+ but removes only literal duplicates.
29
+ """
30
+ def __init__(self, num_base_solutions: int, difficulty: float):
31
+ if not (0.1 <= difficulty <= 0.99):
32
+ raise ValueError("Difficulty must be between 0.1 and 0.99")
33
+
34
+ self.num_base_solutions = num_base_solutions
35
+ self.difficulty = difficulty
36
+
37
+ def _find_empty(self, grid):
38
+ """Finds the next empty cell (value 0) in the grid."""
39
+ for i in range(9):
40
+ for j in range(9):
41
+ if grid[i, j] == 0:
42
+ return (i, j)
43
+ return None
44
+
45
+ def _is_valid(self, grid, pos, num):
46
+ """Checks if placing a number in a position is valid."""
47
+ row, col = pos
48
+ # Check row, column, and 3x3 box
49
+ if num in grid[row, :] or num in grid[:, col]:
50
+ return False
51
+ box_x, box_y = col // 3, row // 3
52
+ if num in grid[box_y*3:box_y*3+3, box_x*3:box_x*3+3]:
53
+ return False
54
+ return True
55
+
56
+ def _backtrack_solve(self, grid):
57
+ """A randomized backtracking solver to generate a filled grid."""
58
+ find = self._find_empty(grid)
59
+ if not find:
60
+ return True
61
+ else:
62
+ row, col = find
63
+
64
+ nums = list(range(1, 10))
65
+ random.shuffle(nums)
66
+ for num in nums:
67
+ if self._is_valid(grid, (row, col), num):
68
+ grid[row, col] = num
69
+ if self._backtrack_solve(grid):
70
+ return True
71
+ grid[row, col] = 0
72
+ return False
73
+
74
+ def _get_symmetries(self, grid):
75
+ """Generates all 8 symmetries of a grid (4 rotations and their mirrors)."""
76
+ symmetries = []
77
+ current_grid = grid.copy()
78
+ for _ in range(4):
79
+ symmetries.append(current_grid)
80
+ symmetries.append(np.flipud(current_grid)) # Horizontal mirror
81
+ current_grid = np.rot90(current_grid)
82
+ return symmetries
83
+
84
+ def _create_puzzle_from_solution(self, solution_grid):
85
+ """Removes a percentage of cells from a solved grid to create a puzzle."""
86
+ puzzle = solution_grid.copy().flatten()
87
+ num_to_remove = int(81 * self.difficulty)
88
+ indices = list(range(81))
89
+ random.shuffle(indices)
90
+ puzzle[indices[:num_to_remove]] = 0
91
+ return puzzle.reshape((9, 9))
92
+
93
+ def generate_and_save(self, output_path: str):
94
+ """Main orchestrator method."""
95
+ print("--- Sudoku Generator V2.1 ---")
96
+
97
+ # --- Step 1: Generate unique base solutions ---
98
+ print(f"Generating {self.num_base_solutions} random base solutions...")
99
+ base_solutions = []
100
+ # Use a simple set of strings to avoid generating duplicate bases upfront
101
+ seen_base_strings = set()
102
+ with tqdm(total=self.num_base_solutions, desc="Generating Bases") as pbar:
103
+ while len(base_solutions) < self.num_base_solutions:
104
+ grid = np.zeros((9, 9), dtype=int)
105
+ self._backtrack_solve(grid)
106
+ grid_str = "".join(map(str, grid.flatten()))
107
+ if grid_str not in seen_base_strings:
108
+ seen_base_strings.add(grid_str)
109
+ base_solutions.append(grid)
110
+ pbar.update(1)
111
+
112
+ # --- Step 2: Expand base solutions with all 8 symmetries ---
113
+ print("Applying all 8 symmetries to each base solution to create the full candidate set...")
114
+ all_candidate_solutions = []
115
+ for grid in tqdm(base_solutions, desc="Applying Symmetries"):
116
+ all_candidate_solutions.extend(self._get_symmetries(grid))
117
+ print(f"Generated {len(all_candidate_solutions)} total solutions (including potential literal duplicates).")
118
+
119
+ # --- Step 3: Deduplicate ONLY literal, block-for-block duplicates ---
120
+ print("Removing literal duplicates, keeping all rotations and mirrors...")
121
+ final_solutions = []
122
+ seen_literal_strings = set()
123
+
124
+ grid_to_string = lambda g: "".join(map(str, g.flatten()))
125
+
126
+ for grid in tqdm(all_candidate_solutions, desc="Deduplicating Literals"):
127
+ grid_str = grid_to_string(grid)
128
+ if grid_str not in seen_literal_strings:
129
+ seen_literal_strings.add(grid_str)
130
+ final_solutions.append(grid)
131
+
132
+ print(f"Found {len(final_solutions)} unique grids after removing literal duplicates.")
133
+ print(f"({len(all_candidate_solutions) - len(final_solutions)} literal duplicates were removed).")
134
+
135
+ # --- Step 4: Create a puzzle for each unique solution ---
136
+ print(f"Creating a puzzle for each of the {len(final_solutions)} final grids...")
137
+ puzzles_and_solutions = []
138
+ for solution_grid in tqdm(final_solutions, desc="Creating Puzzles"):
139
+ puzzle_grid = self._create_puzzle_from_solution(solution_grid)
140
+ puzzles_and_solutions.append({
141
+ 'quizzes': grid_to_string(puzzle_grid),
142
+ 'solutions': grid_to_string(solution_grid)
143
+ })
144
+
145
+ # --- Step 5: Save to CSV ---
146
+ print(f"\nSaving {len(puzzles_and_solutions)} puzzles to '{output_path}'...")
147
+ df = pd.DataFrame(puzzles_and_solutions)
148
+ # Shuffle the final dataset so symmetric puzzles aren't clumped together
149
+ df = df.sample(frac=1).reset_index(drop=True)
150
+ df.to_csv(output_path, index=False)
151
+
152
+ print("\n--- Generation Complete ---")
153
+ print(f"Final dataset contains {len(df)} puzzles.")
154
+
155
+
156
+ if __name__ == '__main__':
157
+ # --- Configuration ---
158
+
159
+ # Number of unique base solutions to generate before applying symmetries.
160
+ # The final dataset size will be approximately this number * 8.
161
+ NUM_BASE_SOLUTIONS = 200
162
+
163
+ # The fraction of cells to be empty in the puzzle.
164
+ DIFFICULTY = 0.7
165
+
166
+ # The output file name.
167
+ OUTPUT_FILE = 'sudoku.csv'
168
+
169
+ # --- Execution ---
170
+ if os.path.exists(OUTPUT_FILE):
171
+ overwrite = input(f"WARNING: '{OUTPUT_FILE}' already exists. Overwrite? (y/n): ").lower()
172
+ if overwrite != 'y':
173
+ print("Generation cancelled by user.")
174
+ sys.exit(0)
175
+
176
+ generator = SudokuGeneratorV2_1(
177
+ num_base_solutions=NUM_BASE_SOLUTIONS,
178
+ difficulty=DIFFICULTY
179
+ )
180
+ generator.generate_and_save(OUTPUT_FILE)