From 389693dabc38ff06178b89e579d8ac2330d9b0e7 Mon Sep 17 00:00:00 2001 From: Antoine Martin Date: Thu, 3 Dec 2020 17:22:43 +0100 Subject: [PATCH] 2020: day03: refacto for part 2 --- aoc2020/src/day03.rs | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/aoc2020/src/day03.rs b/aoc2020/src/day03.rs index 2c7331c..7804cf0 100644 --- a/aoc2020/src/day03.rs +++ b/aoc2020/src/day03.rs @@ -13,25 +13,17 @@ pub fn run() -> aoc::Result { Ok(res) } -fn part1(input: &str) -> aoc::Result { +fn part1(input: &str) -> aoc::Result { let forest = input.parse()?; - Ok(count_trees(forest)) + Ok(count_trees(&forest, (3, 1))) } -fn count_trees(forest: Forest) -> u64 { - let mut count = 0; +fn count_trees(forest: &Forest, (right, down): (usize, usize)) -> usize { + let vertical_range = (0..forest.height()).step_by(down); + let horizontal_range = (0..).step_by(right); - let vertical_range = 0..forest.height(); - let horizontal_range = (0..).step_by(3); - - for (i, j) in vertical_range.zip(horizontal_range) { - if forest[i][j] { - count += 1 - } - } - - count + vertical_range.zip(horizontal_range).filter(|(i, j)| forest[*i][*j]).count() } #[derive(Debug)] @@ -87,14 +79,7 @@ impl FromStr for Forest { fn from_str(s: &str) -> aoc::Result { let trees = s .lines() - .map(|line| { - line.chars() - .map(|c| match c { - '.' => false, - _ => true, - }) - .collect() - }) + .map(|line| line.chars().map(|c| matches!(c, '#')).collect()) .collect(); Ok(Self { trees })