-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), none}. adder(_Path, Size, Total) when Size > 100000 -> Total; adder(_Path, Size, Total) -> Size + Total. 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(<>, 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.