solve() function
This commit is contained in:
parent
35859acb27
commit
1b18b19c85
2 changed files with 51 additions and 7 deletions
|
@ -1,18 +1,23 @@
|
||||||
#!/usr/bin/python3
|
#!/usr/bin/python3
|
||||||
|
|
||||||
from .board import Board
|
from .board import Board
|
||||||
|
from .solver import solve
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
board = Board.default_puzzle
|
solution = solve(
|
||||||
print(board)
|
Board.default_puzzle,
|
||||||
print(board.solution_class, board.binary_repr)
|
lambda state: state.solution_class == (3, 1, 2),
|
||||||
|
)
|
||||||
|
|
||||||
for btn in (2, 4, 5, 7): # 2 is not a regular button, but alas
|
if solution is None:
|
||||||
|
print("Unsolvable!")
|
||||||
|
return
|
||||||
|
|
||||||
|
for btn, state in solution:
|
||||||
print(f"clicking button {btn} ...")
|
print(f"clicking button {btn} ...")
|
||||||
board.click(btn)
|
print(state)
|
||||||
print(board)
|
print(state.solution_class, state.binary_repr)
|
||||||
print(board.solution_class, board.binary_repr)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
39
pigeon_magnet_solver/solver.py
Normal file
39
pigeon_magnet_solver/solver.py
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from .board import Board
|
||||||
|
|
||||||
|
|
||||||
|
def solve(
|
||||||
|
state: Board,
|
||||||
|
is_solved: Callable[[Board], bool],
|
||||||
|
*,
|
||||||
|
history: list[tuple[int, Board]] | None = None,
|
||||||
|
) -> list[tuple[int, Board]] | None:
|
||||||
|
|
||||||
|
if history is None:
|
||||||
|
# create starting state
|
||||||
|
history = [(-1, state)]
|
||||||
|
|
||||||
|
if is_solved(state):
|
||||||
|
return history
|
||||||
|
|
||||||
|
for button in state.buttons:
|
||||||
|
# try to click all buttons
|
||||||
|
next = state.click(button)
|
||||||
|
|
||||||
|
if next is not None:
|
||||||
|
# click successful
|
||||||
|
binary_history = (
|
||||||
|
state.binary_repr
|
||||||
|
for _, state in history
|
||||||
|
)
|
||||||
|
|
||||||
|
if next.binary_repr not in binary_history:
|
||||||
|
# "next" is a new state
|
||||||
|
solution = solve(
|
||||||
|
next, is_solved,
|
||||||
|
history=[*history, (button, next)]
|
||||||
|
)
|
||||||
|
|
||||||
|
if solution is not None:
|
||||||
|
return solution
|
Loading…
Reference in a new issue