Last active
December 16, 2023 10:00
-
-
Save k12ish/484222999a0cc43eb1c3cdbf2e3b2bb0 to your computer and use it in GitHub Desktop.
Knights Move Puzzle (with Sympy!!)
This file contains 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
from sympy import symbols, solve, Eq | |
def knight_moves(x, y, board_size=8): | |
moves = [ | |
(x + 1, y + 2), | |
(x + 1, y - 2), | |
(x - 1, y + 2), | |
(x - 1, y - 2), | |
(x + 2, y + 1), | |
(x + 2, y - 1), | |
(x - 2, y + 1), | |
(x - 2, y - 1), | |
] | |
return [(i, j) for i, j in moves if 0 <= i < board_size and 0 <= j < board_size] | |
squares = [symbols(f"{col}1:9") for col in "abcdefgh"] | |
def equations(): | |
for i in range(8): | |
for j in range(i, 8): | |
# symmetry condition along diagonal | |
yield Eq(squares[i][j], squares[j][i]) | |
if (i, j) == (7, 7): | |
# the final square is the destination, and is set to zero | |
yield Eq(squares[-1][-1], 0) | |
else: | |
# every other square is equal to 1 + (∑ neighbour ) / len(neighbours) | |
possible_moves = knight_moves(i, j) | |
yield Eq( | |
squares[i][j], | |
1 | |
+ sum(squares[x][y] for x, y in possible_moves) | |
/ len(possible_moves), | |
) | |
print(solve(list(equations()))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The rough idea behind our solution is this equation for the expected distance between nodes:
Here, we generate 64 equations procedurally, and solve it with Sympy!
Script output: