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.
37 lines
1.4 KiB
37 lines
1.4 KiB
-module(day7).
|
|
|
|
-export([solve/1]).
|
|
|
|
solve(InputData) ->
|
|
Input = binary:split(InputData, <<"\n">>, [trim_all, global]),
|
|
#{sizes := Sizes} = lists:foldl(fun execute/2, #{cwd => [], sizes => #{}}, Input),
|
|
{maps:fold(fun adder/3, 0, Sizes), part2(Sizes)}.
|
|
|
|
adder(_Path, Size, Total) when Size > 100000 -> Total;
|
|
adder(_Path, Size, Total) -> Size + Total.
|
|
|
|
part2(#{[] := FullSize} = SizesIn) ->
|
|
Sizes0 = maps:values(SizesIn),
|
|
Sizes1 = lists:filter(fun(Size) -> Size > FullSize - 40000000 end, Sizes0),
|
|
lists:min(Sizes1).
|
|
|
|
execute(<<"$ cd /">>, State) -> State#{cwd := []};
|
|
execute(<<"$ cd ..">>, #{cwd := [_Cwd | Parent]} = State) -> State#{cwd := Parent};
|
|
execute(<<"$ cd ", Dir/binary>>, #{cwd := Cwd} = State) -> State#{cwd := [Dir | Cwd]};
|
|
execute(<<"$ ls">>, State) -> State;
|
|
execute(<<"dir ", Dir/binary>>, #{cwd := Cwd} = State) -> State#{[Dir | Cwd] => 0};
|
|
execute(FileCommand ,#{cwd := Cwd, sizes := Sizes} = State) ->
|
|
{_Filename, Size} = parse_file_command(FileCommand),
|
|
State#{sizes := add_sizes(Cwd, Size, Sizes)}.
|
|
|
|
parse_file_command(Command) -> parse_file_command(Command, 0).
|
|
|
|
parse_file_command(<<$\s, Name/binary>>, Size) -> {Name, Size};
|
|
parse_file_command(<<Digit, Rest/binary>>, Size) -> parse_file_command(Rest, (Size*10) + (Digit - $0)).
|
|
|
|
add_sizes(Path, Size, Sizes) ->
|
|
NewSizes = maps:update_with(Path, fun(OldSize) -> OldSize + Size end, Size, Sizes),
|
|
case Path of
|
|
[] -> NewSizes;
|
|
[_Head| Parent] -> add_sizes(Parent, Size, NewSizes)
|
|
end.
|