Skip to content

Commit 7bd2e9e

Browse files
Merge pull request #2571 from andoriyaprashant/branch23
KenKen Puzzle Solver Script Added
2 parents e5e1241 + 128805f commit 7bd2e9e

File tree

3 files changed

+157
-0
lines changed

3 files changed

+157
-0
lines changed

KenKen Puzzle Solver/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# KenKen Puzzle Solver
2+
3+
This is a Python script to solve KenKen puzzles, which are grid-based arithmetic puzzles. The script uses a backtracking algorithm to find a solution that satisfies the rules for each group of cells in the puzzle.
4+
5+
## Requirements
6+
7+
- Python 3.x
8+
- math module (included in Python standard library)
9+
10+
## Features
11+
12+
- Solve KenKen puzzles of various sizes and group configurations.
13+
- Customizable grid size and group size.
14+
- Input validation to ensure a valid puzzle is provided.
15+
- User-friendly interface to input the KenKen puzzle interactively.
16+
- Pretty printing of the solved KenKen puzzle.
17+
18+
## How to Use
19+
20+
1. Ensure you have Python 3.x installed on your system.
21+
2. Run the script `kenken_puzzle_solver.py`.
22+
3. Follow the on-screen instructions to input the puzzle details:
23+
- Enter the size of the grid (e.g., 5 for a 5x5 puzzle).
24+
- Enter the size of each group (e.g., 3 for a standard 9x9 puzzle).
25+
- For each group, enter the target number and the operation (+, -, *, /).
26+
4. The script will attempt to solve the puzzle and display the solution or inform you if no solution exists.
27+
28+
## How It Works
29+
30+
1. The script uses a backtracking algorithm to fill the grid with numbers that satisfy the rules for each group.
31+
2. The `solve_kenken` function recursively explores possible solutions until the puzzle is solved or no solution exists.
32+
3. The `is_valid` function checks if a number can be placed in a cell without violating the rules of the puzzle.
33+
34+
## Contributing
35+
36+
If you find any issues or have suggestions for improvement, feel free to open an issue or submit a pull request.
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
import math
2+
3+
def is_valid(board, row, col, num, group_size):
4+
# Check if 'num' can be placed in the given position without violating the rules
5+
# Check row and column
6+
for i in range(len(board)):
7+
if board[i][col] == num or board[row][i] == num:
8+
return False
9+
10+
# Check the group constraints
11+
group_start_row, group_start_col = row - row % group_size, col - col % group_size
12+
for i in range(group_size):
13+
for j in range(group_size):
14+
if board[group_start_row + i][group_start_col + j] == num:
15+
return False
16+
17+
return True
18+
19+
def find_empty_cell(board):
20+
# Find an empty cell (cell with value 0) on the board and return its coordinates
21+
for i in range(len(board)):
22+
for j in range(len(board)):
23+
if board[i][j] == 0:
24+
return i, j
25+
return None
26+
27+
def solve_kenken(board, group_size):
28+
# Function to solve the KenKen puzzle using backtracking
29+
empty_cell = find_empty_cell(board)
30+
if not empty_cell:
31+
# If no empty cell found, the board is solved
32+
return True
33+
34+
row, col = empty_cell
35+
36+
for num in range(1, len(board) + 1):
37+
if is_valid(board, row, col, num, group_size):
38+
board[row][col] = num
39+
40+
if solve_kenken(board, group_size):
41+
return True
42+
43+
board[row][col] = 0
44+
45+
return False
46+
47+
def validate_puzzle_input(size, groups):
48+
# Function to validate the user-provided KenKen puzzle input
49+
# Check for the following conditions:
50+
# 1. The board size is valid (greater than 1 and a perfect square)
51+
# 2. The number of groups is equal to the board size
52+
# 3. Each group has a valid target number (greater than 0)
53+
# 4. Each group operation is valid (+, -, *, /)
54+
55+
if size <= 1 or int(size ** 0.5) ** 2 != size:
56+
print("Invalid board size. The size should be greater than 1 and a perfect square.")
57+
return False
58+
59+
if len(groups) != size:
60+
print(f"Invalid number of groups. Expected {size} groups.")
61+
return False
62+
63+
valid_operations = {'+', '-', '*', '/'}
64+
for target, operation in groups:
65+
if target <= 0:
66+
print("Invalid target number. The target number should be greater than 0 for each group.")
67+
return False
68+
if operation not in valid_operations:
69+
print("Invalid operation. Valid operations are '+', '-', '*', or '/'.")
70+
return False
71+
72+
return True
73+
74+
def get_puzzle_input():
75+
# Function to get the KenKen puzzle input from the user
76+
size = int(input("Enter the size of the grid (e.g., 5 for a 5x5 puzzle): "))
77+
group_size = int(input("Enter the size of each group (e.g., 3 for a standard 9x9 puzzle): "))
78+
79+
groups = []
80+
for i in range(size):
81+
while True:
82+
try:
83+
group_target = int(input(f"Enter the target number for group {i + 1}: "))
84+
group_operation = input(f"Enter the operation for group {i + 1} (+, -, *, /): ")
85+
groups.append((group_target, group_operation))
86+
break
87+
except ValueError:
88+
print("Invalid input. Please enter a valid target number and operation.")
89+
90+
if validate_puzzle_input(size, groups):
91+
return size, group_size, groups
92+
else:
93+
print("Invalid puzzle input. Please try again.")
94+
return None
95+
96+
def print_board(board):
97+
# Function to pretty print the KenKen board
98+
for row in board:
99+
print(" ".join(str(num) if num != 0 else "-" for num in row))
100+
print()
101+
102+
def main():
103+
# Main function to run the KenKen puzzle solver
104+
print("KenKen Puzzle Solver")
105+
106+
puzzle_input = get_puzzle_input()
107+
if puzzle_input:
108+
size, group_size, groups = puzzle_input
109+
110+
# Initialize the board with zeros
111+
kenken_board = [[0 for _ in range(size)] for _ in range(size)]
112+
113+
if solve_kenken(kenken_board, group_size):
114+
print("Solved KenKen Puzzle:")
115+
print_board(kenken_board)
116+
else:
117+
print("No solution exists.")
118+
119+
if __name__ == "__main__":
120+
main()

KenKen Puzzle Solver/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
math

0 commit comments

Comments
 (0)