From 9fb42bf830560502aaf5acb3241c3bc8b53a35c2 Mon Sep 17 00:00:00 2001 From: Justin Wernick Date: Sun, 20 Oct 2024 18:01:18 +0200 Subject: Day 23 --- 2015/day23.exs | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 2015/day23.exs (limited to '2015') diff --git a/2015/day23.exs b/2015/day23.exs new file mode 100644 index 0000000..433f70a --- /dev/null +++ b/2015/day23.exs @@ -0,0 +1,57 @@ +require Integer + +program = + File.stream!("inputs/day23.txt") + |> Enum.map(&String.trim(&1)) + +programLength = length(program) + +step = fn {programCounter, a, b} -> + instruction = Enum.at(program, programCounter) + + case instruction do + "hlf a" -> + {programCounter + 1, div(a, 2), b} + + "tpl a" -> + {programCounter + 1, a * 3, b} + + "inc a" -> + {programCounter + 1, a + 1, b} + + "inc b" -> + {programCounter + 1, a, b + 1} + + <<"jmp " <> offset::binary>> -> + {offset, ""} = Integer.parse(offset) + {programCounter + offset, a, b} + + <<"jie a, " <> offset::binary>> -> + if Integer.is_even(a) do + {offset, ""} = Integer.parse(offset) + {programCounter + offset, a, b} + else + {programCounter + 1, a, b} + end + + <<"jio a, " <> offset::binary>> -> + if a == 1 do + {offset, ""} = Integer.parse(offset) + {programCounter + offset, a, b} + else + {programCounter + 1, a, b} + end + end +end + +{_, _, terminalState1} = + Stream.iterate({0, 0, 0}, &step.(&1)) + |> Enum.find(fn {programCounter, _, _} -> programCounter >= programLength end) + +IO.puts("Part 1: #{terminalState1}") + +{_, _, terminalState2} = + Stream.iterate({0, 1, 0}, &step.(&1)) + |> Enum.find(fn {programCounter, _, _} -> programCounter >= programLength end) + +IO.puts("Part 2: #{terminalState2}") -- cgit v1.2.3