day06: Make more generic and add part 2 with it

Part 2 is basically the same just with 14 chars instead of 4.
This commit is contained in:
MasterofJOKers 2022-12-19 14:38:32 +01:00
parent 035f8e86ac
commit 01789441db
1 changed files with 11 additions and 9 deletions

View File

@ -3,23 +3,25 @@ use std::error;
use std::fs::File; use std::fs::File;
use std::io::prelude::*; use std::io::prelude::*;
const N_CHARS: usize = 14;
fn main() -> Result<(), Box<dyn error::Error>> { fn main() -> Result<(), Box<dyn error::Error>> {
let mut f = File::open("input.txt")?; let mut f = File::open("input.txt")?;
let mut buf = [0; 32]; let mut buf = [0; 32];
let mut pos = 0; let mut pos = 0;
let mut found = false; let mut found = false;
let mut n = f.read(&mut buf[3..])?; let mut n = f.read(&mut buf[(N_CHARS - 1)..])?;
while n > 0 { while n > 0 {
for i in 4..(4 + n) { for i in N_CHARS..(N_CHARS + n) {
pos += 1; pos += 1;
// println!("{}", std::str::from_utf8(&buf[(i - 4)..i]).unwrap()); // println!("{}", std::str::from_utf8(&buf[(i - N_CHARS)..i]).unwrap());
// skip if we read uninitialized data from first run // skip if we read uninitialized data from first run
if buf[i - 4] == 0 { if buf[i - N_CHARS] == 0 {
continue; continue;
} }
let set: HashSet<&u8> = HashSet::from_iter(&buf[(i - 4)..i]); let set: HashSet<&u8> = HashSet::from_iter(&buf[(i - N_CHARS)..i]);
if set.len() == 4 { if set.len() == N_CHARS {
found = true; found = true;
break; break;
} }
@ -27,10 +29,10 @@ fn main() -> Result<(), Box<dyn error::Error>> {
if found { if found {
break; break;
} }
for i in 0..3 { for i in 0..(N_CHARS - 1) {
buf[i] = buf[29 + i]; buf[i] = buf[(32 - N_CHARS + 1) + i];
} }
n = f.read(&mut buf[3..])?; n = f.read(&mut buf[(N_CHARS - 1)..])?;
} }
println!("Found 4 different chars at position {}", pos); println!("Found 4 different chars at position {}", pos);
Ok(()) Ok(())