summaryrefslogtreecommitdiff
path: root/src/bin/day5.rs
blob: ea9a58b58c46d70f24fbdb857ae67b04f9cd90d8 (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
fn main() {
    let input = advent::read_lines(5);
    println!("5a: {}", count_nice(&input, is_nice));
    println!("5b: {}", count_nice(&input, is_nice2));
}

fn is_nice(word: &str) -> bool {
    let mut prev = ' ';
    let mut vowel_count = 0;
    let mut double_letter = false;

    for c in word.chars() {
        if ['a', 'e', 'i', 'o', 'u'].contains(&c) {
            vowel_count += 1;
        }
        if prev == c {
            double_letter = true;
        }
        let pair = format!("{}{}", prev, c);
        if ["ab".to_string(), "cd".to_string(), "pq".to_string(), "xy".to_string()].contains(&pair) {
            return false;
        }

        prev = c;
    }
    double_letter && vowel_count >= 3
}

fn has_two_pairs(word: &str) -> bool {
    let mut prev = ' ';

    for c in word.chars() {
        let pair = format!("{}{}", prev, c);

        if word.matches(&pair).count() > 1 {
            return true;
        }

        prev = c;
    }
    false
}

fn has_one_letter_repeat(word: &str) -> bool {
    let mut prev = ' ';
    let mut prevprev = ' ';

    for c in word.chars() {
        if c == prevprev {
            return true;
        }
        prevprev = prev;
        prev = c;
    }
    false
}

fn is_nice2(word: &str) -> bool {
    has_two_pairs(word) && has_one_letter_repeat(word)
}

fn count_nice(input: &[String], f: fn(&str) -> bool) -> usize {
    input.iter()
         .filter(|&x| f(x))
         .count()
}

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

    #[test]
    fn test() {
        assert!(is_nice("ugknbfddgicrmopn"));
        assert!(is_nice("aaa"));
        assert!(!is_nice("jchzalrnumimnmhp"));
        assert!(!is_nice("haegwjzuvuyypxyu"));
        assert!(!is_nice("dvszwmarrgswjxmb"));

        assert!(is_nice2("qjhvhtzxzqqjkmpb"));
        assert!(is_nice2("xxyxx"));
        assert!(!is_nice2("uurcxstgmygtbstg"));
        assert!(!is_nice2("ieodomkazucvgmuy"));
    }
}