Skip to content

Instantly share code, notes, and snippets.

@Celeo
Last active August 19, 2018 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Celeo/6df2ea81a0c06d206947250cbc24628a to your computer and use it in GitHub Desktop.
Save Celeo/6df2ea81a0c06d206947250cbc24628a to your computer and use it in GitHub Desktop.
Tic-tac-toe simple solver
from tictactoe import check
TESTCASES = {
'#########': '#',
'XXX######': 'X',
'###XXX###': 'X',
'######XXX': 'X',
'X##X##X##': 'X',
'#X##X##X#': 'X',
'##X##X##X': 'X',
'X###X###X': 'X',
'##X#X#X##': 'X',
'OOO######': 'O',
'###OOO###': 'O',
'######OOO': 'O',
'O##O##O##': 'O',
'#O##O##O#': 'O',
'##O##O##O': 'O',
'O###O###O': 'O',
'##O#O#O##': 'O'
}
def test_check():
for data, expected in TESTCASES.items():
assert check(data) == expected
import sys
# Layout, in terms of array indexes:
# 012
# 345
# 678
VALID_WINS = [
'012',
'345',
'678',
'036',
'147',
'258',
'048',
'246'
]
def check(data):
for condition in VALID_WINS:
indexes = [int(e) for e in condition]
if data[indexes[0]] == data[indexes[1]] == data[indexes[2]] and data[indexes[0]] != '#':
return data[indexes[0]]
return '#'
if __name__ == '__main__':
test_data = sys.stdin.readline().strip()
print(check(test_data))
@Celeo
Copy link
Author

Celeo commented Aug 19, 2018

Requires pytest to run the tests, or a bit of manual work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment