File tree 1 file changed +66
-0
lines changed
1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
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 "
You can’t perform that action at this time.
0 commit comments