defmodule Day7 do def run do lines = File.read!("test.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) [part1, part2] = Enum.map([1, 2], fn part -> # filter valid lines for parts 1 and 2, grab their targets, and sum them Enum.filter(lines, &valid?(&1, part)) |> Enum.map(&elem(&1, 0)) |> Enum.sum() end) dbg({part1, part2}) end defp valid?({total, [a, b | rest]}, part) do # if we're in part 1, just check a * b and a + b. in part 2, we'll also check a <> b branches = if part == 1, do: [a * b, a + b], else: [a * b, a + b, concat(a, b)] case [a, b | rest] do # base case is 2 elements. if any succeed, return true [_, _] -> Enum.any?(branches, fn n -> n == total end) # recurse by trying each branch, subbing the first 2 elements with the new combined element [_, _ | _] -> Enum.any?(branches, &valid?({total, [&1 | rest]}, part)) end end defp concat(a, b) do "#{a}#{b}" |> String.to_integer() end end Day7.run()