Implementation day 3

This commit is contained in:
2020-12-03 08:53:49 +01:00
parent 1df2a6f54d
commit eedbe874bd
5 changed files with 419 additions and 0 deletions

View File

@@ -34,6 +34,30 @@ where
buf.trim().parse().unwrap()
}
pub fn read_char_grid(input: &mut dyn Read) -> Vec<Vec<u8>> {
let mut reader = BufReader::new(input);
let mut buffer = Vec::new();
let mut grid = Vec::new();
while let Ok(read) = reader.read_until(b'\n', &mut buffer) {
if read == 0 {
break;
}
let line: &[u8] = if let Some(&b'\n') = buffer.last() {
&buffer[..(buffer.len() - 1)]
} else {
&buffer[..]
};
grid.push(line.to_owned());
buffer.clear();
}
grid
}
/// An interface to count elements in particular categories.
pub trait GroupingCount {
/// The type of the categories under inspection

60
2020/src/day03.rs Normal file
View File

@@ -0,0 +1,60 @@
use std::io::Read;
use crate::common::read_char_grid;
use crate::Solution;
#[derive(Default)]
pub struct Day03;
fn walk(right: usize, down: usize, forrest: &[Vec<u8>]) -> usize {
let mut trees = 0;
let mut x = 0;
for line in forrest.iter().step_by(down) {
if line[x] == b'#' {
trees += 1;
}
x = (x + right) % line.len();
}
trees
}
impl Solution for Day03 {
fn part1(&mut self, input: &mut dyn Read) -> String {
let forrest = read_char_grid(input);
walk(3, 1, &forrest).to_string()
}
fn part2(&mut self, input: &mut dyn Read) -> String {
let forrest = read_char_grid(input);
let mut product = 1;
for &(right, down) in &[(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] {
product *= walk(right, down, &forrest);
}
product.to_string()
}
}
#[cfg(test)]
mod tests {
use crate::test_implementation;
use super::*;
const SAMPLE: &[u8] = include_bytes!("../samples/03.txt");
#[test]
fn sample_part1() {
test_implementation!(Day03, 1, SAMPLE, 7);
}
#[test]
fn sample_part2() {
test_implementation!(Day03, 2, SAMPLE, 336);
}
}

View File

@@ -17,6 +17,7 @@ pub fn get_implementation(day: usize) -> Box<dyn Solution> {
match day {
1 => Box::new(day01::Day01::default()),
2 => Box::new(day02::Day02::default()),
3 => Box::new(day03::Day03::default()),
_ => panic!("Unsupported day {}", day),
}
}