diff --git a/lib/day2/day2.ex b/lib/day2/day2.ex new file mode 100644 index 0000000..0f5fd0e --- /dev/null +++ b/lib/day2/day2.ex @@ -0,0 +1,67 @@ +defmodule Day2 do + def read_program do + File.read!("lib/day2/input.txt") + |> String.trim() + |> String.split(",") + |> Enum.map(&String.to_integer/1) + end + + def part1 do + read_program() + |> List.replace_at(1, 12) + |> List.replace_at(2, 2) + |> run() + end + + def part2 do + base_prog = read_program() + + Enum.each(0..99, fn a -> + Enum.each(0..99, fn b -> + res = + base_prog + |> List.replace_at(1, a) + |> List.replace_at(2, b) + |> run() + + if Enum.at(res, 0) == 19_690_720 do + IO.inspect(100 * a + b) + end + end) + end) + end + + def run(memory, ip \\ 0) + + def run(memory, ip) when ip < length(memory) do + case eval(Enum.drop(memory, ip), memory) do + {:halt, memory} -> + memory + + {:cont, memory, offset} -> + run(memory, ip + offset) + end + end + + def run(memory, _ip), do: memory + + def eval([99 | _], memory) do + {:halt, memory} + end + + def eval([1, a, b, dest | _], memory) do + { + :cont, + List.replace_at(memory, dest, Enum.at(memory, a) + Enum.at(memory, b)), + 4 + } + end + + def eval([2, a, b, dest | _], memory) do + { + :cont, + List.replace_at(memory, dest, Enum.at(memory, a) * Enum.at(memory, b)), + 4 + } + end +end diff --git a/lib/day2/input.txt b/lib/day2/input.txt new file mode 100644 index 0000000..5a0b748 --- /dev/null +++ b/lib/day2/input.txt @@ -0,0 +1 @@ +1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,1,19,5,23,1,23,9,27,2,27,6,31,1,31,6,35,2,35,9,39,1,6,39,43,2,10,43,47,1,47,9,51,1,51,6,55,1,55,6,59,2,59,10,63,1,6,63,67,2,6,67,71,1,71,5,75,2,13,75,79,1,10,79,83,1,5,83,87,2,87,10,91,1,5,91,95,2,95,6,99,1,99,6,103,2,103,6,107,2,107,9,111,1,111,5,115,1,115,6,119,2,6,119,123,1,5,123,127,1,127,13,131,1,2,131,135,1,135,10,0,99,2,14,0,0 \ No newline at end of file