Skip to content

Instantly share code, notes, and snippets.

@svineet
Created September 21, 2013 09:33
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 svineet/6648909 to your computer and use it in GitHub Desktop.
Save svineet/6648909 to your computer and use it in GitHub Desktop.
Google Code Jam problem - "Tic-Tac-Toe-Tomek" Link to problem - https://code.google.com/codejam/contest/2270488/dashboard
#!/usr/bin/python
X = "X"
O = "O"
T = "T"
cases = ["",
"X won",
"Draw",
"Game has not completed",
"O won"]
input_file_name = "A-small-practice.in"
def runtests(rows):
# Horizontal tests
for i in range(0,len(rows)):
countx, counto, countt = 0, 0 , False
for j in range(0,4):
cc = rows[i][j] # Current Character
if cc == X:
countx += 1
elif cc == O:
counto += 1
elif cc == T:
countt = True
if countx == 4 or (countx == 3 and countt):
return 1
if counto == 4 or (counto == 3 and countt):
return 4
# Vertical tests
for j in range(0,4):
countx, counto, countt = 0, 0 , False
for i in range(0,4):
cc = rows[i][j] # Current Character
if cc == X:
countx += 1
elif cc == O:
counto += 1
elif cc == T:
countt = True
if countx == 4 or (countx == 3 and countt):
return 1
if counto == 4 or (counto == 3 and countt):
return 4
# Diagonal test 1
countx, counto, countt = 0, 0 , False
for i in range(0,4):
j = i
cc = rows[i][j] # Current Character
if cc == X:
countx += 1
elif cc == O:
counto += 1
elif cc == T:
countt = True
if countx == 4 or (countx == 3 and countt):
return 1
if counto == 4 or (counto == 3 and countt):
return 4
# Diagonal test 2
countx, counto, countt = 0, 0 , False
for i in range(0,4):
j = 3-i
cc = rows[i][j] # Current Character
if cc == X:
countx += 1
elif cc == O:
counto += 1
elif cc == T:
countt = True
if countx == 4 or (countx == 3 and countt):
return 1
if counto == 4 or (counto == 3 and countt):
return 4
for i in range(0,4):
for j in range(0,4):
cc = rows[i][j]
if cc == ".":
return 3
return 2
# Parse file and test cases in to list.
with open(input_file_name) as inputfile:
fparsed = inputfile.read().split('\n')
numcases = fparsed[0]
fparsed.remove(numcases)
# Create list of all useful lines(rows of game)
caselist = []
for i in range(0,len(fparsed)):
if fparsed[i]!='':
caselist.append(fparsed[i])
# Run test for each game state(4 rows)
of = open("output.txt","w")
for i in range(0,len(caselist),4):
of.write("Case #"+str((i/4)+1)+": "+cases[runtests(caselist[i:i+4])] + "\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment