Skip to content

Instantly share code, notes, and snippets.

@mnagy
Created June 17, 2013 06:17
Show Gist options
  • Save mnagy/5794927 to your computer and use it in GitHub Desktop.
Save mnagy/5794927 to your computer and use it in GitHub Desktop.
Script that solves the wooden snake cube puzzle.
#!/usr/bin/env python3
directions = [
(1, 0, 0), (0, 1, 0), (0, 0, 1),
(-1, 0, 0), (0, -1, 0), (0, 0, -1),
]
def new_position(position, direction, length):
length -= 1
new_pos = [pos + dir*length for pos, dir in zip(position, direction)]
for coord in new_pos:
if not 0 <= coord < 3:
return None
return new_pos
def clone_state(state):
new_state = []
for x in state:
new_row = []
new_state.append(new_row)
for y in x:
new_col = []
new_row.append(new_col)
for z in y:
new_col.append(z)
return new_state
def modify_state(state, pos, direction, length):
"""Return a new state, if valid, othrewise return None."""
new_pos = new_position(pos, direction, length)
if not new_pos:
return None
state = clone_state(state)
# Don't count the first one, which will already
# be set to 1.
length -= 1
while length:
x = pos[0] + direction[0] * length
y = pos[1] + direction[1] * length
z = pos[2] + direction[2] * length
if state[x][y][z] == 1:
return None
state[x][y][z] = 1
length -= 1
return state, new_pos
def crack(state, position, lens):
global directions
if len(lens) == 0:
return []
for direction in directions:
state_pos = modify_state(state, position, direction, lens[0])
if not state_pos:
continue
new_state, new_pos = state_pos
dirs = crack(new_state, new_pos, lens[1:])
if dirs is not None:
dirs.insert(0, direction)
return dirs
return None
if __name__ == "__main__":
lengths = [3, 2, 2, 3, 2, 3, 2, 2, 3, 3, 2, 2, 2, 3, 3, 3, 3]
state = [
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
]
# Try all posible initial states
for x in range(3):
for y in range(3):
for z in range(3):
state[x][y][z] = 1
res = crack(state, (x, y, z), lengths)
if res:
print(state)
print(res)
print()
state[x][y][z] = 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment