Powered by AppSignal & Oban Pro

Advent of Code 2024 Day 7 Part 2

2024_day7_part2.livemd

Advent of Code 2024 Day 7 Part 2

Mix.install([
  {:kino_aoc, "~> 0.1"}
])

Get Inputs

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2024", "7", System.fetch_env!("LB_SESSION"))

My answer

sample_input =
  """
  190: 10 19
  3267: 81 40 27
  83: 17 5
  156: 15 6
  7290: 6 8 6 15
  161011: 16 10 13
  192: 17 8 14
  21037: 9 7 18 13
  292: 11 6 16 20
  """
  |> String.trim()
parse = fn input ->
  input
  |> String.split("\n")
  |> Enum.map(fn row ->
    [left, right] = String.split(row, ":")

    {
      String.to_integer(left),
      right
      |> String.trim()
      |> String.split(" ")
      |> Enum.map(&String.to_integer(&1))
    }
  end)
end
equations = parse.(sample_input)
defmodule Combinations do
  def all_with_repetition(_, 0), do: [[]]

  def all_with_repetition(list, n) do
    for x <- list,
        tail <- all_with_repetition(list, n - 1) do
      [x | tail]
    end
  end
end
operation_combinations = Combinations.all_with_repetition(["+", "*", "||"], 1)
find_valid_operations = fn {left, right} ->
  ["+", "*", "||"]
  |> Combinations.all_with_repetition(length(right) - 1)
  |> Enum.find(fn operations ->
    [tl(right), operations]
    |> Enum.zip()
    |> Enum.reduce(hd(right), fn {num, op}, acc ->
      case op do
        "+" ->
          acc + num
        "*" ->
          acc * num
        "||" ->
          String.to_integer(Integer.to_string(acc) <> Integer.to_string(num))
      end
    end)
    |> then(fn result -> result == left end)
  end)
end
find_valid_operations.({156, [15, 6]})
equations
|> Enum.reduce(0, fn {left, _} = equation, acc ->
  case find_valid_operations.(equation) do
    nil -> acc
    _ -> left + acc
  end
end)
puzzle_input
|> parse.()
|> Enum.reduce(0, fn {left, _} = equation, acc ->
  IO.inspect(equation)
  case find_valid_operations.(equation) do
    nil -> acc
    _ -> left + acc
  end
end)