Skip to content

Commit c707fce

Browse files
committed
day 7
1 parent 2a7948b commit c707fce

File tree

4 files changed

+1064
-0
lines changed

4 files changed

+1064
-0
lines changed

07/a.rb

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
fs = { "/" => {} }
2+
pwd = []
3+
4+
File.foreach("07/input.txt", chomp: true) do |line|
5+
if chdir = line[/\$ cd (.+)/, 1]
6+
chdir == ".." ? pwd.pop : pwd << chdir
7+
elsif dirname = line[/dir (.+)/, 1]
8+
fs.dig(*pwd)[dirname] = {}
9+
elsif filematch = line.match(/(\d+) (.+)/)
10+
fs.dig(*pwd)[filematch[2]] = filematch[1].to_i
11+
end
12+
end
13+
14+
def dir_sizes(fs, pwd = ["/"])
15+
dir = fs.dig(*pwd)
16+
subdirs = dir.keys.select { |k| dir[k].is_a?(Hash) }
17+
subdir_sizes = subdirs.map { |d| dir_sizes(fs, pwd + [d]) }.reduce(:merge)
18+
local_size = dir.values.sum { |i| i.is_a?(Integer) ? i : 0 }
19+
total_size = local_size + subdirs.sum { |d| subdir_sizes[pwd + [d]] }
20+
21+
{ pwd => total_size }.merge(subdir_sizes || {})
22+
end
23+
24+
p dir_sizes(fs).values.sum { |s| s <= 100_000 ? s : 0 }

07/b.rb

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
fs = { "/" => {} }
2+
pwd = []
3+
4+
File.foreach("07/input.txt", chomp: true) do |line|
5+
if chdir = line[/\$ cd (.+)/, 1]
6+
chdir == ".." ? pwd.pop : pwd << chdir
7+
elsif dirname = line[/dir (.+)/, 1]
8+
fs.dig(*pwd)[dirname] = {}
9+
elsif filematch = line.match(/(\d+) (.+)/)
10+
fs.dig(*pwd)[filematch[2]] = filematch[1].to_i
11+
end
12+
end
13+
14+
def dir_sizes(fs, pwd = ["/"])
15+
dir = fs.dig(*pwd)
16+
subdirs = dir.keys.select { |k| dir[k].is_a?(Hash) }
17+
subdir_sizes = subdirs.map { |d| dir_sizes(fs, pwd + [d]) }.reduce(:merge)
18+
local_size = dir.values.sum { |i| i.is_a?(Integer) ? i : 0 }
19+
total_size = local_size + subdirs.sum { |d| subdir_sizes[pwd + [d]] }
20+
21+
{ pwd => total_size }.merge(subdir_sizes || {})
22+
end
23+
24+
disk = 70_000_000
25+
needed = 30_000_000
26+
ps = dir_sizes(fs)
27+
avail = disk - ps[["/"]]
28+
29+
p ps.values.sort.find { |v| v >= needed - avail }

07/example.txt

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
$ cd /
2+
$ ls
3+
dir a
4+
14848514 b.txt
5+
8504156 c.dat
6+
dir d
7+
$ cd a
8+
$ ls
9+
dir e
10+
29116 f
11+
2557 g
12+
62596 h.lst
13+
$ cd e
14+
$ ls
15+
584 i
16+
$ cd ..
17+
$ cd ..
18+
$ cd d
19+
$ ls
20+
4060174 j
21+
8033020 d.log
22+
5626152 d.ext
23+
7214296 k

0 commit comments

Comments
 (0)