51 lines
1.0 KiB
Ruby
51 lines
1.0 KiB
Ruby
|
#prepare the input which is a string containing new lines
|
||
|
def parse(input)
|
||
|
data = []
|
||
|
map = []
|
||
|
input.each_line do |line|
|
||
|
if data.empty?
|
||
|
data << line.split(":").last.split(" ").map(&:to_i)
|
||
|
next
|
||
|
end
|
||
|
if line.include?(":") && !map.empty?
|
||
|
puts map
|
||
|
data << map
|
||
|
map = []
|
||
|
next
|
||
|
end
|
||
|
next if line.include?(":")
|
||
|
next if line.strip.empty?
|
||
|
# build the map
|
||
|
target,source,ranges = line.split(" ").map(&:to_i)
|
||
|
diff = target-source
|
||
|
map << [source,ranges,diff]
|
||
|
end
|
||
|
data << map
|
||
|
data
|
||
|
end
|
||
|
|
||
|
# result should a single string or integer
|
||
|
def calculate(data)
|
||
|
seeds = nil
|
||
|
data.each do |d|
|
||
|
if seeds.nil?
|
||
|
seeds = d
|
||
|
next
|
||
|
end
|
||
|
# start mapping
|
||
|
new_seeds = seeds.map do |seed|
|
||
|
mapped = seed
|
||
|
d.each do |mapping|
|
||
|
source,ranges,diff = mapping
|
||
|
if source <= seed && seed <= source + ranges
|
||
|
mapped = seed + diff
|
||
|
break
|
||
|
end
|
||
|
end
|
||
|
mapped
|
||
|
end
|
||
|
seeds = new_seeds
|
||
|
end
|
||
|
seeds.min
|
||
|
end
|