You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
31 lines
1.0 KiB
31 lines
1.0 KiB
-module(day3).
|
|
|
|
-export([solve/1]).
|
|
|
|
solve(InputData) ->
|
|
Rucksacks = binary:split(InputData, <<$\n>>, [trim_all, global]),
|
|
{lists:foldl(fun part1/2, 0, Rucksacks), part2(Rucksacks)}.
|
|
|
|
part2([]) -> 0;
|
|
part2([Ruck1, Ruck2, Ruck3 | Rest]) ->
|
|
[Badge] = maps:keys(
|
|
sets:intersection(
|
|
sets:intersection(tally(Ruck1), tally(Ruck2)),
|
|
tally(Ruck3)
|
|
)),
|
|
priority(Badge) + part2(Rest).
|
|
|
|
part1(Rucksack, TotalPriority) ->
|
|
CompartmentSize = byte_size(Rucksack) div 2,
|
|
<<Compartment1:CompartmentSize/binary, Compartment2:CompartmentSize/binary>> = Rucksack,
|
|
[DupeLetter] = maps:keys(sets:intersection(tally(Compartment1), tally(Compartment2))),
|
|
priority(DupeLetter) + TotalPriority.
|
|
|
|
tally(Compartment) -> tally(Compartment, #{}).
|
|
tally(<<>>, Set) -> Set;
|
|
tally(<<Item, Rest/binary>>, Set) when is_map_key(Item, Set) -> tally(Rest, Set);
|
|
tally(<<Item, Rest/binary>>, Set) -> tally(Rest, Set#{Item => []}).
|
|
|
|
priority(Item) when Item >= $a andalso Item =< $z -> Item - $a + 1;
|
|
priority(Item) when Item >= $A andalso Item =< $Z -> Item - $A + 27.
|
|
|