Hi Everyone,
I’m about two weeks in to Elixir and have gotten stuck on understanding the triangle path code from rosetta code:
defmodule Maximum do
def triangle_path(text) do
text
|> String.split("\n", trim: true)
|> Enum.map(fn line ->
line
|> String.split()
|> Enum.map(&String.to_integer(&1))
end)
|> Enum.reduce([], fn x,total ->
[0]++total++[0]
|> Enum.chunk_every( 2, 1)
|> Enum.map(&Enum.max(&1))
|> Enum.zip(x)
|> Enum.map(fn{a,b} -> a+b end)
end)
|> Enum.max()
end
end
Basically I’ve deconstructed it line by line and adding one line at a time to see how it progresses. It’s all ok until I get to Enum.reduce where I pipe the following data to it:
iex> c = [[1], [2, 3], [4, 5, 6]]
iex> c |> Enum.reduce(, fn x, total → [0]++total++[0] end)
[0, 0, 0, 0, 0, 0]
Trying to figure out why it’s all zeros, but the number of elements is equal so I sort of see the pattern.
Then:
iex> c |> Enum.reduce(, fn x, total → [0]++total++[0] |> Enum.chunk_every(2,1) end)
[
[0, [0, [0, 0]]],
[[0, [0, 0]], [[0, 0], [0]]],
[[[0, 0], [0]], [[0], 0]],
[[[0], 0], [0]],
[[0], 0],
[0]
]
This seems to be a recursive chunking, which I can sort of understand
next:
iex> c |> Enum.reduce(, fn x, total → [0]++total++[0] |> Enum.chunk_every(2,1) |> Enum.map(&Enum.max(&1)) end)
[0, 0, 0, 0, 0, 0]
Now I’m starting to get lost as I’m not sure why we’re calling map on max since it’s all zeroes
Then finally:
c |> Enum.reduce(, fn x, total → [0]++total++[0] |> Enum.chunk_every(2,1) |> Enum.map(&Enum.max(&1)) |> Enum.zip(x) end)
[{{{0, 1}, 2}, 4}, {{{0, 1}, 3}, 5}, {{{0, 1}, 3}, 6}]
Now I’m really confused as the numbers appear and appear in the right order as well. Not all elements appear tho, for example, there’s no 1,2,5 which is a valid path.
I’m missing something here and I’m not so sure what it is, can someone please explain to how this code does what it does?