logo

adventofcode

Unnamed repository; edit this file 'description' to name the repository.
commit: 5e085cd22976cc01bf10ecbb1a2d1e801fdf2618
parent: d675347e2effd644a14990b7842704ef47070930
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Mon,  2 Dec 2019 13:04:54 +0100

day2: part one

Diffstat:

Alib/day2.ex16++++++++++++++++
Ascripts/day2.ex33+++++++++++++++++++++++++++++++++
2 files changed, 49 insertions(+), 0 deletions(-)

diff --git a/lib/day2.ex b/lib/day2.ex @@ -0,0 +1,16 @@ +defmodule Day2 do + # add + def opcode([1, pos1, pos2, store], tokens) do + List.replace_at(tokens, store, Enum.at(tokens, pos1) + Enum.at(tokens, pos2)) + end + + # multiply + def opcode([2, pos1, pos2, store], tokens) do + List.replace_at(tokens, store, Enum.at(tokens, pos1) * Enum.at(tokens, pos2)) + end + + # halt + def opcode([99, _, _, _], _) do + :halt + end +end diff --git a/scripts/day2.ex b/scripts/day2.ex @@ -0,0 +1,33 @@ +line = "1,9,10,3,2,3,11,0,99,30,40,50" +line = "1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,1,6,19,23,1,23,13,27,2,6,27,31,1,5,31,35,2,10,35,39,1,6,39,43,1,13,43,47,2,47,6,51,1,51,5,55,1,55,6,59,2,59,10,63,1,63,6,67,2,67,10,71,1,71,9,75,2,75,10,79,1,79,5,83,2,10,83,87,1,87,6,91,2,9,91,95,1,95,5,99,1,5,99,103,1,103,10,107,1,9,107,111,1,6,111,115,1,115,5,119,1,10,119,123,2,6,123,127,2,127,6,131,1,131,2,135,1,10,135,0,99,2,0,14,0" +line = "1,12,2,3,1,1,2,3,1,3,4,3,1,5,0,3,2,10,1,19,1,6,19,23,1,23,13,27,2,6,27,31,1,5,31,35,2,10,35,39,1,6,39,43,1,13,43,47,2,47,6,51,1,51,5,55,1,55,6,59,2,59,10,63,1,63,6,67,2,67,10,71,1,71,9,75,2,75,10,79,1,79,5,83,2,10,83,87,1,87,6,91,2,9,91,95,1,95,5,99,1,5,99,103,1,103,10,107,1,9,107,111,1,6,111,115,1,115,5,119,1,10,119,123,2,6,123,127,2,127,6,131,1,131,2,135,1,10,135,0,99,2,0,14,0" +{:ok, agent} = Agent.start_link fn -> [] end + +IO.puts(line) + +Agent.update(agent, fn _ -> + line + |> String.split([" ", ",", "\n"]) + |> Enum.map(&String.to_integer(&1)) + end) + +Agent.get(agent, & &1) +|> Enum.chunk_every(4) +|> Enum.each(fn opcode -> + result = Day2.opcode(opcode, Agent.get(agent, & &1)) + + if :halt == result do + Agent.get(agent, & &1) + |> Enum.at(0) + |> Integer.to_string() + |> IO.puts() + + exit(:normal) + else + Agent.update(agent, fn _ -> result end) + + result + |> Enum.map(&(Integer.to_string(&1) <> ",")) + |> IO.puts() + end +end)