~xenrox/aoc2020

58b1210a2cc8f0c0572fdc721ea1e13b95322a5c — Thorben Günther 1 year, 4 months ago 9fdf5d6
Solve day 3 part 2
1 files changed, 33 insertions(+), 7 deletions(-)

M src/days/day03.rs
M src/days/day03.rs => src/days/day03.rs +33 -7
@@ 8,7 8,7 @@ fn parse_contents(contents: String) -> Vec<Vec<char>> {
    map
}

fn count_trees(map: &Vec<Vec<char>>) -> i32 {
fn count_trees(map: &Vec<Vec<char>>, x_add: usize, y_add: usize) -> i32 {
    let mut x = 0;
    let mut y = 0;
    let mut count = 0;


@@ 16,9 16,9 @@ fn count_trees(map: &Vec<Vec<char>>) -> i32 {
    let x_max = map[0].len();
    let y_max = map.len();

    while y != y_max - 1 {
        y += 1;
        x = (x + 3) % x_max;
    while y < y_max - y_add {
        y += y_add;
        x = (x + x_add) % x_max;
        if map[y][x] == '#' {
            count += 1;
        }


@@ 26,12 26,30 @@ fn count_trees(map: &Vec<Vec<char>>) -> i32 {
    count
}

fn calc_solution2(map: &Vec<Vec<char>>) -> i64 {
    // Using only i32 would cause on overflow
    let mut product: i64 = 1;
    let mut count = count_trees(map, 1, 1);
    product *= count as i64;
    count = count_trees(map, 3, 1);
    product *= count as i64;
    count = count_trees(map, 5, 1);
    product *= count as i64;
    count = count_trees(map, 7, 1);
    product *= count as i64;
    count = count_trees(map, 1, 2);
    product *= count as i64;
    product
}

pub fn get_solution() {
    let contents = fs::read_to_string("data/day03.dat").expect("Could not read data");
    let map = parse_contents(contents);
    let count = count_trees(&map);
    let count = count_trees(&map, 3, 1);

    println!("Day 3, part 1: {}", count);
    let product = calc_solution2(&map);

    println!("Day 3, part 1: {}, part 2: {}", count, product);
}

#[cfg(test)]


@@ 42,7 60,15 @@ mod tests {
    fn part1() {
        let contents = fs::read_to_string("data/day03_test.dat").expect("Could not read data");
        let map = parse_contents(contents);
        let count = count_trees(&map);
        let count = count_trees(&map, 3, 1);
        assert_eq!(count, 7);
    }

    #[test]
    fn part2() {
        let contents = fs::read_to_string("data/day03_test.dat").expect("Could not read data");
        let map = parse_contents(contents);
        let product = calc_solution2(&map);
        assert_eq!(product, 336);
    }
}