From cd8a8345b33f56fac004c6bd2d3d44977f3b5a46 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Tue, 14 Dec 2021 21:47:01 -0800 Subject: [PATCH] [2021][ruby][15.x] use a Set for a minor speedup --- 2021/ruby/day_15.rb | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/2021/ruby/day_15.rb b/2021/ruby/day_15.rb index e22acb0..cd9a8c7 100644 --- a/2021/ruby/day_15.rb +++ b/2021/ruby/day_15.rb @@ -1,12 +1,12 @@ +require "set" + cavern = ARGF.read.split("\n").map { _1.chars.map(&:to_i) } -cavern = (0..4).flat_map {|i| - cavern.map {|row| row.map { (_1 + i - 1) % 9 + 1 }} -} -cavern = cavern.map {|row| - (0..4).flat_map {|i| - row.map { (_1 + i - 1) % 9 + 1 } - } -} +cavern = (0..4).flat_map {|i| cavern.map {|row| + row.map { (_1 + i - 1) % 9 + 1 } +}} +cavern = cavern.map {|row| (0..4).flat_map {|i| + row.map { (_1 + i - 1) % 9 + 1 } +}} cavern = cavern .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[[0,0]] = 0 -edges = [[0,0]] +edges = Set[[0,0]] until risks.has_key?(bottom_right) yx = edges.min_by { risks.fetch(_1) } @@ -32,7 +32,7 @@ until risks.has_key?(bottom_right) risks[_1] = risk + cavern.fetch(_1) end - edges.concat(neighbors) + edges.merge(neighbors) end p risks[bottom_right]