Skip to content

Instantly share code, notes, and snippets.

@rugyoga
Last active December 4, 2023 18:12
Show Gist options
  • Select an option

  • Save rugyoga/9c2531cbe32944084a51fead2bc5f448 to your computer and use it in GitHub Desktop.

Select an option

Save rugyoga/9c2531cbe32944084a51fead2bc5f448 to your computer and use it in GitHub Desktop.
Advent of Code 2023 day 4
import AOC
aoc 2023, 4 do
def p1(input) do
input
|> winning_cards()
|> Enum.map(fn 0 -> 0; n -> 2 ** (n-1) end)
|> Enum.sum()
end
def winning_cards(input) do
process = fn card -> card |> String.split(" ", trim: true) |> Enum.map(&String.to_integer/1) |> MapSet.new end
input
|> String.split("\n", trim: true)
|> Enum.map(fn line ->
[winning, held] = line |> String.split(": ") |> Enum.at(1) |> String.split("|") |> Enum.map(process)
MapSet.intersection(winning, held) |> Enum.count()
end)
end
def p2(input) do
input
|> winning_cards()
|> Enum.map(&{1, &1})
|> process()
|> Enum.unzip()
|> elem(0)
|> Enum.sum()
end
def process([]), do: []
def process([{count, multiplier} = x | xs]) do
{before, after_} = Enum.split(xs, multiplier)
[x | process(Enum.map(before, fn {c, n} -> {c + count, n} end) ++ after_)]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment