1

I am trying to solve Euler 18 in Dyalog APL, and I am not able to understand why my solution does not work.

The problem is as follow:

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

   3 
  7 4 
 2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Taking the example that I represent this way:

d ← (3 0 0 0)  (7 4 0 0)  (2 4 6 0)  (8 5 9 3) 

I am trying to solve it this way:

{⍵+((2⌈/⍺)),0}/⌽d

Which gives me this array: 22 19 15 0, where the bigger number is 22, which is not the right answer for the problem, which would be 23.

I am getting this behavior (left to right for ease of reading):

(2⌈/(8 5 9 3),0)+(2⌈/(2 4 6 0),0)+(2⌈/(7 4 0 0),0)+(2⌈/(3 0 0 0),0)

Which gives me the same result as the function.

What I would expect is this behavior (where each statement is substituted directly in the next line):

    (2⌈/(8 5 9 3)),0
(2 4 6 0)+8 9 9 0
    (2⌈/(10 13 15 0)),0
(7 4 0 0)+13 15 15 0
    (2⌈/(20 19 15 0)),0
(3 0 0 0) + 20 19 15 0
23 19 15 0

Am I wondering where I am misunderstanding something in the APL process that leads to a different result than the one I am expecting.

Thank you!

Adám
  • 6,573
  • 20
  • 37
gabc
  • 23
  • 3
  • Can you add the description of Problem 18 to the question? Even a single sentence such as "I need to find the sum of the maximum element selected from each subarray" would be helpful, as the link doesn't lead to problem 18 directly. – user Jun 04 '21 at 23:42
  • That is a good point, I did add the description, but I can't seem to fix the issue with the link, it showed me the archive page the first time I clicked on it and afterwards it is alright. – gabc Jun 05 '21 at 12:11

1 Answers1

4

/ works in the reverse way to what you expected - it evaluates through the array right-to-left.

F/a b c d is ⊂a F b F c F d, or, with parentheses, ⊂(a F (b F (c F d))).

After removing the and swapping and , you get {⍺+(2⌈/⍵),0}/d, which gives the result you want.

user
  • 7,435
  • 3
  • 14
  • 44
dzaima
  • 388
  • 3
  • 9
  • The OP also doesn't need to append a zero at each step and pad each row ([TIO](https://tio.run/##SyzI0U2pTMzJT/8PBCkKj9omKGjoGGsqaJgrmGgqKGgYKZgomIEYFgqmCpYKxppcXNWPendpGz3q6dB/1Lu1Vj8FAA)) – user Jun 05 '21 at 15:06