advent_of_code/year2018/
day02.rs

1use crate::input::Input;
2use std::collections::HashMap;
3
4pub fn solve(input: &Input) -> Result<String, String> {
5    if input.is_part_one() {
6        let picks = input.text.lines().fold((0, 0), |state, line| {
7            let mut occurrences = HashMap::new();
8
9            line.chars()
10                .for_each(|c| *occurrences.entry(c).or_insert(0) += 1);
11
12            let has_occurrence = |count| occurrences.iter().any(|(_key, &value)| value == count);
13
14            (
15                state.0 + i64::from(has_occurrence(2)),
16                state.1 + i64::from(has_occurrence(3)),
17            )
18        });
19
20        Ok((picks.0 * picks.1).to_string())
21    } else {
22        fn common_chars<'a>(s1: &'a str, s2: &'a str) -> impl Iterator<Item = char> + 'a {
23            s1.chars()
24                .zip(s2.chars())
25                .filter_map(|(c1, c2)| if c1 == c2 { Some(c1) } else { None })
26        }
27
28        let input: Vec<&str> = input.text.lines().collect();
29
30        for i in 0..input.len() {
31            for j in i + 1..input.len() {
32                let s1 = input[i];
33                let s2 = input[j];
34
35                if common_chars(s1, s2).count() + 1 == s1.len() {
36                    return Ok(common_chars(s1, s2).collect::<String>());
37                }
38            }
39        }
40
41        Err("No solution found".to_string())
42    }
43}
44
45#[test]
46fn tests() {
47    use crate::input::{test_part_one, test_part_two};
48
49    test_part_one!(
50                    "abcdef
51bababc
52abbcde
53abcccd
54aabcdd
55abcdee
56ababab
57"
58 => "12".into());
59
60    let input = include_str!("day02_input.txt");
61    test_part_one!(input => "6972".into());
62
63    test_part_two!(
64            "abcde
65fghij
66klmno
67pqrst
68fguij
69axcye
70wvxyz
71"
72        =>"fgij".into()
73    );
74
75    test_part_two!(
76        input=>
77            "aixwcbzrmdvpsjfgllthdyoqe".into()
78    );
79}