Skip to content

Instantly share code, notes, and snippets.

@dhermes
Created January 2, 2025 15:22
Show Gist options
  • Save dhermes/71d4f0e7ad661ce9a97a06da32ebaa95 to your computer and use it in GitHub Desktop.
Save dhermes/71d4f0e7ad661ce9a97a06da32ebaa95 to your computer and use it in GitHub Desktop.
[2025-01-02] Chessboard parity (odd/even sums across rows and columns)
# See: https://www.youtube.com/watch?v=EONem7cdmSM
import fractions
import numpy as np
def even_sum(m, n):
for i in range(n):
s = sum(m[i, :])
if s % 2 != 0:
return False
for j in range(n):
s = sum(m[:, j])
if s % 2 != 0:
return False
return True
def chessboard_parity(n):
s = n**2
match_count = 0
total_count = 0
for i in range(2**s):
as_bin = bin(i)[2:].zfill(s)
d = [int(c) for c in as_bin]
m = np.array(d).reshape((n, n))
total_count += 1
if even_sum(m, n):
match_count += 1
f = fractions.Fraction(match_count, total_count)
expected = fractions.Fraction(2, 4**n)
print(f"n = {n}: {match_count}/{total_count} = {f} (expected: {expected})")
def main():
chessboard_parity(3)
chessboard_parity(4)
chessboard_parity(5)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment