2017-06-13

Project Euler Problem 11

First let's format the grid to fit in a list. I do this by copying it into Excel and replace all " " with "," and then copy it into a list. Since the position in the grid matters, actually I might need a two dimensional list. How do they work? Stack overflow helps out.

Now that I've though about it, there must be a better way of reading data into a Python list. And there is! I copy the data into a textfile and then read the textfile.


lines = []

with open('pe11.txt') as file:
    for line in file:
        lines = file.read().splitlines()

This is not enough though, I want a two dimensional matrix. I need to know how to add space separated values from a textfile to a Python list.







with open('pe11.txt', 'r') as file:
    lines = [[int(num) for num in line.split()] for line in file]

product = 1rowProduct = 1colProduct = 1diaDownProduct = 1diaUpProduct = 1
for row in range(0, 20):
    for col in range(0, 17):
        newProduct = lines[row][col] * lines[row][col + 1] * lines[row][col + 2] * lines[row][col + 3]
        if newProduct > rowProduct:
            rowProduct = newProduct
            rowResult = [lines[row][col], lines[row][col + 1], lines[row][col + 2], lines[row][col + 3], 'row:', row, 'col', col, 'row product', rowProduct]

for col in range(0, 20):
    for row in range(0, 17):
        newProduct = lines[row][col] * lines[row + 1][col] * lines[row + 2][col] * lines[row + 3][col]
        if newProduct > colProduct:
            colProduct = newProduct
            colResult = [lines[row][col], lines[row + 1][col], lines[row + 2][col], lines[row + 3][col], 'row:', row, 'col', col, 'col product', colProduct]

for row in range(0, 17):
    for col in range(0, 17):
        newProduct = lines[row][col] * lines[row + 1][col + 1] * lines[row + 2][col + 2] * lines[row + 3][col + 3]
        if newProduct > diaDownProduct:
            diaDownProduct = newProduct
            diaDownResult = [lines[row][col], lines[row + 1][col + 1], lines[row + 2][col + 2], lines[row + 3][col + 3], 'row:', row, 'col', col, 'dia down product', diaDownProduct]

for row in range(0, 17):
    for col in range(0, 17):
        newProduct = lines[row + 3][col] * lines[row + 2][col + 1] * lines[row + 1][col + 2] * lines[row][col + 3]
        if newProduct > diaUpProduct:
            diaUpProduct = newProduct
            diaUpResult = [lines[row + 3][col], lines[row + 2][col + 1], lines[row + 1][col + 2], lines[row][col + 3], 'row:', row, 'col', col, 'dia up product', diaUpProduct]

print(rowResult, "\n", colResult, "\n", diaDownResult, "\n", diaUpResult)

resultList = [rowProduct, colProduct, diaDownProduct, diaUpProduct]
print(max(resultList))


The codes are growing! It feels like this problem should be solvable in a more elegant way both mathematically and programatically. I'll go with this solution for now and maybe turn back in the future to try a new way (if I learn one).

/Ludvig

No comments:

Post a Comment