diff --git a/2023/elixir/lib/2023/4.ex b/2023/elixir/lib/2023/4.ex index 360dbbf..8c6a2d0 100644 --- a/2023/elixir/lib/2023/4.ex +++ b/2023/elixir/lib/2023/4.ex @@ -9,11 +9,40 @@ aoc 2023, 4 do |> Enum.sum() end - def p2(_input) do - # input - # |> String.split("\n") - # |> Enum.map(&parse_line/1) - # |> Enum.map(&score_2/1) + def p2(input) do + cards = + input + |> String.split("\n") + |> Enum.map(&parse_line/1) + |> Enum.map(&score_2/1) + + card_counts = + cards + |> Stream.map(fn {id, _} -> {id, 1} end) + |> Enum.into(%{}) + + cards + |> Enum.reduce(card_counts, fn {id, winners}, counts -> + if winners > 0 do + copies = Map.get(counts, id) + + copied_range = + (id + 1)..(id + winners) + + for copy_id <- copied_range, reduce: counts do + counts -> + if Map.has_key?(counts, copy_id) do + Map.update!(counts, copy_id, &(&1 + copies)) + else + counts + end + end + else + counts + end + end) + |> Map.values() + |> Enum.sum() end def parse_line(line) do diff --git a/README.md b/README.md index 389032c..eaf8cd2 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ 1. [2020] **17/50** 🌟 1. [2021] **43/50** 🌟 1. [2022] **14/50** 🌟 -1. [2023] **7/50** 🌟 +1. [2023] **8/50** 🌟 [2015]: ./2015 [2017]: ./2017