Sudoku Project
Sudoku Project
A MINI-PROJECT REPORT
Submitted By
Vikash P [RA2211042020009]
Srivarshan S [RA2211042020015]
Ramakrishnan S G [RA2211042020024]
BACHELOR OF TECHNOLOGY
in
BONAFIDE CERTIFICATE
Certified that this mini project report titled “Sudoku Puzzle Generator and
Solver” is the bonafide work of “VIKASH P(RA2211042020009),
SRIVARSHAN S (RA2211042020015), RAMAKRISHNAN S G
(RA2211042020024)”
SIGNATURE
Ms.Aishwarya.K M.E
Assistant Professor,
DECLARATION
We hereby declare that the entire work contained in this mini project report titled “Sudoku
Puzzle Generator and Solver” has been carried out by VIKASH P [RA2211042020009],
SRIVARSHAN S [RA2211042020015], RAMAKRISHNAN S G [RA2211042020024]
at
SRM Institute of Science and Technology, Ramapuram Campus, Chennai - 600089,
Place: Chennai
Date:
ABSTRACT
The software offers a user-friendly interface where users can generate new
puzzles for solving, or let the software solve existing puzzles. It includes
features such as user score, and puzzle difficulty levels.
Overall, the Sudoku generator and solver software provides an engaging and
challenging experience for Sudoku enthusiasts, offering endless puzzles to
solve and enjoy while showcasing the effectiveness of various algorithms in
generating and solving Sudoku puzzles.
TABLE OF CONTENTS
LIST OF FIGURES xi
INTRODUCTION 1
1 1.1 Overview 1
1.2 Problem Statement 2
1.3 Aim of the Project 3
1.4 Scope of the Project 4
SOFTWARE AND HARDWARE 5
SPECIFICATIONS
2 2.1 Hardware Requirements 5
2.2 Software Requirements 5
PROJECT DESCRIPTION 6
3.1 Introduction 6
3 3.2 Algorithm Used 7
3.3 Advantages of Algorithm used 9
3.4 Architecture Diagram 10
3.5 Explanation of the Project 11
3.6 Output Results 12
3.7 Conclusion 13
APPENDIX 14
Source Code 14
LIST OF FIGURES
Fig No. Figure Name Page No.
4.1 Architecture Diagram 10
4.2 Output Screen 12
CHAPTER 1
INTRODUCTION
1.1 Overview
Sudoku, a Japanese puzzle craze that has swept the globe, is a game of logic and numbers
that challenges players of all skill levels. Its allure lies in its simple rules yet complex
solutions, making it a beloved pastime for enthusiasts seeking mental stimulation and
strategic engagement. With its grid of cells waiting to be filled with digits, Sudoku presents
an ideal playground for computational algorithms to flex their muscles in both generation
and solving.
In this digital age, where automation permeates various facets of our lives, the
development of automated Sudoku generators and solvers not only enhances the
accessibility and convenience of the game but also showcases the prowess of
computational techniques in tackling intricate logical puzzles. This project delves into the
realm of Sudoku generation and solving, presenting a comprehensive exploration of
algorithms and methodologies employed in crafting puzzles and finding their solutions.
The primary objective of this work is twofold: first, to develop an automated Sudoku
generator capable of producing puzzles of varying difficulty levels, ensuring their
uniqueness and solvability; and second, to devise an efficient solver algorithm capable of
accurately solving Sudoku puzzles within reasonable timeframes. Through the
amalgamation of heuristic strategies, constraint satisfaction techniques, and advanced
search algorithms, we aim to create a robust computational framework that caters to both
puzzle generation and solving aspects of Sudoku.
1
1.2 Problem Statement
The problem statement for a Sudoku generator and solver revolves around the need for an
automated system capable of both creating and solving Sudoku puzzles. Specifically, it
involves addressing the challenges of efficiently generating unique and solvable Sudoku
puzzles of varying difficulty levels and accurately solving existing puzzles within
reasonable timeframes.
a) Creating an algorithm to automatically generate Sudoku puzzles that are unique and
solvable through logic alone.
b) Ensuring the generated puzzles cater to different skill levels by adjusting their
difficulty levels.
c) Developing strategies to efficiently create puzzles while maintaining their quality
and uniqueness.
d) Designing an algorithm to accurately and efficiently solve Sudoku puzzles.
e) Implementing techniques such as constraint propagation and logical deduction to
systematically find solutions.
f) Ensuring the solver can handle puzzles of varying complexities and provide correct
solutions within reasonable timeframes.
g) Providing functionalities for users to generate new puzzles, solve existing ones, and
adjust difficulty levels seamlessly.
2
1.3 Aim of the Project
The primary objective of the Sudoku generator and solver system is to provide a
comprehensive computational solution for the creation and solution of Sudoku puzzles.
Automated Puzzle Generation: The system aims to automatically generate Sudoku puzzles
of varying difficulty levels. These puzzles should be unique, ensuring that there is only one
solution, and solvable by logic alone, without requiring guessing or trial and error.
Diverse Challenge Levels: The generator component seeks to produce puzzles that cater to
a wide range of players, from beginners to seasoned enthusiasts. By adjusting the
complexity of generated puzzles, the system aims to provide engaging gameplay
experiences for users of different skill levels.
Efficient Puzzle Solving: The solver component aims to accurately and efficiently solve
Sudoku puzzles, regardless of their complexity. It should employ intelligent algorithms and
logical deduction techniques to systematically search for and identify optimal solutions
within reasonable timeframes.
Reliability and Performance: Both the generator and solver components strive to exhibit
reliability and high performance. The system should consistently generate unique and
solvable puzzles, while the solver should reliably find correct solutions for a diverse set of
Sudoku grids, demonstrating its effectiveness and accuracy.
Usability and Accessibility: The system aims to be user-friendly and accessible to a wide
audience. It should provide intuitive interfaces for generating and solving puzzles, allowing
users to interact with the system effortlessly and enjoyably.
Overall, the objective of the Sudoku generator and solver system is to offer a robust and
versatile computational tool for Sudoku enthusiasts, enhancing their puzzle-solving
experience and showcasing the capabilities of computational algorithms in tackling
complex logical challenges.
3
1.4 Scope of the Project
The scope of the Sudoku generator and solver project encompasses the development,
implementation, and evaluation of an automated system for generating and solving Sudoku
puzzles.
Thus, the scope of the project is focused on creating a functional and reliable Sudoku
generator and solver system that can serve as a valuable tool for puzzle enthusiasts,
showcasing the capabilities of computational algorithms in solving complex logical
puzzles.
CHAPTER 2
4
SOFTWARE AND HARDWARE SPECIFICATIONS
Processor (CPU):
Any modern processor capable of running Python efficiently should suffice. The game's
computational requirements are minimal.
Memory (RAM):
A minimum of 2GB RAM is recommended for smooth execution of the game. More RAM
may be beneficial if running other applications simultaneously.
Operating System:
a) The Sudoku game can run on various operating systems that support Python,
including: Windows, macOS (OS X), Linux distributions.
b) Python Interpreter: Python 3.x (where x is 6 or later) should be installed on your
system. The game was developed using Python 3.6 or higher.
c) Required Python Libraries:
random: This is a built-in module used for generating random numbers and
shuffling sequences.
copy: Another built-in module used for creating deep copies of objects.
You can use any text editor (e.g., Visual Studio Code, Sublime Text, Atom)
or Python IDE (e.g., PyCharm, IDLE) to edit and run the Python code.
CHAPTER 3
5
PROJECT DESCRIPTION
3.1 Introduction
Sudoku, a popular Japanese puzzle game embraced worldwide, challenges players with its
logical rules and numerical grids, providing mental stimulation and strategic enjoyment for
all levels of expertise. Its simplicity in rules belies the complexity of its solutions, making
it a favourite pastime for those seeking engaging puzzles.
In today's digital era, where automation plays a significant role, the development of
automated Sudoku generators and solvers not only increases accessibility and convenience
but also demonstrates the power of computational methods in tackling intricate puzzles.
This project focuses on Sudoku puzzle generation and solving, exploring various
algorithms and methodologies used in crafting puzzles and finding their solutions.
The main goals of this project are two-fold: first, to create an automated Sudoku generator
capable of producing puzzles of different difficulty levels, ensuring uniqueness and
solvability; and second, to devise an efficient solver algorithm capable of solving Sudoku
puzzles accurately within reasonable timeframes. By combining heuristic strategies,
constraint satisfaction techniques, and advanced search algorithms, we aim to build a
strong computational framework that addresses both puzzle generation and solving aspects
of Sudoku.
6
3.2 Algorithm Used
Sudoku, a globally cherished puzzle game, has become a playground for computational
algorithms, enabling automated generation and solving. The puzzle's appeal lies in its
simple rules yet complex solutions, offering enthusiasts mental stimulation and strategic
engagement. In the digital age, automated Sudoku generators and solvers not only enhance
accessibility but also demonstrate the prowess of computational techniques in tackling
intricate puzzles.
The backtracking algorithm for solving Sudoku involves recursively attempting to place
numbers (1-9) in empty cells while adhering to Sudoku rules—no duplicate numbers in
rows, columns, or 3x3 subgrids. If a number placement violates rules, the algorithm
backtracks, trying a different number until a valid solution is found. Optimization
strategies include starting with cells having fewer options, employing constraint
propagation techniques, and using heuristics to enhance efficiency.
To generate Sudoku puzzles, start with an empty grid and solve it using backtracking.
Randomly remove filled cells from the solved grid while ensuring solvability and
uniqueness. Verify puzzle uniqueness and adjust the difficulty by controlling the number
of cells removed. Optimization techniques involve applying symmetry constraints and
implementing unique solution checks during generation.
7
4. Sudoku Solver using Recursion:
This recursive solver iteratively fills empty cells by trying possible values (1-9) and
verifying rule compliance. If valid, the algorithm recursively solves the next empty cell.
Backtracking occurs if a solution path leads to an invalid state. Optimization involves
heuristic cell and value selection, constraint propagation, and pruning techniques to
enhance efficiency.
The recursive generator starts with an empty grid and randomly fills cells, ensuring rule
compliance. If a value is valid, the generator recurses to fill the next cell until the grid is
complete. Difficulty control involves adjusting backtracking steps. Optimization includes
symmetry breaking to avoid redundant solutions and ensuring unique puzzle generation.
Randomization techniques are employed in both puzzle generation and solving to introduce
variation and enhance efficiency. These techniques include random cell and value
selection, shuffling orders, and applying symmetry transformations. Randomization can
influence difficulty levels and aid in escaping local optima during the search.
In summary, Sudoku puzzle generation and solving are rich areas for algorithmic
exploration, leveraging backtracking, constraint satisfaction, recursion, and randomization
to craft and solve puzzles efficiently while embracing the intricacies of logical constraints
and computational techniques.
8
3.3 Advantages of Algorithm used
1. Efficiency:
By leveraging efficient algorithms and optimization techniques from DAA, the Sudoku
generator and solver can perform complex operations such as constraint satisfaction and
backtracking efficiently. DAA provides a framework for analyzing the time and space
complexity of algorithms, ensuring that the generator and solver can handle large Sudoku
puzzles with minimal computational resources.
2. Scalability:
Algorithms designed using DAA principles are often scalable, allowing the generator and
solver to handle Sudoku puzzles of varying sizes and complexities. Whether it's a standard
9x9 Sudoku puzzle or a larger variant with different grid sizes, the generator and solver can
adapt to the task at hand.
3. Correctness:
DAA emphasizes rigorous analysis and correctness proofs of algorithms, ensuring that the
Sudoku generator produces valid and solvable puzzles while the solver accurately finds
solutions. Through careful design and testing, potential errors and edge cases are identified
and addressed, resulting in reliable functionality.
4. Flexibility:
5. Optimization:
9
3.4 Architecture Diagram
10
3.5 Explanation of the Project
The workflow of the Sudoku Solver project can be detailed through a series of steps
starting with user interaction and progressing through puzzle generation, solving, and
validation. Initially, the program prompts the user to choose a difficulty level for the
Sudoku puzzle, which determines the number of initial clues provided in the puzzle grid.
Once the difficulty is selected, the program generates a Sudoku puzzle by first filling the
diagonal 3x3 grids with random numbers to ensure initial uniqueness within these
subgrids.
The puzzle generation process then utilizes a backtracking algorithm to fully solve the
board, guaranteeing a valid and complete solution. Subsequently, a subset of numbers is
removed from the solved board to create the puzzle grid, ensuring the resulting puzzle has
a unique solution. The generated puzzle is presented to the user in a text-based format,
with empty cells represented by dots or zeros, prompting the user to start solving by
inputting numbers into the empty cells based on Sudoku rules.
Upon completing the puzzle or requesting a solution check, the program utilizes the
backtracking algorithm again to verify the correctness of the user's solution. Finally, the
program allows users to continue solving puzzles or generate new puzzles based on their
preference, with a focus on modularity and readability in the underlying code structure for
maintainability and extensibility. This detailed workflow encapsulates the user journey and
the intricate steps involved in generating, solving, and validating Sudoku puzzles within
the Sudoku Solver project.
11
3.6 Output Results
The output and results for a Sudoku generator and solver implemented would typically
include the following:
Generated Sudoku puzzles of varying difficulty levels. The output could be in the
form of a 9x9 grid representing the Sudoku puzzle, with some cells filled in as
clues and others left empty.
Solutions to Sudoku puzzles are provided as a 9x9 grid, with each cell filled in with
the correct value. If the solver cannot find a solution for a given puzzle.
12
3.7 Conclusion
13
APPENDIX
Source Code
import random
import copy
def print_board(board):
horizontal_line = "+-------+-------+------+"
print(horizontal_line)
for i in range(9):
row_string = "| "
for j in range(9):
if board[i][j] == 0:
row_string += ". "
else:
row_string += str(board[i][j]) + " "
if j % 3 == 2:
row_string += "| "
print(row_string)
if i % 3 == 2:
print(horizontal_line)
14
for i in range(start_row, start_row + 3):
for j in range(start_col, start_col + 3):
if board[i][j] == num:
return False
return True
def solve_sudoku(board):
"""Use backtracking to solve the Sudoku puzzle."""
empty_cell = find_empty(board)
if not empty_cell:
return True # Puzzle solved
return False
def find_empty(board):
"""Find the first empty cell (represented by 0) in the Sudoku board."""
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return (i, j)
return None
def generate_sudoku():
"""Generate a Sudoku puzzle with a unique solution."""
15
board = [[0] * 9 for _ in range(9)]
return shuffled_board
def shuffle_numbers():
"""Generate a random permutation of numbers 1-9."""
16
numbers = list(range(1, 10))
random.shuffle(numbers)
return numbers
def shuffle_board(board):
"""Shuffle rows, columns, and numbers within the Sudoku board."""
# Shuffle rows within each 3x3 grid
for _ in range(3):
random.shuffle(board)
def main():
print("Welcome to Unique Sudoku Challenge!")
player_name = input("Enter your name: ")
print(f"Hello, {player_name}! Let's solve some unique Sudoku puzzles.")
score = 0
while True:
print("\nChoose difficulty level:")
print("1. Easy")
print("2. Medium")
print("3. Hard")
print("4. Quit")
17
if choice == "4":
print(f"Thank you for playing, {player_name}! Your final score is {score}.")
break
18