From 6110da0c69cf2912eba14e7aa3a040931e3de4a1 Mon Sep 17 00:00:00 2001 From: mflinn-broad Date: Thu, 9 Dec 2021 19:02:26 -0500 Subject: [PATCH] part 1 --- src/days/day9.rs | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/src/days/day9.rs b/src/days/day9.rs index b129d94..3da8aec 100644 --- a/src/days/day9.rs +++ b/src/days/day9.rs @@ -23,6 +23,25 @@ fn is_local_minima(target: u8, adjacents: Vec) -> bool { .all(|val| target < *val) } +fn get_adjacents(grid: &Vec>, pos: (usize, usize)) -> Vec { + let (row, col) = pos; + let mut adjacents: Vec = Vec::new(); + if row != 0 { + adjacents.push(grid[row - 1][col]); + } + if col != 0 { + adjacents.push(grid[row][col - 1]); + } + if row != (grid.len() - 1) { + adjacents.push(grid[row + 1][col]); + } + if col != (grid[0].len() - 1) { + adjacents.push(grid[row][col + 1]); + } + + adjacents +} + fn part_1(input: &Vec>) -> u32 { input.iter() .enumerate() @@ -30,19 +49,7 @@ fn part_1(input: &Vec>) -> u32 { risk_score + row.iter() .enumerate() .fold(0, |row_risk, (col, height)| { - let mut adjacents: Vec = Vec::new(); - if row_idx != 0 { - adjacents.push(input[row_idx - 1][col]); - } - if col != 0 { - adjacents.push(input[row_idx][col - 1]); - } - if row_idx != (input.len() - 1) { - adjacents.push(input[row_idx + 1][col]); - } - if col != (input[0].len() - 1) { - adjacents.push(input[row_idx][col + 1]); - } + let adjacents = get_adjacents(input, (row_idx, col)); if is_local_minima(*height, adjacents) { row_risk + (*height as u32) + 1 } else {