AOC2022/rust/6/part1.rs
2022-12-07 00:04:57 +00:00

36 lines
911 B
Rust

use std::{
fs::File,
io::{BufReader, Read}, collections::HashSet,
};
fn main() -> () {
let input = File::open("input.txt").unwrap();
let buf = BufReader::new(input);
let window_size = 4;
let mut chars_iter = buf.bytes();
let mut window = vec![0u8; 4];
let mut dup_check = HashSet::<u8>::with_capacity(4);
let mut cursor = window_size - 1;
// initialise buffer
for i in 0..window_size - 1 {
window[i] = chars_iter.next().unwrap().unwrap();
}
// find non-duplicate window
let pos = chars_iter.position(|byte| {
let byte = byte.unwrap();
window[cursor] = byte;
cursor = (cursor + 1) % window_size;
dup_check.clear();
dup_check.extend(window.iter());
dup_check.len() == window_size
}).unwrap();
let pos = pos + window_size; // account for buffer initialisation
println!("{}", pos);
}