Skip to content

Instantly share code, notes, and snippets.

@saolsen
Created December 8, 2022 14:09
Show Gist options
  • Save saolsen/73163c5253850d10586d665016dfdb30 to your computer and use it in GitHub Desktop.
Save saolsen/73163c5253850d10586d665016dfdb30 to your computer and use it in GitHub Desktop.
aoc 2022 day08
use core::num;
fn parse(input: &str) -> Vec<Vec<u32>> {
let mut grid = vec![];
for line in input.split("\n") {
let mut row = vec![];
for c in line.chars() {
let i = c.to_digit(10).unwrap();
row.push(i);
}
grid.push(row);
}
grid
}
fn is_visible(grid: &Vec<Vec<u32>>, x: usize, y: usize) -> bool {
let tree_height = grid[y][x];
// from the left
let mut from_left = true;
for i in 0..x {
if grid[y][i] >= tree_height {
from_left = false;
break;
}
}
// from the right
let mut from_right = true;
for i in x + 1..grid[y].len() {
if grid[y][i] >= tree_height {
from_right = false;
break;
}
}
// from the top
let mut from_top = true;
for i in 0..y {
if grid[i][x] >= tree_height {
from_top = false;
break;
}
}
// from the bottom
let mut from_bottom = true;
for i in y + 1..grid.len() {
if grid[i][x] >= tree_height {
from_bottom = false;
break;
}
}
from_left || from_right || from_top || from_bottom
}
fn scenic_score(grid: &Vec<Vec<u32>>, x: usize, y: usize) -> i32 {
let tree_height = grid[y][x];
let mut left_score = 0;
for i in (0..x).rev() {
left_score += 1;
if grid[y][i] >= tree_height {
break;
}
}
let mut right_score = 0;
for i in x + 1..grid[y].len() {
right_score += 1;
if grid[y][i] >= tree_height {
break;
}
}
let mut up_score = 0;
for i in (0..y).rev() {
up_score += 1;
if grid[i][x] >= tree_height {
break;
}
}
let mut down_score = 0;
for i in y + 1..grid.len() {
down_score += 1;
if grid[i][x] >= tree_height {
break;
}
}
left_score * right_score * up_score * down_score
}
fn main() {
let grid = parse(include_str!("day08_input.txt"));
// could just brute force check each tree.
let mut num_visible = 0;
let mut max_score = 0;
for y in 0..grid.len() {
for x in 0..grid[y].len() {
if is_visible(&grid, x, y) {
num_visible += 1;
}
let score = scenic_score(&grid, x, y);
if score > max_score {
max_score = score;
}
}
}
eprintln!("num visible: {num_visible}");
eprintln!("max score: {max_score}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment