1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
grid = ARGF.read.lines(chomp: true).map { _1.chars.map(&:to_i) }

def each(grid)
  return enum_for(__method__, grid) unless block_given?

  transposed = grid.transpose

  grid.each.with_index do |row, y|
    row.each.with_index do |tree, x|
      col = transposed[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] },
      ]

      yield tree, sight_lines
    end
  end
end

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