| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| import pandas as pd |
| import numpy as np |
| import matplotlib.pyplot as plt |
| import seaborn as sns |
| from tqdm.auto import tqdm |
| import os |
|
|
| |
|
|
| def string_to_grid(s: str) -> np.ndarray: |
| """Converts an 81-character string to a 9x9 NumPy array.""" |
| return np.array(list(map(int, s))).reshape((9, 9)) |
|
|
| def grid_to_string(g: np.ndarray) -> str: |
| """Converts a 9x9 NumPy array back to an 81-character string.""" |
| return "".join(map(str, g.flatten())) |
|
|
| def get_all_symmetries(grid: np.ndarray) -> set: |
| """ |
| Generates all 8 unique symmetries (rotations and mirrors) for a given grid. |
| Returns a set of the grids represented as strings. |
| """ |
| symmetries = set() |
| current_grid = grid.copy() |
| |
| for _ in range(4): |
| symmetries.add(grid_to_string(current_grid)) |
| symmetries.add(grid_to_string(np.flipud(current_grid))) |
| current_grid = np.rot90(current_grid) |
| |
| return symmetries |
|
|
| def compare_cell_similarity(grid1: np.ndarray, grid2: np.ndarray) -> int: |
| """Counts the number of cells that have the same value in the same position.""" |
| return np.sum(grid1 == grid2) |
|
|
| def compare_digit_frequency_similarity(grid1: np.ndarray, grid2: np.ndarray) -> int: |
| """ |
| Counts how many digits (1-9) have the same frequency in both grids. |
| """ |
| |
| |
| vals1, counts1 = np.unique(grid1, return_counts=True) |
| vals2, counts2 = np.unique(grid2, return_counts=True) |
| |
| freq_map1 = dict(zip(vals1, counts1)) |
| freq_map2 = dict(zip(vals2, counts2)) |
| |
| similar_freq_count = 0 |
| for digit in range(1, 10): |
| if freq_map1.get(digit, 0) == freq_map2.get(digit, 0): |
| similar_freq_count += 1 |
| |
| return similar_freq_count |
|
|
| |
|
|
| def analyze_solved_grids( |
| csv_path: str = 'sudoku.csv', |
| start_index: int = 0, |
| end_index: int = 600, |
| min_diff_cells_for_log: int = 4 |
| ): |
| """ |
| Main function to drive the analysis of the solved sudoku grids. |
| """ |
| print("--- Sudoku Solved Grid Analyzer ---") |
|
|
| |
| if not os.path.exists(csv_path): |
| print(f"ERROR: The file '{csv_path}' was not found.") |
| print("Please ensure the sudoku data file is in the same directory.") |
| return |
|
|
| print(f"Loading data from '{csv_path}'...") |
| df = pd.read_csv(csv_path) |
| |
| if 'solutions' not in df.columns: |
| print("ERROR: The CSV file must contain a 'solutions' column with fully solved grids.") |
| return |
| |
| |
| if end_index > len(df): |
| print(f"Warning: end_index ({end_index}) is greater than number of puzzles ({len(df)}). Adjusting to max.") |
| end_index = len(df) |
| if start_index >= end_index: |
| print("Error: start_index must be less than end_index.") |
| return |
|
|
| |
| print("Analyzing the 'solutions' column (fully solved grids).") |
| puzzle_solutions = df['solutions'].iloc[start_index:end_index].tolist() |
| grids = [string_to_grid(p) for p in puzzle_solutions] |
| num_grids = len(grids) |
| print(f"Analysis will be performed on {num_grids} solved grids (indices {start_index} to {end_index-1}).") |
|
|
| |
| exact_duplicates = [] |
| symmetry_pairs = [] |
| cell_similarity_counts = [] |
| digit_freq_similarity_counts = [] |
|
|
| print("\nStarting pairwise comparison... This may take a while.") |
| |
| |
| for i in tqdm(range(num_grids), desc="Analyzing Solved Grids"): |
| grid_i = grids[i] |
| symmetries_of_i = get_all_symmetries(grid_i) |
| |
| for j in range(i + 1, num_grids): |
| grid_j = grids[j] |
| |
| if np.array_equal(grid_i, grid_j): |
| exact_duplicates.append({'index_1': start_index + i, 'index_2': start_index + j}) |
| continue |
| |
| if grid_to_string(grid_j) in symmetries_of_i: |
| symmetry_pairs.append({'index_1': start_index + i, 'index_2': start_index + j}) |
| |
| num_same_cells = compare_cell_similarity(grid_i, grid_j) |
| |
| if (81 - num_same_cells) >= min_diff_cells_for_log: |
| cell_similarity_counts.append(num_same_cells) |
| digit_freq_similarity_counts.append(compare_digit_frequency_similarity(grid_i, grid_j)) |
|
|
| print("\nAnalysis complete. Saving results...") |
|
|
| |
| if exact_duplicates: |
| duplicates_df = pd.DataFrame(exact_duplicates) |
| duplicates_df.to_csv('solved_exact_duplicates.csv', index=False) |
| print(f"Found {len(duplicates_df)} exact duplicate pairs. Logged to 'solved_exact_duplicates.csv'.") |
| else: |
| print("No exact duplicates found in the specified range.") |
|
|
| if symmetry_pairs: |
| symmetry_df = pd.DataFrame(symmetry_pairs) |
| symmetry_df.to_csv('solved_possible_symmetry_pairs.csv', index=False) |
| print(f"Found {len(symmetry_df)} potential symmetry pairs. Logged to 'solved_possible_symmetry_pairs.csv'.") |
| else: |
| print("No symmetry pairs found in the specified range.") |
| |
| |
| sns.set_style("darkgrid") |
|
|
| |
| plt.figure(figsize=(12, 6)) |
| sns.histplot(cell_similarity_counts, bins=81, kde=False) |
| plt.title(f'Distribution of Cell Similarity on Solved Grids ({num_grids} Grids)', fontsize=16) |
| plt.xlabel('Number of Identical Cells in Same Position (out of 81)', fontsize=12) |
| plt.ylabel('Frequency (Number of Pairs)', fontsize=12) |
| plt.xlim(0, 81) |
| plt.tight_layout() |
| plt.savefig('solved_cell_similarity_histogram.png') |
| plt.close() |
| print("Saved 'solved_cell_similarity_histogram.png'.") |
|
|
| |
| plt.figure(figsize=(12, 6)) |
| sns.histplot(digit_freq_similarity_counts, bins=10, discrete=True, kde=False) |
| plt.title(f'Distribution of Digit Frequency Similarity on Solved Grids ({num_grids} Grids)', fontsize=16) |
| plt.xlabel('Number of Digits (1-9) with Same Frequency in Both Grids', fontsize=12) |
| plt.ylabel('Frequency (Number of Pairs)', fontsize=12) |
| plt.xticks(range(10)) |
| plt.tight_layout() |
| plt.savefig('solved_digit_frequency_similarity_histogram.png') |
| plt.close() |
| print("Saved 'solved_digit_frequency_similarity_histogram.png'.") |
| |
| print("\n--- Analysis Finished ---") |
|
|
|
|
| if __name__ == '__main__': |
| |
| DATA_FILE_PATH = 'sudoku.csv' |
| START_PUZZLE_INDEX = 0 |
| END_PUZZLE_INDEX = 600 |
| MIN_DIFFERENT_CELLS = 4 |
| |
| |
| analyze_solved_grids( |
| csv_path=DATA_FILE_PATH, |
| start_index=START_PUZZLE_INDEX, |
| end_index=END_PUZZLE_INDEX, |
| min_diff_cells_for_log=MIN_DIFFERENT_CELLS |
| ) |