summaryrefslogtreecommitdiff
path: root/2023/rust/day6/src/lib.rs
blob: b3e33cbb906a678227e21d528211f946cf4a3c4d (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
pub fn part1(input: &str) -> u64 {
    let mut res: u64 = 1;

    let td: Vec<Vec<_>> = input
        .trim_end()
        .split('\n')
        .map(|x| {
            x.split(':')
                .nth(1)
                .unwrap()
                .trim()
                .replace("    ", " ")
                .replace("   ", " ")
                .replace("  ", " ")
                .split(' ')
                .map(|y| y.parse::<u64>().unwrap())
                .collect()
        })
        .collect();

    assert_eq!(td.len(), 2);
    let (t, d) = (&td[0], &td[1]);

    for i in 0..t.len() {
        let mut r = 0;
        for j in 0..t[i] {
            if (t[i] - j) * j > d[i] {
                r += 1;
            }
        }
        res *= r;
    }

    res
}

pub fn part2(input: &str) -> u64 {
    let mut res: u64 = 1;

    let td: Vec<Vec<_>> = input
        .trim_end()
        .split('\n')
        .map(|x| {
            x.split(':')
                .nth(1)
                .unwrap()
                .trim()
                .replace(" ", "")
                .split(' ')
                .map(|y| y.parse::<u64>().unwrap())
                .collect()
        })
        .collect();

    assert_eq!(td.len(), 2);
    let (t, d) = (&td[0], &td[1]);

    for i in 0..t.len() {
        let mut r = 0;
        for j in 0..t[i] {
            if (t[i] - j) * j > d[i] {
                r += 1;
            }
        }
        res *= r;
    }

    res
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn example_part1() {
        let input = include_str!("../example.txt");
        let result = part1(input);
        assert_eq!(result, 288);
    }

    #[test]
    fn input_part1() {
        let input = include_str!("../input.txt");
        let result = part1(input);
        assert_eq!(result, 74698);
    }

    #[test]
    fn example_part2() {
        let input = include_str!("../example.txt");
        let result = part2(input);
        assert_eq!(result, 71503);
    }

    #[test]
    fn input_part2() {
        let input = include_str!("../input.txt");
        let result = part2(input);
        assert_eq!(result, 27563421);
    }
}