[2022][ruby][8.x] refactored

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

@ -1,37 +1,34 @@
# grid = ARGF.read.lines(chomp: true).map {|row| row.chars.map { [_1.to_i, false] }}
# def mark!(ary)
# max = -1
# ary.each do |tree_counted|
# if tree_counted.first > max
# max = tree_counted.first
# tree_counted[1] = true
# end
# end
# end
grid = ARGF.read.lines(chomp: true).map { _1.chars.map(&:to_i) }
# grid.each { mark!(_1) }
# grid.each { mark!(_1.reverse) }
# grid.transpose.each { mark!(_1) }
# grid.transpose.each { mark!(_1.reverse) }
def each(grid)
return enum_for(__method__, grid) unless block_given?
# p grid.sum { _1.count(&:last) }
transposed = grid.transpose
grid = ARGF.read.lines(chomp: true).map { _1.chars.map(&:to_i) }
grid.each.with_index do |row, y|
row.each.with_index do |tree, x|
col = transposed[x]
def score(grid, y, x)
tree = grid[y][x]
sight_lines = [
(0...x).map { row[_1] }.reverse,
(x+1...row.size).map { row[_1] },
(0...y).map { col[_1] }.reverse,
(y+1...row.size).map { col[_1] },
]
[
(0...y).to_a.reverse.slice_after {|i| grid[i][x] >= tree }.first,
(y+1...grid.size).slice_after {|i| grid[i][x] >= tree }.first,
(0...x).to_a.reverse.slice_after {|i| grid[y][i] >= tree }.first,
(x+1...grid.size).slice_after {|i| grid[y][i] >= tree }.first,
].compact.map(&:size).inject(:*)
yield tree, sight_lines
end
end
end
p grid.flat_map.with_index {|row,y|
row.map.with_index {|tree,x|
score(grid, y, x)
p each(grid).count {|tree, sight_lines|
sight_lines.any? { _1.empty? || tree > _1.max }
}
p each(grid).map {|tree, sight_lines|
sight_lines
.map {|sl| sl.slice_after { _1 >= tree }.first }
.compact
.map(&:size)
.inject(:*)
}.max

Loading…
Cancel
Save