diff --git a/day05/example.txt b/day05/example.txt index 02edcf2..2fc793b 100644 --- a/day05/example.txt +++ b/day05/example.txt @@ -1,9 +1,13 @@ -ugknbfddgicrmopn -aaa -jchzalrnumimnmhp -haegwjzuvuyypxyu -dvszwmarrgswjxmb -qjhvhtzxzqqjkmpb -xxyxx -uurcxstgmygtbstg -ieodomkazucvgmuy +#ugknbfddgicrmopn +#aaa +#jchzalrnumimnmhp +#haegwjzuvuyypxyu +#dvszwmarrgswjxmb + +#qjhvhtzxzqqjkmpb +#xxyxx +#uurcxstgmygtbstg +#ieodomkazucvgmuy +#aaa +xyxy +#aabcdefgaa diff --git a/day05/src/main.rs b/day05/src/main.rs index c8d9c63..b78cbac 100644 --- a/day05/src/main.rs +++ b/day05/src/main.rs @@ -14,14 +14,18 @@ fn main() { } fn part_1_and_2 bool>(data: &str, f: T) { - let sum = data.lines().filter(f).count(); + let sum = data + .lines() + .filter(|line| !line.starts_with('#')) + .filter(f) + .count(); println!("{sum}"); } fn is_nice_1(s: &&str) -> bool { let vowel_count = s.chars().filter(|c| VOWELS.contains(*c)).count(); - let double_letter = s.chars().zip(s.chars().skip(1)).any(|(a, b)| a == b); + let has_double_letter = s.chars().zip(s.chars().skip(1)).any(|(a, b)| a == b); let has_forbidden_tuple = s .chars() @@ -29,14 +33,53 @@ fn is_nice_1(s: &&str) -> bool { .map(|(a, b)| format!("{a}{b}")) .any(|tuple| FORBIDDEN.contains(&tuple.as_str())); - vowel_count >= 3 && double_letter && !has_forbidden_tuple + vowel_count >= 3 && has_double_letter && !has_forbidden_tuple } fn is_nice_2(s: &&str) -> bool { let mut subrule_1 = false; - let mut subrule_2 = false; + + let mut digraphs = extract_digraphs(s); + + digraphs.sort_unstable(); + + let double_digraphs = digraphs + .iter() + .zip(digraphs.iter().skip(1)) + .filter(|(a, b)| a == b) + .map(|(a, _)| a.clone()); + + for dd in double_digraphs { + // can't use the other one again because we + // need it unsorted here + let digraphs = extract_digraphs(s); + + let mut iter = digraphs.into_iter(); + let idx1 = iter.position(|x| x == *dd).unwrap(); + let idx2 = iter.position(|x| x == *dd).unwrap() + idx1 + 1; + + if idx2.abs_diff(idx1) >= 2 { + subrule_1 = true; + break; + } + } + + let repeated_letter = s + .chars() + .zip(s.chars().skip(2)) + .find(|(a, b)| a == b) + .map(|(a, _)| a); + + let subrule_2 = repeated_letter.is_some(); subrule_1 && subrule_2 } +fn extract_digraphs(s: &&str) -> Vec { + s.chars() + .zip(s.chars().skip(1)) + .map(|(a, b)| format!("{a}{b}")) + .collect() +} + // https://adventofcode.com/2015/day/5