Skip to content

Commit e636fd0

Browse files
author
Robb Kidd
committed
tighten parsing 'cuz we don't need filenames
1 parent c314d62 commit e636fd0

File tree

1 file changed

+23
-21
lines changed

1 file changed

+23
-21
lines changed

2022/ruby/day07.rb

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ def self.go
77

88
def initialize(input=nil)
99
@input = input || real_input
10-
@dirs = parse_input
10+
@dirs = parse_input(@input)
1111
end
1212

1313
# @example
@@ -46,32 +46,34 @@ def part2
4646
def total_dir_size(dir_name)
4747
@dirs
4848
.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 }
5050
.reduce(&:+)
5151
end
5252

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)
5456
cwd = "root"
55-
@input
57+
58+
input
5659
.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+
6769
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+
}
7577
end
7678
}
7779
end

0 commit comments

Comments
 (0)