Re:Ask HN: What's your favorite elegant/beautiful algorithm?
by laurentl on Wednesday October 17, 2018 @11:22AM
(#18239952)
Nitpick: this only works if the player played exactly three moves (in the version of Tic Tac Toe I know you can play for up to 5 moves). Generalizing to 4 moves is fairly simple, to 5 moves less so; you can test all '3 from 5' combinations, which is only 10 possibilities, but I doubt the code to do this is easy to read and understand after the fact.
[ Parent
| on HN ]
Re:Ask HN: What's your favorite elegant/beautiful algorithm?
by chrisshroba on Wednesday October 17, 2018 @11:53AM
(#18240251)
I'd disagree here; I still think it's quite elegant. For example, in python, it would look something like
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