Skip to content

Commit e2f540f

Browse files
committedDec 21, 2023
Day 21 part 1 Ruby solution
1 parent d8e6246 commit e2f540f

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
 

‎21-1.rb

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#!/usr/bin/env ruby
2+
3+
require 'numo/narray'
4+
5+
class Garden
6+
attr_accessor :map, :height, :width, :start
7+
8+
def initialize(input)
9+
@height = input.size
10+
@width = input[0].size
11+
@map = Numo::UInt8.zeros(@width, @height)
12+
@start = [-1, -1]
13+
@height.times do |y|
14+
@width.times do |x|
15+
@map[y, x] = 1 if input[y][x] == '#'
16+
@start = [y, x] if input[y][x] == 'S'
17+
end
18+
end
19+
end
20+
21+
def available?(y, x)
22+
y >= 0 and y < @height and
23+
x >= 0 and x < @width and
24+
@map[y, x] == 0
25+
end
26+
27+
def walk(steps)
28+
previous_locations = [@start]
29+
steps.times do |n|
30+
new_locations = []
31+
previous_locations.each do |p|
32+
new_locations << [p[0] + 1, p[1]] if available?(p[0] + 1, p[1])
33+
new_locations << [p[0] - 1, p[1]] if available?(p[0] - 1, p[1])
34+
new_locations << [p[0], p[1] + 1] if available?(p[0], p[1] + 1)
35+
new_locations << [p[0], p[1] - 1] if available?(p[0], p[1] - 1)
36+
end
37+
previous_locations = new_locations.uniq
38+
end
39+
previous_locations.size
40+
end
41+
42+
def inspect
43+
to_s
44+
end
45+
46+
def to_s
47+
s = "<#{self.class}:\n"
48+
@height.times do |y|
49+
@width.times do |x|
50+
s += case @map[y, x]
51+
when 0
52+
'.'
53+
when 1
54+
'#'
55+
end
56+
end
57+
s += "\n"
58+
end
59+
s += ">"
60+
end
61+
end
62+
63+
input = File.read('21.input').lines.map(&:strip).map(&:chars)
64+
65+
garden = Garden.new(input)
66+
print garden.walk(64), "\n"

0 commit comments

Comments
 (0)