Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Advent of Code 2023 Day 4 Part 2

2023_day4_part2.livemd

Advent of Code 2023 Day 4 Part 2

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

Get Inputs

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

My answer

defmodule Resolver do
  def parse(input) do
    input
    |> String.split("\n")
    |> Enum.with_index()
    |> Enum.into(%{}, fn {line, index} ->
      [_, card] = String.split(line, ":")
      [winning_card, my_card] = String.split(card, "|")
      winning_card = parse_card(winning_card)
      my_card = parse_card(my_card)

      nuber_of_matches =
        winning_card
        |> Enum.count(fn winnig_number ->
          Enum.member?(my_card, winnig_number)
        end)

      copies = get_copies(index + 1, nuber_of_matches)

      {index + 1, copies}
    end)
  end

  defp get_copies(_, 0), do: []

  defp get_copies(current_index, nuber_of_matches) do
    Enum.to_list((current_index + 1)..(current_index + nuber_of_matches))
  end

  defp parse_card(card) do
    card
    |> String.split(" ")
    |> Enum.filter(fn value -> value != "" end)
    |> Enum.map(fn value -> String.to_integer(value) end)
  end

  def resolve(games) do
    games
    |> Enum.map(fn {card_index, _} ->
      get_card(games, card_index, 0)
    end)
    |> Enum.sum()
  end

  defp get_card(games, card_index, acc) do
    games[card_index]
    |> Enum.map(fn next_card_index ->
      get_card(games, next_card_index, acc)
    end)
    |> Enum.sum()
    |> Kernel.+(1)
  end
end
games =
  """
  Card 1: 41 48 83 86 17 | 83 86  6 31 17  9 48 53
  Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
  Card 3:  1 21 53 59 44 | 69 82 63 72 16 21 14  1
  Card 4: 41 92 73 84 69 | 59 84 76 51 58  5 54 83
  Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
  Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
  """
  |> String.slice(0..-2)
  |> Resolver.parse()
Resolver.resolve(games)
games = Resolver.parse(puzzle_input)
Resolver.resolve(games)