by rodovich · 8y ago · 0 comments
Several years later I saw a Matlab demo that did this by indexing the grid using values from a 3x3 magic square[1]. In a magic square, every row, column, and diagonal has the same sum. So checking for a winner was just checking if a player’s three moves added up to 15. Finding a space that would make the computer win, or block the human opponent from winning, was subtracting two moves from 15 and checking if that spot was available.
I wonder if this is true of larger magic squares.
Some Python:
from collections import Counter
from itertools import combinations
def number_of_sums(n, M):
combs = combinations(range(1,n**2+1), n)
sums = (sum(c) for c in combs)
return Counter(sums)[M]
print(number_of_sums(3, 15))
print(number_of_sums(4, 34))238, 22, 494
21, 10659, 39
665, 55, 1105
so checking for a winner was equivalent to checking if the gcd of a player’s spaces was greater than 1.
Much less efficient! But it looks like I was on the right track in searching for compact numerical alternatives to traversing the board and measuring strides.
Edit: fixed an arithmetic error
from itertools import combinations
magic_square = [2,7,6,
9,5,1,
4,3,8]
def did_user_win(moves):
# Convert moves to magic square values
magic_values = [magic_square[move] for move in moves]
# Check if any sum of three moves equals 15
for three_values in combinations(magic_values,3):
if sum(three_values) == 15: return True
return False