#!/usr/bin/env ruby require_relative '../common' class Day08 < Day def part1 grid = stdin.map { |r| r.chars.map(&:to_i) } grid.each_with_index.inject(0) do |visible, (row, i)| visible + row.each_with_index.inject(0) do |row_visible, (tree, j)| if i == 0 || i == grid.size - 1 || j == 0 || j == row.size - 1 || [row[0...j], row[j + 1..], grid[0...i].map { |k| k[j] }, grid[i + 1..].map { |k| k[j] }].map(&:max).any? { |k| k < tree } row_visible + 1 else row_visible end end end end def part2 grid = stdin.map { |r| r.chars.map(&:to_i) } grid.each_with_index.inject(0) do |max_scenic_score, (row, i)| scenic_score = row.each_with_index.inject(0) do |max_scenic_score_row, (tree, j)| scenic_score_row = [ row[0...j].reverse, row[j + 1..], grid[0...i].map { |k| k[j] }.reverse, grid[i + 1..].map { |k| k[j] } ].map do |direction| taller_tree = direction.detect { |t| t >= tree } if taller_tree direction.index(taller_tree) + 1 else direction.size end end.inject(:*) if scenic_score_row > max_scenic_score_row scenic_score_row else max_scenic_score_row end end if scenic_score > max_scenic_score scenic_score else max_scenic_score end end end end Day08.run