Day 15
This commit is contained in:
32
lib/day15.ex
Normal file
32
lib/day15.ex
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
defmodule Aoc2023.Day15 do
|
||||||
|
use Aoc2023
|
||||||
|
|
||||||
|
def parse(input) do
|
||||||
|
input |> String.split(",")
|
||||||
|
end
|
||||||
|
|
||||||
|
defp hash(str) do
|
||||||
|
for <<char <- str>>, reduce: 0 do
|
||||||
|
acc -> Bitwise.band((acc + char) * 17, 255)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def part1(input) do
|
||||||
|
input |> Enum.map(&hash/1) |> Enum.sum
|
||||||
|
end
|
||||||
|
|
||||||
|
def part2(input) do
|
||||||
|
for instr <- input, reduce: 0..255 |> Enum.map(&{&1, []}) |> Enum.into(%{}) do
|
||||||
|
boxes ->
|
||||||
|
[_, label, op, lens] = Regex.run(~r/([a-z]+)([-=])(\d*)/, instr)
|
||||||
|
box = hash(label)
|
||||||
|
label = String.to_atom(label)
|
||||||
|
case op do
|
||||||
|
"=" -> boxes |> Map.update!(box, &Keyword.update(&1, label, String.to_integer(lens), fn _ -> String.to_integer(lens) end))
|
||||||
|
"-" -> boxes |> Map.update!(box, &Keyword.delete(&1, label))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|> Enum.flat_map(fn {box, lenses} -> lenses |> Enum.with_index(1) |> Enum.map(fn {{_, focus}, i} -> focus * (box + 1) * i end) end)
|
||||||
|
|> Enum.sum
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -16,6 +16,7 @@ defmodule Mix.Tasks.Aoc do
|
|||||||
defp module(12), do: Aoc2023.Day12
|
defp module(12), do: Aoc2023.Day12
|
||||||
defp module(13), do: Aoc2023.Day13
|
defp module(13), do: Aoc2023.Day13
|
||||||
defp module(14), do: Aoc2023.Day14
|
defp module(14), do: Aoc2023.Day14
|
||||||
|
defp module(15), do: Aoc2023.Day15
|
||||||
# [MODULE INSERTION POINT]
|
# [MODULE INSERTION POINT]
|
||||||
|
|
||||||
defp base_dir(), do: System.get_env("AOC_BASE")
|
defp base_dir(), do: System.get_env("AOC_BASE")
|
||||||
@@ -252,4 +253,4 @@ defmodule Mix.Tasks.Aoc do
|
|||||||
{:noreply, state}
|
{:noreply, state}
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
1
tests/day15/1
Normal file
1
tests/day15/1
Normal file
@@ -0,0 +1 @@
|
|||||||
|
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7
|
||||||
1
tests/day15/1.1
Normal file
1
tests/day15/1.1
Normal file
@@ -0,0 +1 @@
|
|||||||
|
1320
|
||||||
1
tests/day15/1.2
Normal file
1
tests/day15/1.2
Normal file
@@ -0,0 +1 @@
|
|||||||
|
145
|
||||||
Reference in New Issue
Block a user