@@ -34,8 +34,8 @@ def parse
34
34
if lines . first . match ( /^seeds: \d / )
35
35
maps [ "seeds" ] = lines . first . split ( ": " ) [ 1 ] . split ( /\s +/ ) . map ( &:to_i )
36
36
else
37
- map_key = lines . shift . split ( " " ) [ 0 ]
38
- maps [ map_key ] = Mapper . new ( lines )
37
+ map_title = lines . shift . split ( " " ) [ 0 ]
38
+ maps [ map_title ] = Mapper . new ( map_title , lines )
39
39
end
40
40
end
41
41
@@ -46,36 +46,24 @@ def parse
46
46
# mapper = Day05::Mapper.new(["50 98 2", "52 50 48"])
47
47
# mapper.convert(79) #=> 81
48
48
class Mapper
49
- attr_reader :converters
50
-
51
- def initialize ( map_lines )
52
- @converters = [ ]
53
-
54
- map_lines
55
- . each do |line |
56
- dest_start , source_start , range_length = line . split ( " " ) . map ( &:to_i )
57
- source_range = Range . new ( source_start , ( source_start +range_length -1 ) )
58
- converters << proc do |input |
59
- if source_range . cover? ( input )
60
- dest_start + ( input - source_start )
61
- else
62
- nil
63
- end
64
- end
65
- end
49
+ attr_reader :map_title , :maps
50
+
51
+ def initialize ( map_title , maps )
52
+ @map_title = map_title
53
+ @maps = maps
54
+ . map { |line | line . split ( " " ) . map ( &:to_i ) }
55
+ . map { |dest_start , source_start , range_length |
56
+ [ Range . new ( source_start , ( source_start +range_length -1 ) ) , dest_start ]
57
+ }
66
58
end
67
59
68
60
def convert ( input )
69
- conversions = converters . map { |c | c . call ( input ) } . compact
70
-
71
- case conversions . length
72
- when 0
73
- input
74
- when 1
75
- conversions . first
76
- else
77
- raise ( "more than one map range matched" )
61
+ maps . each do |source_range , dest_start |
62
+ next unless source_range . cover? ( input )
63
+ return dest_start + ( input - source_range . min )
78
64
end
65
+
66
+ return input
79
67
end
80
68
end
81
69
0 commit comments