[2022][ruby][8.x] refactored
change lyorolkkxrluyvpunyyyrkkkrkonxmzw
commit 3adcbd6d722ea9a9e1e9c1a3651a5125b064b846
author Alpha Chen <alpha@kejadlen.dev>
date
parent msrmkspx
diff --git a/2022/ruby/day_08.rb b/2022/ruby/day_08.rb
index aa98b9d..8ca8954 100644
--- a/2022/ruby/day_08.rb
+++ b/2022/ruby/day_08.rb
@@ -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