From 035f8e86ac2dff49f0dd252c3babce04b86ca183 Mon Sep 17 00:00:00 2001 From: MasterofJOKers Date: Mon, 19 Dec 2022 14:34:02 +0100 Subject: [PATCH] day06: Add part 1 Borrow-checker hindered me to keep the same HashSet around all the time and just clear it, so it feels a little inefficient to have a new set every time. --- day06/Cargo.lock | 7 +++++++ day06/Cargo.toml | 8 ++++++++ day06/src/main.rs | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 day06/Cargo.lock create mode 100644 day06/Cargo.toml create mode 100644 day06/src/main.rs diff --git a/day06/Cargo.lock b/day06/Cargo.lock new file mode 100644 index 0000000..0c65426 --- /dev/null +++ b/day06/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "day06" +version = "0.1.0" diff --git a/day06/Cargo.toml b/day06/Cargo.toml new file mode 100644 index 0000000..2f276f3 --- /dev/null +++ b/day06/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "day06" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/day06/src/main.rs b/day06/src/main.rs new file mode 100644 index 0000000..623064d --- /dev/null +++ b/day06/src/main.rs @@ -0,0 +1,37 @@ +use std::collections::HashSet; +use std::error; +use std::fs::File; +use std::io::prelude::*; + +fn main() -> Result<(), Box> { + let mut f = File::open("input.txt")?; + + let mut buf = [0; 32]; + let mut pos = 0; + let mut found = false; + let mut n = f.read(&mut buf[3..])?; + while n > 0 { + for i in 4..(4 + n) { + pos += 1; + // println!("{}", std::str::from_utf8(&buf[(i - 4)..i]).unwrap()); + // skip if we read uninitialized data from first run + if buf[i - 4] == 0 { + continue; + } + let set: HashSet<&u8> = HashSet::from_iter(&buf[(i - 4)..i]); + if set.len() == 4 { + found = true; + break; + } + } + if found { + break; + } + for i in 0..3 { + buf[i] = buf[29 + i]; + } + n = f.read(&mut buf[3..])?; + } + println!("Found 4 different chars at position {}", pos); + Ok(()) +}