From f283c20581ef197714488f0fd6dee96287570e39 Mon Sep 17 00:00:00 2001 From: Shanti Chellaram Date: Sun, 11 Dec 2022 21:37:08 +0900 Subject: [PATCH] Day 10-1 --- day10.erl | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 day10.erl diff --git a/day10.erl b/day10.erl new file mode 100644 index 0000000..1c2da4e --- /dev/null +++ b/day10.erl @@ -0,0 +1,34 @@ +-module(day10). + +-export([solve/1]). + +solve(Input) -> + {part1(Input), none}. + +part1(Input) -> + History = run(Input, [{1, 1}]), + Interesting = [20, 60, 100, 140, 180, 220], + Score = fun(Key) -> + Key * element(2, lists:keyfind(Key, 1, History)) + end, + lists:sum(lists:map(Score, Interesting)). + +run(<<"\n", Rest/binary>>, StateIn) -> + run(Rest, StateIn); +run(<<"noop", Rest/binary>>, [{Cycle, X}|_]=History) -> + run(Rest, [{Cycle+1, X} | History]); +run(<<"addx ", RestIn/binary>>, [{Cycle, X}|_]=History) -> + {Value, RestOut} = parse_int(RestIn), + run(RestOut, [{Cycle+2, X+Value}, {Cycle+1, X} | History]); +run(<<>>, State) -> + State. + +parse_int(<<$-, Rest/binary>>) -> + {AbsoluteValue, Binary} = parse_int0(Rest, 0), + {-1 * AbsoluteValue, Binary}; +parse_int(Binary) -> + parse_int0(Binary, 0). + +parse_int0(<>, Acc) when Digit >= $0 andalso Digit =< $9 -> + parse_int0(Rest, Acc*10 + Digit - $0); +parse_int0(Binary, Acc) when is_binary(Binary) -> {Acc, Binary}.