summaryrefslogtreecommitdiffstats
path: root/src/day_6.rs
blob: 5983400c34e55bf6953411afb3c6f310ddc3f7b2 (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
use std::collections::HashSet;

use anyhow::Result;

use crate::{Problem, Solution};

fn get_window_pos(input: &str, win_size: usize) -> Option<usize> {
    input
        .as_bytes()
        .windows(win_size)
        .position(|set| {
            let mut h = HashSet::new();
            for &c in set {
                if !h.insert(c) {
                    return false;
                }
            }
            true
        })
        .map(|i| i + win_size)
}

pub struct Day6;

impl Problem for Day6 {
    const DAY: u8 = 6;

    const INPUT: &'static str = include_str!("../input/day_6.txt");
}

impl Solution for Day6 {
    type Answer1 = usize;

    type Answer2 = usize;

    fn part_1(input: &str) -> Result<Self::Answer1, anyhow::Error> {
        get_window_pos(input, 4).ok_or_else(|| anyhow::anyhow!("Failed to find item"))
    }

    fn part_2(input: &str) -> Result<Self::Answer2, anyhow::Error> {
        get_window_pos(input, 14).ok_or_else(|| anyhow::anyhow!("Failed to find item"))
    }
}

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

    #[test]
    fn test_part_1_example() -> Result<()> {
        let tests = vec![
            ("mjqjpqmgbljsphdztnvjfqwrcgsmlb", 7),
            ("bvwbjplbgvbhsrlpgdmjqwftvncz", 5),
            ("nppdvjthqldpwncqszvftbrmjlhg", 6),
            ("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 10),
            ("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 11),
        ];
        for test in tests {
            assert_eq!(test.1, Day6::part_1(test.0)?);
        }

        Ok(())
    }

    #[test]
    fn test_part_2_example() -> Result<()> {
        let tests = vec![
            ("mjqjpqmgbljsphdztnvjfqwrcgsmlb", 19),
            ("bvwbjplbgvbhsrlpgdmjqwftvncz", 23),
            ("nppdvjthqldpwncqszvftbrmjlhg", 23),
            ("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 29),
            ("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 26),
        ];
        for test in tests {
            assert_eq!(test.1, Day6::part_2(test.0)?);
        }

        Ok(())
    }
}