summaryrefslogtreecommitdiff
path: root/2020/rust/day03/src/main.rs
blob: 900bd8ac9ecf4d544c59d39b32646e03522ad292 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
use anyhow::{Result, anyhow};
use std::env::args;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::ops::AddAssign;
use std::path::Path;
use thiserror::Error;

#[derive(Clone,Copy)]
struct CoordPair {
    x: usize,
    y: usize,
}

impl AddAssign for CoordPair {
    fn add_assign(&mut self, other: Self) {
        *self = Self {
            x: self.x + other.x,
            y: self.y + other.y,
        };
    }
}

#[derive(Debug)]
struct TreeMap {
    width: usize,
    height: usize,
    map: Vec<bool>,
}

#[derive(Error, Debug)]
pub enum TreeError {
    #[error("Could not access TreeMap")]
    Invalid,
}

impl TreeMap {
    fn is_tree(&self, pos: CoordPair) -> Result<bool, TreeError> {
        let mut p = pos;
        p.x %= self.width;
        self.map.get(p.y * self.width + p.x).copied().ok_or(TreeError::Invalid)
    }
}

fn read_input<T: AsRef<Path>>(filename: T) -> Result<TreeMap> {
    let f = File::open(filename)?;
    let reader = BufReader::new(f);

    let tree_map = reader.lines()
        .fold(Ok(TreeMap { width: 0, height: 0, map: vec![] }), |acc, l| {
            let line = l?;
            let row: Result<Vec<bool>> = line.chars().map(|c| match c {
                '#' => Ok(true),
                '.' => Ok(false),
                _ => Err(anyhow!("Invalid map character: '{}'", c)),
            }).collect();

            match acc {
                Ok(mut a) => {
                    a.map.append(&mut row?);
                    a.height += 1;
                    Ok(a)
                },
                Err(err) => Err(err)
            }
        });
    match tree_map {
        Ok(mut tm) => {
            tm.width = tm.map.len()/tm.height;
            Ok(tm)
        },
        err => err,
    }
}

fn part1(input: &TreeMap) -> Result<usize> {
    let mut pos = CoordPair { x: 0, y: 0, };
    let slope = CoordPair { x: 3, y: 1, };
    let mut collision_count = 0;

    while pos.y < input.height {
        if input.is_tree(pos)? {
            collision_count += 1;
        }
        pos += slope;
    }

    Ok(collision_count)
}

fn part2(input: &TreeMap) -> Result<usize> {
    let slopes = vec![
        CoordPair { x: 1, y: 1, },
        CoordPair { x: 3, y: 1, },
        CoordPair { x: 5, y: 1, },
        CoordPair { x: 7, y: 1, },
        CoordPair { x: 1, y: 2, },
    ];

    let res = slopes.iter().map(|slope| {
        let mut pos = CoordPair { x: 0, y: 0, };
        let mut collision_count = 0;

        while pos.y < input.height {
            if input.is_tree(pos)? {
                collision_count += 1;
            }
            pos += *slope;
        }

        Ok(collision_count)
    }).product();

    res
}

fn main() {
    let ( do_part_1, do_part_2 ) = aoc::do_parts();

    let filename = match args().nth(1) {
        Some(f) => f,
        None => {
            eprintln!("Missing input filename");
            std::process::exit(1);
        },
    };
    match read_input(filename) {
        Ok(input) => {
            if do_part_1 {
                match part1(&input) {
                    Ok(solution) => println!("Part1: would encounter {} trees", solution),
                    Err(err) => {
                        eprintln!("Part1, no solution found: {}", err);
                        std::process::exit(1);
                    }
                };
            }
            if do_part_2 {
                match part2(&input) {
                    Ok(solution) => println!("Part2: {} is the product of all tree collisions", solution),
                    Err(err) => {
                        eprintln!("Part2, no solution found: {}", err);
                        std::process::exit(1);
                    }
                };
            }
        },
        Err(err) => eprintln!("Could not read input: {}", err),
    }
}