Skip to content

Commit b75d728

Browse files
committed
Day 12 Ruby solutions
1 parent 3a21be3 commit b75d728

File tree

2 files changed

+134
-0
lines changed

2 files changed

+134
-0
lines changed

12-1.rb

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/usr/bin/env ruby
2+
3+
class Map
4+
attr_accessor :neighbours
5+
attr_accessor :paths
6+
7+
def initialize
8+
@neighbours = Hash.new { Array.new }
9+
@paths = -1
10+
end
11+
12+
def connect(cave1, cave2)
13+
n1 = @neighbours[cave1]
14+
n2 = @neighbours[cave2]
15+
16+
n1.append cave2 unless n1.any? cave2
17+
n2.append cave1 unless n2.any? cave1
18+
19+
@neighbours[cave1] = n1
20+
@neighbours[cave2] = n2
21+
end
22+
23+
def visit(cave, path)
24+
if cave == 'end'
25+
@paths += 1
26+
else
27+
@neighbours[cave].each { |n| visit(n, path + [cave]) unless path.any? n.downcase }
28+
end
29+
end
30+
31+
def count_paths
32+
return @paths unless @paths.negative?
33+
34+
@paths = 0
35+
visit('start', [])
36+
@paths
37+
end
38+
39+
def to_s
40+
s = "<#{self.class} (#{@paths}):\n"
41+
@neighbours.each do |cave, neighbours|
42+
s += "#{cave} -> #{neighbours}\n"
43+
end
44+
s += '>'
45+
s
46+
end
47+
48+
def inspect
49+
to_s
50+
end
51+
end
52+
53+
map = Map.new
54+
55+
input = File.read('12.input').lines.map(&:strip).map { |row| (row.split '-') }
56+
57+
input.each do |conn|
58+
map.connect conn[0], conn[1]
59+
end
60+
61+
print map.count_paths, "\n"

12-2.rb

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#!/usr/bin/env ruby
2+
3+
class Map
4+
attr_accessor :neighbours
5+
attr_accessor :paths
6+
7+
def initialize
8+
@neighbours = Hash.new { Array.new }
9+
@paths = -1
10+
end
11+
12+
def connect(cave1, cave2)
13+
n1 = @neighbours[cave1]
14+
n2 = @neighbours[cave2]
15+
16+
n1.append cave2 unless n1.any? cave2
17+
n2.append cave1 unless n2.any? cave1
18+
19+
@neighbours[cave1] = n1
20+
@neighbours[cave2] = n2
21+
end
22+
23+
def visit(cave, path)
24+
if cave == 'end'
25+
@paths += 1
26+
else
27+
path += [cave]
28+
@neighbours[cave].each do |n|
29+
if n == 'start'
30+
# Returned to start
31+
next
32+
elsif n == n.downcase and
33+
path.count(n) >= 1 and
34+
path.detect { |c| c == c.downcase and path.count(c) > 1 }
35+
next
36+
else
37+
visit(n, path)
38+
end
39+
end
40+
end
41+
end
42+
43+
def count_paths
44+
return @paths unless @paths.negative?
45+
46+
@paths = 0
47+
visit('start', [])
48+
@paths
49+
end
50+
51+
def to_s
52+
s = "<#{self.class} (#{@paths}):\n"
53+
@neighbours.each do |cave, neighbours|
54+
s += "#{cave} -> #{neighbours}\n"
55+
end
56+
s += '>'
57+
s
58+
end
59+
60+
def inspect
61+
to_s
62+
end
63+
end
64+
65+
map = Map.new
66+
67+
input = File.read('12.input').lines.map(&:strip).map { |row| (row.split '-') }
68+
69+
input.each do |conn|
70+
map.connect conn[0], conn[1]
71+
end
72+
73+
print map.count_paths, "\n"

0 commit comments

Comments
 (0)