From f23af95c022eca8d0cbb40b9760a4f6af3c84e41 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Tue, 14 Dec 2021 21:39:33 -0800 Subject: [PATCH] [2021][ruby][15.x] --- 2021/ruby/day_15.rb | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 2021/ruby/day_15.rb diff --git a/2021/ruby/day_15.rb b/2021/ruby/day_15.rb new file mode 100644 index 0000000..e22acb0 --- /dev/null +++ b/2021/ruby/day_15.rb @@ -0,0 +1,38 @@ +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 = cavern + .flat_map.with_index {|row,y| row.map.with_index {|risk,x| [[y,x], risk] }} + .to_h +bottom_right = cavern.keys.max + +risks = Hash.new(0) +risks[[0,0]] = 0 +edges = [[0,0]] + +until risks.has_key?(bottom_right) + yx = edges.min_by { risks.fetch(_1) } + edges.delete(yx) + + y,x = yx + neighbors = [[-1, 0], [1, 0], [0, 1], [0, -1]] + .map {|dy,dx| [y+dy, x+dx] } + .select { cavern.has_key?(_1) } + .reject { risks.has_key?(_1) } + + risk = risks.fetch(yx) + neighbors.each do + risks[_1] = risk + cavern.fetch(_1) + end + + edges.concat(neighbors) +end + +p risks[bottom_right]