diff --git a/2022/day6/rust/src/main.rs b/2022/day6/rust/src/main.rs index a8bd880..c02b708 100644 --- a/2022/day6/rust/src/main.rs +++ b/2022/day6/rust/src/main.rs @@ -1,29 +1,25 @@ #![warn(clippy::pedantic)] -use std::{ - collections::HashSet, - io::{stdin, Read}, -}; +use std::io::{stdin, Read}; -use aoc::*; +fn all_distinct(slice: &[T]) -> bool { + slice + .iter() + .enumerate() + .all(|(i, x)| slice[i + 1..].iter().all(|y| y != x)) +} + +fn end_of_first_distinct_run(data: &[T], len: usize) -> Option { + data.windows(len) + .position(|cs| all_distinct(cs)) + .map(|i| i + len) +} fn main() { let mut data = String::new(); stdin().read_to_string(&mut data).unwrap(); + let data = data.as_bytes(); - let i = data - .as_bytes() - .windows(4) - .position(|cs| HashSet::::from_iter(cs.into_iter().copied()).len() == 4) - .unwrap(); - - println!("{:?}", i + 4); - - let i = data - .as_bytes() - .windows(14) - .position(|cs| HashSet::::from_iter(cs.into_iter().copied()).len() == 14) - .unwrap(); - - println!("{:?}", i + 14); + println!("{:?}", end_of_first_distinct_run(data, 4).unwrap()); + println!("{:?}", end_of_first_distinct_run(data, 14).unwrap()); }