Skip to content

Commit 580e486

Browse files
author
Robb Kidd
committed
2022 day 7 part 1
1 parent 50f089d commit 580e486

File tree

3 files changed

+91
-1
lines changed

3 files changed

+91
-1
lines changed

2022/ruby/Gemfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ source "https://rubygems.org"
44

55
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
66

7+
gem "rake"
78
gem "pry"
89
gem "yard-doctest"
910
gem "priority_queue_cxx"

2022/ruby/Gemfile.lock

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ GEM
88
pry (0.14.1)
99
coderay (~> 1.1)
1010
method_source (~> 1.0)
11+
rake (13.0.6)
1112
webrick (1.7.0)
1213
yard (0.9.28)
1314
webrick (~> 1.7.0)
@@ -17,11 +18,13 @@ GEM
1718

1819
PLATFORMS
1920
arm64-darwin-22
21+
ruby
2022

2123
DEPENDENCIES
2224
priority_queue_cxx
2325
pry
26+
rake
2427
yard-doctest
2528

2629
BUNDLED WITH
27-
2.3.7
30+
2.3.26

2022/ruby/day07.rb

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
class Day07
2+
def self.go
3+
day = new
4+
puts "Part 1: #{day.part1}"
5+
puts "Part 2: #{day.part2}"
6+
end
7+
8+
def initialize(input=nil)
9+
@input = input || real_input
10+
@dirs = parse_input
11+
end
12+
13+
# @example
14+
# day.part1 #=> 95_437
15+
def part1
16+
@dirs
17+
.map { |dir_name, _|
18+
dirs
19+
.select{ |subdir, _| subdir.start_with?(dir_name) }
20+
.map{|dir, files| files.empty? ? 0 : files.map{|name,size| size}.reduce(&:+)}
21+
.reduce(&:+)
22+
}
23+
.select{ |dir_size| dir_size < 100_000 }
24+
.reduce(&:+)
25+
end
26+
27+
def part2
28+
end
29+
30+
def parse_input
31+
cwd = "root"
32+
@input
33+
.split("$ ")
34+
.each_with_object({}) { |cmd_and_output, dirs|
35+
lines = cmd_and_output.split("\n")
36+
cmd = lines.shift
37+
case cmd
38+
when "cd /"
39+
cwd = "root"
40+
when "cd .."
41+
cwd = cwd.split("/")[0..-2].join("/")
42+
cwd = "root" if cwd == ""
43+
when /cd (\w*)/
44+
cwd += "/#{$1}"
45+
when "ls"
46+
dirs[cwd] ||= { }
47+
lines
48+
.reject { |line| line.start_with?("dir")}
49+
.map { |line| line.split(" ") }
50+
.each { |size, filename| dirs[cwd][filename] = size.to_i }
51+
else
52+
:do_nothing
53+
end
54+
}
55+
end
56+
57+
def real_input
58+
File.read('../inputs/day07-input.txt')
59+
end
60+
61+
EXAMPLE_INPUT = <<~INPUT
62+
$ cd /
63+
$ ls
64+
dir a
65+
14848514 b.txt
66+
8504156 c.dat
67+
dir d
68+
$ cd a
69+
$ ls
70+
dir e
71+
29116 f
72+
2557 g
73+
62596 h.lst
74+
$ cd e
75+
$ ls
76+
584 i
77+
$ cd ..
78+
$ cd ..
79+
$ cd d
80+
$ ls
81+
4060174 j
82+
8033020 d.log
83+
5626152 d.ext
84+
7214296 k
85+
INPUT
86+
end

0 commit comments

Comments
 (0)