project-euler/149_searching_for_maxsum_su...

58 lines
1.3 KiB
Python
Raw Normal View History

2023-03-26 17:21:44 +02:00
#!/usr/bin/env python3
def search_row(row):
row = [a for a in row]
for i in range(1, len(row)):
prev, val = row[i-1], row[i]
row[i] = max(prev + val, val)
return max(row)
def search_rows(grid):
return max(search_row(row) for row in grid)
def search_diagonals(grid):
ln = len(grid)
m = 0
for d in range(-ln + 1, ln):
r = search_row([grid[i][i+d]
for i in range(ln) if 0 <= i+d < ln])
m = max(m, r)
return m
def fib_gen(k, mem):
if len(mem) > k and mem[k] != None:
return mem[k]
elif k < 56:
s = 100003 - 200003*k + 300007*k**3
s %= 1000000
s -= 500000
else:
s = (fib_gen(k-24, mem) + fib_gen(k-55, mem) + 1000000) % 1000000
s -= 500000
mem += [None] * (k - len(mem) + 1)
mem[k] = s
return s
grid2 = [[-2, 5, 3, 2],
[9, -6, 5, 1],
[3, 2, 7, 3],
[-1, 8, -4, 8]]
mem = []
side = 2000
grid = [[0]*side for i in range(side)]
for ri in range(side):
for ci in range(side):
grid[ri][ci] = fib_gen(side*ri + ci + 1, mem)
rows = search_rows(grid)
cols = search_rows(zip(*grid))
dia1 = search_diagonals(grid)
dia2 = search_diagonals([row[::-1] for row in grid])
print(max(rows, cols, dia1, dia2))