68 lines
1.3 KiB
Elixir
68 lines
1.3 KiB
Elixir
|
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
|