You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
35 lines
1.1 KiB
Elixir
35 lines
1.1 KiB
Elixir
defmodule Day7 do
|
|
def run do
|
|
lines =
|
|
File.read!("data.txt")
|
|
|> String.trim()
|
|
|> String.split("\n")
|
|
|> Enum.map(fn l -> String.split(l, ~r{\D+}) |> Enum.map(&String.to_integer(&1)) end)
|
|
|> Enum.map(fn [head | tail] -> {head, tail} end)
|
|
|
|
[
|
|
# part 1's operatons: * and +
|
|
[&*/2, &+/2],
|
|
# part 2's operatons: *, +, and concat
|
|
[&*/2, &+/2, &("#{&1}#{&2}" |> String.to_integer())]
|
|
]
|
|
|> Enum.map(fn ops ->
|
|
# filter valid lines for parts 1 and 2, grab their targets, and sum them
|
|
Enum.filter(lines, &valid?(&1, ops)) |> Enum.map(&elem(&1, 0)) |> Enum.sum()
|
|
end)
|
|
|> Enum.map(&dbg(&1))
|
|
end
|
|
|
|
# base case, when there are 2 operands. returns true if applying any of the ops returns the target
|
|
defp valid?({total, [a, b]}, ops) do
|
|
Enum.any?(ops, fn op -> op.(a, b) == total end)
|
|
end
|
|
|
|
# apply each operation to the first two operands, prepend and recurse
|
|
defp valid?({total, [a, b | rest]}, ops) do
|
|
Enum.any?(ops, fn op -> valid?({total, [op.(a, b) | rest]}, ops) end)
|
|
end
|
|
end
|
|
|
|
Day7.run()
|