-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcube_solver.py
94 lines (75 loc) · 2.86 KB
/
cube_solver.py
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
WIDTH = 5
DEPTH = 5
HEIGHT = 5
Cube = [[[0 for k in range(WIDTH)] for j in range(DEPTH)] for i in range(HEIGHT)]
Configurations = [
[[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [1, 1, 0]],
[[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [2, 1, 0]],
[[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [1, 0, 1]],
[[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [2, 0, 1]],
[[0, 0, 0], [-2, 1, 0], [-1, 1, 0], [0, 1, 0], [1, 1, 0]],
[[0, 0, 0], [-1, 1, 0], [0, 1, 0], [1, 1, 0], [2, 1, 0]],
[[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [-1, 1, 0]],
[[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 1, 1]],
[[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [1, 1, 0]],
[[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [-1, 2, 0]],
[[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 2, 1]],
[[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [1, 2, 0]],
[[0, 0, 0], [0, 0, 1], [-2, 0, 1], [-1, 0, 1], [1, 0, 1]],
[[0, 0, 0], [0, 0, 1], [-1, 0, 1], [1, 0, 1], [2, 0, 1]],
[[0, 0, 0], [0, 0, 1], [0, -2, 1], [0, -1, 1], [0, 1, 1]],
[[0, 0, 0], [0, 0, 1], [0, -1, 1], [0, 1, 1], [0, 2, 1]],
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [-1, 0, 1]],
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, -1, 1]],
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [1, 0, 1]],
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 1]],
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [-1, 0, 2]],
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, -1, 2]],
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [1, 0, 2]],
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 2]]
]
def print_cube():
for level in Cube:
for row in level:
print(row)
print()
print("-" * 15)
def remove_piece(n):
for z in range(0, HEIGHT):
for y in range(0, DEPTH):
for x in range(0, WIDTH):
if Cube[z][y][x] == n:
Cube[z][y][x] = 0
def insert_piece(x, y, z, c, n):
config = Configurations[c]
# Check if the piece fits
for b in config:
x_b = x + b[0]
y_b = y + b[1]
z_b = z + b[2]
# Out of bounds
if (x_b < 0) or (x_b >= WIDTH) or (y_b < 0) or (y_b >= DEPTH) or (z_b < 0) or (z_b >= HEIGHT):
return False
# Slot taken
if Cube[z_b][y_b][x_b] != 0:
return False
# Insert piece
for b in config:
Cube[z+b[2]][y+b[1]][x+b[0]] = n
return True
def find_pos():
for z in range(0, HEIGHT):
for y in range(0, DEPTH):
for x in range(0, WIDTH):
if Cube[z][y][x] == 0:
return[x, y, z]
def find_solution(n):
if n > 25:
print_cube()
return
[x, y, z] = find_pos()
for c in range(len(Configurations)):
if insert_piece(x, y, z, c, n):
find_solution(n+1)
remove_piece(n)
find_solution(1)