summaryrefslogtreecommitdiffstats
path: root/day1/src/main.rs
blob: fd7856386f94f929c85ef95e836ba041e048680e (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
struct Day1 {}

impl Day1 {
    fn part_n(&self, input: BufReader<Box<dyn Read>>) -> (Vec<u32>, Vec<u32>) {
        let mut a: Vec<u32> = vec![];
        let mut b: Vec<u32> = vec![];

        for line in self.read_lines(input) {
            let mut s = line.split(' ');

            loop {
                let ia = s.next().unwrap();

                let num = match ia.parse::<u32>() {
                    Ok(num) => num,
                    Err(_) => continue,
                };

                a.push(num);
                break;
            }

            loop {
                let ib = s.next_back().unwrap();

                let num = match ib.parse::<u32>() {
                    Ok(num) => num,
                    Err(_) => continue,
                };

                b.push(num);
                break;
            }
        }

        (a, b)
    }
}

impl Day for Day1 {
    fn example_input(&self) -> &'static str {
        r#"
        3   4
        4   3
        2   5
        1   3
        3   9
        3   3
        "#.trim()
    }

    fn example_result_part_1(&self) -> &'static str {
        "11"
    }

    fn example_result_part_2(&self) -> &'static str {
        "31"
    }

    fn part_1(&self, input: BufReader<Box<dyn Read>>) -> String {
        let (mut a, mut b) = self.part_n(input);

        a.sort();
        b.sort();

        let mut distances: Vec<u32> = vec![];
        for (ia, ib) in a.iter().zip(b) {
            if *ia > ib {
                distances.push(ia - ib);
            } else {
                distances.push(ib - ia);
            }
        }

         format!("{}", (distances.iter().sum::<u32>()))
    }

    fn part_2(&self, input: BufReader<Box<dyn Read>>) -> String {
        let (a, b) = self.part_n(input);

        let mut scores: Vec<u32> = vec![];
        for item in a {
            let count = b.iter().filter(|&&i| i == item).count();
            scores.push(item * count as u32);
        }

        format!("{}", (scores.iter().sum::<u32>()))
    }
}

use aoc;
use std::io::{BufReader, Read};
use aoc::Day;

fn main() {
    aoc::main(&Day1 {});
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_day1() {
        aoc::test_day(&Day1 {});
    }
}