Last active
February 12, 2026 14:56
-
-
Save tribela/16df907f8bf42885514f8f5eb02bf790 to your computer and use it in GitHub Desktop.
Hanoi tower, without recursion, Just state -> next state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pytest | |
| def step_parity(state: list[int]) -> bool: | |
| prev = 0 | |
| for p in reversed(state): # From biggest disk to smallest | |
| if p != prev: | |
| prev = 3 - p - prev | |
| return p == prev | |
| def next_move(state: list[int]) -> list[int]: | |
| n = len(state) | |
| state = state.copy() | |
| if step_parity(state): | |
| # Time to move the smallest disk | |
| direction = -1 if n % 2 == 1 else 1 | |
| state[0] = (state[0] + direction) % 3 | |
| return state | |
| else: | |
| # Move the next smallest disk that can be moved | |
| disk_to_move = next(i for i in range(1, n) if state[i] != state[0]) | |
| state[disk_to_move] = 3 - state[disk_to_move] - state[0] | |
| return state | |
| def test_all(): | |
| answers = ( | |
| ( | |
| [0, 0, 0], | |
| [2, 0, 0], | |
| [2, 1, 0], | |
| [1, 1, 0], | |
| [1, 1, 2], | |
| [0, 1, 2], | |
| [0, 2, 2], | |
| [2, 2, 2], | |
| ), ( | |
| [0, 0], | |
| [1, 0], | |
| [1, 2], | |
| [2, 2], | |
| ), | |
| ) | |
| for answer in answers: | |
| for index, state, next_state in zip(range(len(answer)), answer, answer[1:]): | |
| assert next_move(state) == next_state, f"Failed at index {index}" | |
| assert step_parity(state) == (index % 2 == 0), f"Parity failed at index {index}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment