1
0
mirror of https://github.com/chylex/Advent-of-Code.git synced 2025-06-02 06:34:05 +02:00

Add 2020 - Day 3 - Part 2

This commit is contained in:
chylex 2022-02-23 05:45:16 +01:00
parent 4cb654dd2f
commit 63f86596b2
Signed by: chylex
GPG Key ID: 4DE42C8F19A80548

View File

@ -2,8 +2,6 @@ use std::error::Error;
use grid::{Grid, GridLine}; use grid::{Grid, GridLine};
use crate::grid::Cell;
#[path = "../utils/mod.rs"] #[path = "../utils/mod.rs"]
mod utils; mod utils;
@ -11,24 +9,22 @@ fn main() -> Result<(), Box<dyn Error>> {
let lines = utils::parse_input_lines::<GridLine>()?; let lines = utils::parse_input_lines::<GridLine>()?;
let grid = Grid::from(lines)?; let grid = Grid::from(lines)?;
let mut x = 0; println!("Total trees on slope going 3 right 1 down: {}", grid.count_trees_on_slope(3, 1));
let mut y = 0;
let mut trees = 0;
loop { let mut product = 1u32;
match grid.get_at(x, y) { let slopes = vec![
None => break, (1, 1),
Some(Cell::Open) => {} (3, 1),
Some(Cell::Tree) => { (5, 1),
trees += 1; (7, 1),
} (1, 2)
} ];
x += 3; for (down, right) in slopes {
y += 1; product *= grid.count_trees_on_slope(down, right);
} }
println!("Total trees: {}", trees); println!("Product of all attempted slopes: {}", product);
Ok(()) Ok(())
} }
@ -58,6 +54,27 @@ mod grid {
let line = self.data.get(y as usize)?; let line = self.data.get(y as usize)?;
Some(line.get_at(x)) Some(line.get_at(x))
} }
pub fn count_trees_on_slope(&self, step_x: i32, step_y: i32) -> u32 {
let mut x = 0;
let mut y = 0;
let mut trees = 0u32;
loop {
match self.get_at(x, y) {
None => break,
Some(Cell::Open) => {}
Some(Cell::Tree) => {
trees += 1;
}
}
x += step_x;
y += step_y;
}
return trees;
}
} }
pub struct GridLine { pub struct GridLine {