#Put your own folding sequences here:
FOLD_SEQUENCES = """
20*20R1D1R1D1R1D1R1D1
40*20R1D1R1D1R1D1R1D1
40*40R1D1R1D1R1D1R1D1
20*80R1D1R1D1R1D1R1D1
"""
import re
def foldRight(grid, n):
h, w = len(grid), len(grid[0])
for y in range(h):
for offset in range(min(n, w - n)):
c1 = grid[y][n + offset]
c2 = grid[y][n - offset - 1]
avg = 0.5 * (c1 + c2)
grid[y][n + offset] = avg
grid[y][n - offset - 1] = avg
def foldDown(grid, n):
h, w = len(grid), len(grid[0])
for x in range(w):
for offset in range(min(n, h - n)):
c1 = grid[n + offset][x]
c2 = grid[n - offset - 1][x]
avg = 0.5 * (c1 + c2)
grid[n + offset][x] = avg
grid[n - offset - 1][x] = avg
def foldGrid(grid, fold):
if fold[0] == 'R':
foldRight(grid, fold[1])
else:
foldDown(grid, fold[1])
def gridAvg(grid):
total = 0.0
for row in grid:
total += sum(row)
return total / (len(grid) * len(grid[0]))
def calcScore(grid, foldSeq):
avg = gridAvg(grid)
for fold in foldSeq:
foldGrid(grid, fold)
score = 0
for row in grid:
for cell in row:
score += abs(cell - avg)
return score
def calcAllScores():
grids = getGrids()
foldSeqs = dict(map(parseFoldSeq, FOLD_SEQUENCES.strip().split('\n')))
if len(foldSeqs) != len(grids):
return None
scores = {}
total = 0
for title in grids:
score = calcScore(grids[title], foldSeqs[title])
total += score
scores[title] = score
return scores, total
def parseFold(foldStr):
return foldStr[0], int(foldStr[1:])
def parseFoldSeq(foldSeqStr):
pattern = r'(\d+\*\d+)' + 8 * r'([RD]\d+)'
data = re.search(pattern, foldSeqStr).groups()
title = data[0]
foldSeq = map(parseFold, data[1:])
return title, foldSeq
def parseRow(rowStr):
row = []
for c in rowStr:
if c == '0':
row.append(0)
elif c == '1':
row.append(1)
return row
def parseGrid(gridStr): #grids are indexed by y then x
rows = gridStr.split('\n')
title = rows[0]
grid = map(parseRow, rows[1:])
return title, grid
def getGrids():
g1 = """20*20
1 1 1 0 1 1 0 0 1 0 0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0 1 0 1 0 0 1 0 1 1
1 1 1 1 1 1 1 0 1 0 0 0 0 1 1 0 0 0 1 1
0 0 0 1 1 0 1 1 1 1 0 1 1 0 1 0 0 0 1 0
0 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 0
0 0 1 1 1 0 1 1 0 0 1 1 0 1 0 0 1 0 1 0
1 0 1 1 1 1 1 1 1 0 0 1 0 1 0 1 0 0 1 1
1 1 0 1 0 1 0 1 0 1 1 0 0 0 0 1 1 1 1 0
0 0 0 1 0 1 0 1 1 1 0 1 0 0 1 0 0 1 0 0
0 1 1 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 1 0
1 1 0 0 1 1 0 0 1 1 0 0 0 1 0 1 1 0 1 1
1 0 1 0 0 0 1 0 0 1 1 1 0 1 0 0 0 0 0 0
1 0 1 1 0 1 1 0 0 1 1 1 0 0 1 1 0 1 1 0
0 0 1 0 1 0 0 1 1 1 0 1 0 1 1 0 1 0 0 0
0 1 0 1 1 0 1 1 1 1 0 1 1 1 1 0 1 0 0 1
1 0 1 0 1 1 0 0 1 0 0 0 1 0 0 1 0 1 0 1
0 1 0 0 1 0 1 0 1 1 1 0 0 0 1 0 1 0 1 1"""
return dict(map(parseGrid, [g1, g2, g3, g4]))
scores, total = calcAllScores()
print 'Total Score:', total
print 'Individual Scores:'
for title in scores:
print title, scores[title]