[2021][ruby][15.x] use a Set for a minor speedup

pull/2/head
Alpha Chen 3 years ago
parent f23af95c02
commit cd8a8345b3

@ -1,12 +1,12 @@
require "set"
cavern = ARGF.read.split("\n").map { _1.chars.map(&:to_i) } cavern = ARGF.read.split("\n").map { _1.chars.map(&:to_i) }
cavern = (0..4).flat_map {|i| cavern = (0..4).flat_map {|i| cavern.map {|row|
cavern.map {|row| row.map { (_1 + i - 1) % 9 + 1 }} row.map { (_1 + i - 1) % 9 + 1 }
} }}
cavern = cavern.map {|row| cavern = cavern.map {|row| (0..4).flat_map {|i|
(0..4).flat_map {|i| row.map { (_1 + i - 1) % 9 + 1 }
row.map { (_1 + i - 1) % 9 + 1 } }}
}
}
cavern = cavern cavern = cavern
.flat_map.with_index {|row,y| row.map.with_index {|risk,x| [[y,x], risk] }} .flat_map.with_index {|row,y| row.map.with_index {|risk,x| [[y,x], risk] }}
@ -15,7 +15,7 @@ bottom_right = cavern.keys.max
risks = Hash.new(0) risks = Hash.new(0)
risks[[0,0]] = 0 risks[[0,0]] = 0
edges = [[0,0]] edges = Set[[0,0]]
until risks.has_key?(bottom_right) until risks.has_key?(bottom_right)
yx = edges.min_by { risks.fetch(_1) } yx = edges.min_by { risks.fetch(_1) }
@ -32,7 +32,7 @@ until risks.has_key?(bottom_right)
risks[_1] = risk + cavern.fetch(_1) risks[_1] = risk + cavern.fetch(_1)
end end
edges.concat(neighbors) edges.merge(neighbors)
end end
p risks[bottom_right] p risks[bottom_right]

Loading…
Cancel
Save