@@ -7,7 +7,7 @@ def self.go
7
7
8
8
def initialize ( input = nil )
9
9
@input = input || real_input
10
- @dirs = parse_input
10
+ @dirs = parse_input ( @input )
11
11
end
12
12
13
13
# @example
@@ -46,32 +46,34 @@ def part2
46
46
def total_dir_size ( dir_name )
47
47
@dirs
48
48
. select { |subdir , _ | subdir . start_with? ( dir_name ) }
49
- . map { | dir , files | files . empty? ? 0 : files . map { | name , size | size } . reduce ( & :+ ) }
49
+ . map { | _name , size | size }
50
50
. reduce ( &:+ )
51
51
end
52
52
53
- def parse_input
53
+ # @example
54
+ # day.parse_input(Day07::EXAMPLE_INPUT) #=> {"root"=>23352670, "root/a"=>94269, "root/a/e"=>584, "root/d"=>24933642}
55
+ def parse_input ( input )
54
56
cwd = "root"
55
- @input
57
+
58
+ input
56
59
. split ( "$ " )
57
- . each_with_object ( { } ) { |cmd_and_output , dirs |
58
- lines = cmd_and_output . split ( "\n " )
59
- cmd = lines . shift
60
- case cmd
61
- when "cd /"
62
- cwd = "root"
63
- when "cd .."
64
- cwd = cwd . split ( "/" ) [ 0 ..-2 ] . join ( "/" )
65
- when /cd (\w *)/
66
- cwd += "/#{ $1} "
60
+ . each_with_object ( { } ) { |command_and_output , dirs | # dirs is updated by and returned from this loop
61
+ command , output = command_and_output . split ( "\n " , 2 )
62
+
63
+ case command
64
+ when "" ; :do_nothing
65
+ when "cd /" ; cwd = "root"
66
+ when "cd .." ; cwd = cwd . split ( "/" ) [ 0 ..-2 ] . join ( "/" )
67
+ when /cd (\w *)/ ; cwd += "/#{ $1} "
68
+
67
69
when "ls"
68
- dirs [ cwd ] ||= { }
69
- lines
70
- . reject { |line | line . start_with? ( "dir" ) }
71
- . map { |line | line . split ( " " ) }
72
- . each { |size , filename | dirs [ cwd ] [ filename ] = size . to_i }
73
- else
74
- :do_nothing
70
+ dirs [ cwd ] ||= output
71
+ . split ( " \n " )
72
+ . reject { |line | line . start_with? ( "dir" ) }
73
+ . map { |line | line . split ( " " ) }
74
+ . reduce ( 0 ) { |dir_size , ( size , _filename ) |
75
+ dir_size += size . to_i
76
+ }
75
77
end
76
78
}
77
79
end
0 commit comments