-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.rb
54 lines (45 loc) · 1.2 KB
/
day7.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
EFile = Struct.new(:name, :size)
EDir = Struct.new(:name, :parent, :directories, :files)
root = EDir.new("/", nil, {}, [])
current = nil
File.read(ARGV[0]).lines.each do |line|
input = line.chomp
if input.start_with?("$ cd /")
current = root
elsif input.start_with?("$ ls")
# noop
elsif input.start_with?("$ cd ..")
current = current.parent
elsif input.start_with?("$ cd")
sub = input.split(' ')[2]
current = current[:directories][sub]
elsif input.start_with?("dir ")
name = input.split(' ')[1]
subdir = EDir.new(name, current, {}, [])
current[:directories][name] = subdir
elsif input.start_with?(/[0-9]/)
size, name = input.split(' ')
file = EFile.new(name, size.to_i)
current[:files] << file
end
end
$dirmap = {}
def fullname(dir)
result = dir[:name]
if dir[:parent].nil?
return "/"
else
return fullname(dir[:parent]) + "/" + dir[:name]
end
end
def edir_size(dir)
size = dir[:files].sum { |f| f[:size] }
size += dir[:directories].sum { |key, value| edir_size(value) }
$dirmap[fullname(dir)] = size
return size
end
edir_size(root)
puts $dirmap.inspect
puts $dirmap.keys.size
total = $dirmap.sum { |k, v| v <= 100000 ? v : 0 }
puts total