diff options
Diffstat (limited to '2022/src/day06.rs')
-rw-r--r-- | 2022/src/day06.rs | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/2022/src/day06.rs b/2022/src/day06.rs new file mode 100644 index 0000000..8bbfe6d --- /dev/null +++ b/2022/src/day06.rs @@ -0,0 +1,47 @@ +mod utils; +use utils::read_input; + +fn main() { + let input = read_input(); + + println!("Part 1: {}", find_chunk_nodup::<4>(&input)); + println!("Part 2: {}", find_chunk_nodup::<14>(&input)); +} + +fn find_chunk_nodup<const N: usize>(input: &str) -> usize { + let mut window = ['a'; N]; + let mut chars = input.chars(); + + // Fill up initial window + for item in window.iter_mut() { + *item = chars.next().unwrap(); + } + + for i in 0..input.len() { + // Shuffle everything in window down + for j in 0..N - 1 { + window[j] = window[j + 1]; + } + window[N - 1] = chars.next().unwrap(); + + if window + .iter() + .fold(Some(0), |acc, chr| add_char(acc?, *chr)) + .is_some() + { + return i + N + 1; + } + } + + panic!("no solution!") +} + +#[inline] +fn add_char(bits: u32, chr: char) -> Option<u32> { + let add = 1 << (chr.to_ascii_lowercase() as u32 - 97); + if (bits | add) != bits { + Some(bits | add) + } else { + None + } +} |