Day 6 speed update

This commit is contained in:
Max 2022-12-06 12:04:21 +01:00
parent 807a59b819
commit d1be2b22e0

View File

@ -1,22 +1,29 @@
use std::{collections::HashSet, fs::read_to_string}; use std::{collections::HashSet, fs::read_to_string};
fn find_nonrecuring_sequence(input: &[char], length: usize) -> usize { fn find_nonrecuring_sequence(input: &[char], length: usize) -> Option<usize> {
input input
.windows(length) .windows(length)
.enumerate() .enumerate()
.find(|(_, chars)| chars.iter().collect::<HashSet<_>>().len() == length) .find(|(_, chars)| {
.unwrap_or((input.len(), &[])) for i in 1..chars.len() {
.0 if chars[..i].contains(&chars[i]) {
+ length return false;
}
}
true
})
//.find(|(_, chars)| chars.iter().collect::<HashSet<_>>().len() == length)
.map(|(i, _)| i + length)
} }
fn main() { fn main() -> Result<(), std::io::Error> {
const PACKET_START_LENGTH: usize = 4; const PACKET_START_LENGTH: usize = 4;
const MESSAGE_START_LENGTH: usize = 14; const MESSAGE_START_LENGTH: usize = 14;
let input = read_to_string("input.txt").unwrap(); let input = read_to_string("input.txt")?;
let input = input.chars().collect::<Vec<_>>(); let input = input.chars().collect::<Vec<_>>();
let packet_marker = find_nonrecuring_sequence(&input, PACKET_START_LENGTH); let packet_marker = find_nonrecuring_sequence(&input, PACKET_START_LENGTH);
println!("first packet marker at {packet_marker}"); println!("first packet marker at {packet_marker:?}");
let message_marker = find_nonrecuring_sequence(&input, MESSAGE_START_LENGTH); let message_marker = find_nonrecuring_sequence(&input, MESSAGE_START_LENGTH);
println!("first message marker at {message_marker}"); println!("first message marker at {message_marker:?}");
Ok(())
} }