From 5126ad233a5de558d595429d2c4fc107e0d34623 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Tue, 17 Dec 2024 21:28:27 -0800 Subject: [PATCH] [2024][ruby][18.2] --- 2024/ruby/day_18.rb | 60 +++++++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/2024/ruby/day_18.rb b/2024/ruby/day_18.rb index 1c12218..3a29bac 100644 --- a/2024/ruby/day_18.rb +++ b/2024/ruby/day_18.rb @@ -1,40 +1,48 @@ falling_bytes = DATA.read.scan(/\d+/).map(&:to_i).each_slice(2).to_a -corrupted = falling_bytes[0,1024] +MAX = 70 +DELTAS = [[-1,0], [1,0], [0,-1], [0,1]] -max = 70 +def path(corrupted) + start = [0,0] + stop = [MAX,MAX] -deltas = [[-1,0], [1,0], [0,-1], [0,1]] + scores = Hash.new(Float::INFINITY) + scores[start] = 0 + frontier = [start] + visited = Set.new + until scores.has_key?(stop) + current = frontier.shift + visited << current -start = [0,0] -stop = [max,max] + neighbors = DELTAS.map {|delta| + current.zip(delta).map { _1 + _2 } + }.select {|xy| + xy.all? { (0..MAX).cover?(_1) } + }.reject {|xy| + corrupted.include?(xy) || visited.include?(xy) + } + neighbors.each do |xy| + scores[xy] = [scores[xy], scores.fetch(current) + 1].min + end -scores = Hash.new(Float::INFINITY) -scores[start] = 0 -frontier = [start] -visited = Set.new -until scores.has_key?(stop) - current = frontier.shift - visited << current + frontier.concat(neighbors) - neighbors = deltas.map {|delta| - current.zip(delta).map { _1 + _2 } - }.select {|xy| - xy.all? { (0..max).cover?(_1) } - }.reject {|xy| - corrupted.include?(xy) || visited.include?(xy) - } - neighbors.each do |xy| - scores[xy] = [scores[xy], scores.fetch(current) + 1].min + frontier.uniq! + frontier.sort_by! { scores.fetch(_1) } end - frontier.concat(neighbors) - - frontier.uniq! - frontier.sort_by! { scores.fetch(_1) } + scores.fetch(stop) end -pp scores.fetch(stop) +i = (0...falling_bytes.length).bsearch {|i| + begin + path(falling_bytes[0,i]) && false + rescue + true + end +} +puts falling_bytes.fetch(i-1).join(?,) __END__ 54,47