Skip to content

Commit 2ab5a0f

Browse files
author
Robb Kidd
committed
refactor to fewer proc shenanigans
1 parent 18aae43 commit 2ab5a0f

File tree

1 file changed

+16
-28
lines changed

1 file changed

+16
-28
lines changed

2023/ruby/day05.rb

Lines changed: 16 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ def parse
3434
if lines.first.match(/^seeds: \d/)
3535
maps["seeds"] = lines.first.split(": ")[1].split(/\s+/).map(&:to_i)
3636
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)
3939
end
4040
end
4141

@@ -46,36 +46,24 @@ def parse
4646
# mapper = Day05::Mapper.new(["50 98 2", "52 50 48"])
4747
# mapper.convert(79) #=> 81
4848
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+
}
6658
end
6759

6860
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)
7864
end
65+
66+
return input
7967
end
8068
end
8169

0 commit comments

Comments
 (0)