Skip to content

Instantly share code, notes, and snippets.

@thomasweitzel
Created December 8, 2022 21:52
Show Gist options
  • Save thomasweitzel/edc818b8e13948125c686f4bda57f98f to your computer and use it in GitHub Desktop.
Save thomasweitzel/edc818b8e13948125c686f4bda57f98f to your computer and use it in GitHub Desktop.
Advent of Code 2022, my solution for day 08
// See: https://adventofcode.com/2022/day/8
fn parse(input: &str) -> Vec<Vec<u32>> {
input
.lines()
.map(|line| {
line.chars().map(|c| c.to_digit(10).expect("NaN")).collect()
})
.collect()
}
fn create_matrix(r: usize, c: usize, v: u32) -> Vec<Vec<u32>> {
let mut m: Vec<Vec<u32>> = vec![];
for _ in 0..r {
m.push(vec![v; c]);
}
m
}
fn visible(m: &Vec<Vec<u32>>) -> Vec<Vec<u32>> {
let rows = m.len();
let columns = m[0].len();
let mut mv = create_matrix(rows, columns, 0);
for r in 0..rows {
for c in 0..columns {
// Determine visibility of [r][c]
let from_left = (0..c).all(|y| m[r][y] < m[r][c]);
let from_right = ((c + 1)..columns).all(|y| m[r][y] < m[r][c]);
let from_top = (0..r).all(|x| m[x][c] < m[r][c]);
let from_bottom = ((r + 1)..rows).all(|x| m[x][c] < m[r][c]);
if from_left || from_right || from_top || from_bottom {
mv[r][c] = 1;
}
}
}
mv
}
fn scenic_score(m: &Vec<Vec<u32>>) -> Vec<Vec<u32>> {
let rows = m.len();
let columns = m[0].len();
let mut mv = create_matrix(rows, columns, 0);
for r in 0..rows {
for c in 0..columns {
// Determine scenic score of [r][c]
let to_left = c - (0..c).rev().find(|&y| m[r][y] >= m[r][c]).unwrap_or(0);
let to_right = ((c + 1)..columns).find(|&y| m[r][y] >= m[r][c]).unwrap_or(columns - 1) - c;
let to_top = r - (0..r).rev().find(|&x| m[x][c] >= m[r][c]).unwrap_or(0);
let to_bottom = ((r + 1)..rows).find(|&x| m[x][c] >= m[r][c]).unwrap_or(rows - 1) - r;
mv[r][c] = (to_left * to_right * to_top * to_bottom) as u32;
}
}
mv
}
pub fn part_one(input: &str) -> u32 {
let m = parse(input);
let mv = visible(&m);
let visible_count: usize = mv.iter().map(|r| r.iter().filter(|&c| *c == 1).count()).sum();
visible_count as u32
}
pub fn part_two(input: &str) -> u32 {
let m = parse(input);
let ms = scenic_score(&m);
let max_scenic_score = ms.iter().map(|r| r.iter().max().unwrap_or(&0)).max().unwrap_or(&0);
*max_scenic_score
}
fn main() {
let input = include_str!("day08.txt");
println!("Part 1 = {:?}", part_one(input));
println!("Part 2 = {:?}", part_two(input));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment