I was trying out Project Euler Problem 10.
The problem asks you to multiply all adjacent numbers which are horizontally, vertically, or diagonally connected. Here is a link to the problem.
Basically, how would you create a two-dimensional array and define it?
Is a two-dimensional array needed?
Can I do it a better way?
Python does not have arrays like in C, unless you install the Numpy library (which I recommend if you are trying to work mathematical and numerical processing problems). Numpy is not necessary to solve this problem. If you want a 2D array you can use nested lists: each row is a list, like this:
board = [[10, 12, 5, 7, ...], [24, 3, 7, 8, ...] ... ]
Then you can index the numbers as board[0][3]
, which would be a 7
(first row, fourth element). You can find a lot more about this in the Python tutorial.
For that particular problem you probably don't even need a two dimensional array. You know the dimension of the board so you can get away with a linear array (e.g. all rows flattened in a 400 element array). Then just by adding you can index in any direction; adding +1/-1 will get the adjacent elements (same row), adding +20/-20 will get the next/previous row elements; adding 21 will move diagonally, etc.
You need to pay some attention to borders: one thing that is not well specified in the problem formulation is what happens at the borders, i.e. do you wrap up or simply stop? Probably the latter.