I’m currently working on a project Euler problem (www.projecteuler.net) for fun but have hit a stumbling block. One of the problem provides a 20×20 grid of numbers and asks for the greatest product of 4 numbers on a straight line. This line can be either horizontal, vertical, or diagonal.
Using a procedural language I’d have no problem solving this, but part of my motivation for doing these problems in the first place is to gain more experience and learn more Haskell.
As of right now I’m reading in the grid and converting it to a list of list of ints, eg — [[Int]]. This makes the horizontal multiplication trivial, and by transposing this grid the vertical also becomes trivial.
The diagonal is what is giving me trouble. I’ve thought of a few ways where I could use explicit array slicing or indexing, to get a solution, but it seems overly complicated and hackey. I believe there is probably an elegant, functional solution here, and I’d love to hear what others can come up with.
I disagree with the estimable Don Stewart. Given the combinatorial nature of the problem and the fact that the problem size is only 20×20, lists of lists are going to be plenty fast enough. And the last thing you want is to futz around with array indexing. Instead I suggest that you extend the techniques developed by Richard Bird in his justly famous sudoku solver. To be more specific, I’d suggest the following:
Write a function that given a sequence, returns all contiguous subsequences of length 4.
Write a function that given a grid, returns all rows.
Write a function that given a grid, returns all columns.
Write a function that given a grid, returns all diagonals.
With these functions in hand, your solution will be easy. But as you mention the diagonal is not so obvious. What is a diagonal anyway?
Let’s look at an example:
Suppose for a moment that you use the
dropfunction and you drop 0 elements from row 0, 1 element from row 1, and so on. Here’s what you wind up with:The elements of the diagonal now form the first column of the triangular thing you have left. Even better, every column of the thing you have left is a diagonal of the original matrix. Throw in a few symmetry transformations and you’ll easily be able to enumerate all the diagonals of a square matrix of any size. Whack each one with your “contiguous subsequences of length 4” function, and Bob’s your uncle!
A little more detail for those who may be stuck:
The key to this problem is composition. Diagonals come in four groups. My example gives one group. To get the other three, apply the same function to the mirror image, the transpose, and the mirror image of the transpose.
Transpose is a one-line function, and you need it anyway to recover columns cleanly.
Mirror image is even simpler than transpose—think about what functions you can use from the Prelude.
The symmetry method will give each major diagonal twice; luckily for the problem stated it’s OK to repeat a diagonal.