[2022][ruby][12.x] refactored

pull/1/head
Alpha Chen 2 years ago
parent 44936f2906
commit e12d4d7c63
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -1,47 +1,20 @@
height_map = ARGF.read.lines(chomp: true).map(&:chars) heights = ARGF.read.lines(chomp: true).map(&:chars)
.each.with_index.with_object({}) do |(row,y),map| .each.with_index.with_object({}) do |(row,y),map|
row.each.with_index do |height,x| row.each.with_index do |height,x|
map[[y,x]] = height map[[y,x]] = height
end end
end end
s, e = height_map.invert.values_at(?S, ?E) class HeightMap
height_map[s] = ?a def initialize(heights)
height_map[e] = ?z @heights = heights
end
# part one
# queue = [s]
# visited = { s => 0 }
# until visited.has_key?(e)
# current = queue.shift
# moves = visited.fetch(current)
# neighbors = [
# [-1, 0],
# [ 1, 0],
# [ 0, -1],
# [ 0, 1],
# ].map { current.zip(_1).map {|a,b| a + b } }
# .select { height_map.has_key?(_1) }
# .reject { visited.has_key?(_1) }
# .select { height_map.fetch(_1).ord - 1 <= height_map.fetch(current).ord }
# neighbors.each do |y,x|
# visited[[y,x]] = moves + 1
# queue << [y,x]
# end
# queue.sort_by { visited.fetch(_1) }
# end
# p visited.fetch(e)
# part two def shortest(from:, to:)
queue = [e] queue = [from]
visited = { e => 0 } visited = { from => 0 }
loop do until queue.empty? || visited.has_key?(to)
current = queue.shift current = queue.shift
moves = visited.fetch(current) moves = visited.fetch(current)
@ -51,14 +24,9 @@ loop do
[ 0, -1], [ 0, -1],
[ 0, 1], [ 0, 1],
].map { current.zip(_1).map {|a,b| a + b } } ].map { current.zip(_1).map {|a,b| a + b } }
.select { height_map.has_key?(_1) } .select { @heights.has_key?(_1) }
.reject { visited.has_key?(_1) } .reject { visited.has_key?(_1) }
.select { height_map.fetch(current).ord <= height_map.fetch(_1).ord + 1 } .select { @heights.fetch(_1).ord - 1 <= @heights.fetch(current).ord }
if a = neighbors.find { height_map.fetch(_1) == ?a }
p moves + 1
break
end
neighbors.each do |y,x| neighbors.each do |y,x|
visited[[y,x]] = moves + 1 visited[[y,x]] = moves + 1
@ -66,4 +34,17 @@ loop do
end end
queue.sort_by { visited.fetch(_1) } queue.sort_by { visited.fetch(_1) }
end
visited.fetch(to, nil)
end
end end
s, e = heights.invert.values_at(?S, ?E)
heights[s] = ?a
heights[e] = ?z
hm = HeightMap.new(heights)
p hm.shortest(from: s, to: e)
p heights.select { _2 == ?a }.map(&:first).map { hm.shortest(from: _1, to: e) }.compact.min

Loading…
Cancel
Save