Created
November 22, 2014 18:53
-
-
Save pqcfox/5dc89d016138c66f672e to your computer and use it in GitHub Desktop.
A piece of code to find the optimal strategy for placing tokens on a n by n board without getting a n-token line on a row or diagonal.
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
import itertools, math | |
# Determines the width/height of a square board. | |
def size(board): | |
return int(math.sqrt(len(board))) | |
# Determines whether a flat bingo board (list of length size**2) has five | |
# in a row on any row, column, or diagonal. | |
def bingo(board): | |
s = size(board) | |
for i in range(s): | |
row = [ board[j + i * s] for j in range(s) ] | |
col = [ board[i + j * s] for j in range(s) ] | |
if all(row) or all(col): | |
return True | |
left_diag = [ board[j + s * j] for j in range(s) ] | |
right_diag = [ board[ ((s - 1) - j) + s * j ] for j in range(s) ] | |
if all(left_diag) or all(right_diag): | |
return True | |
return False | |
# Displays the board on the terminal using the mapping defined in symbols. | |
def display(board): | |
s = size(board) | |
symbols = { False: 'o', True: 'x' } | |
for i in range(s): | |
print ''.join([ symbols[board[j + i * s]] for j in range(s) ]) | |
s = 5 | |
boards = itertools.product([False, True], repeat=s**2) | |
valids = filter(lambda b: not bingo(b), boards) | |
highest = max([ board.count(True) for board in valids ]) | |
for board in [ board for board in valids if board.count(True) == highest ]: | |
display(board) | |
print '\n' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment