In order to solve the 18th Euler problem, I used a
lookahead function that tries to find out which position to choose in the
current level of the triangle based on the next level. It also uses the last
position used in order to pick the right values in the next levels of the
triangle. First, I defined both triangles using a list of lists, as one can
see below.
Then, I created a few utility functions that I thought I could use, such as
maxValue, which returns the position of the best number among 2; the
indexOf, which btw I am not very proud of, that returns the position of a
given number in a list (note: although one should never define such a function
like that, I am sure I will find an element in that list, so the result will
always be correct); and finally maxOf, which tells the lookahead
function which position it should return based on the next level of the
triangle. Here are the definitions:
The lookahead calculates the sum of the relevant values in the current and
next level of the triangle, and returns the best position to choose:
Finally, it was a matter of assembling everything:
The interpreter returned the following output, when I executed the total
function: (0.03 secs, 4125124 bytes) Although it is not a pretty solution, it
solved the problem relatively fast. Now I will try it in problem 67, where there are
299 possible routes!