From 2742fabb808fcb6eb202e1029d69a5e62b1c606c Mon Sep 17 00:00:00 2001 From: Shanti Chellaram Date: Mon, 19 Dec 2022 11:06:50 +0900 Subject: [PATCH] Day 13-1 --- day13.erl | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 day13.erl diff --git a/day13.erl b/day13.erl new file mode 100644 index 0000000..20589f6 --- /dev/null +++ b/day13.erl @@ -0,0 +1,44 @@ +-module(day13). + +-export([solve/1]). + +-compile(export_all). + +solve(Input) -> + PacketPairs = binary:split(Input, <<"\n\n">>, [global, trim_all]), + Part1 = part1(PacketPairs), + {Part1, none}. + +part1(PacketPairs) -> part1(PacketPairs, {1, 0}). + +part1([], {_Index, Score}) -> Score; +part1([PacketPair|Rest], {Index, Score}) -> + [LeftStr, RightStr] = binary:split(PacketPair, <<$\n>>, [trim_all]), + Left = parse_packet(LeftStr), + Right = parse_packet(RightStr), + NewScore = case compare(Left, Right) of + true -> Score + Index; + false -> Score + end, + part1(Rest, {Index+1, NewScore}). + +compare([], []) -> undecided; +compare([], [_|_Rest]) -> true; +compare([_|_Rest], []) -> false; +compare([Left | LeftRest], [Right | RightRest]) when is_list(Left) and is_list(Right) -> + case compare(Left, Right) of + undecided -> compare(LeftRest, RightRest); + Result -> Result + end; +compare([Left | _] = Lefts, [Right | RightRest]) when is_list(Left) and is_integer(Right) -> + compare(Lefts, [[Right] | RightRest]); +compare([Left | LeftRest], [Right | _] = Rights) when is_integer(Left) and is_list(Right) -> + compare([[Left] | LeftRest], Rights); +compare([Value | Left], [Value | Right]) when is_integer(Value) -> compare(Left, Right); +compare([Left|_], [Right|_]) when is_integer(Left) and is_integer(Right) -> Left < Right; +compare(Left, Right) when is_integer(Left) and is_integer(Right) -> Left < Right. + +parse_packet(Packet) -> + {ok, Tokens, _EndLine} = erl_scan:string(unicode:characters_to_list([Packet,$.])), + {ok, Parsed} = erl_parse:parse_term(Tokens), + Parsed.