From 387355f690b41a02ab9865526790d774e2585bbd Mon Sep 17 00:00:00 2001 From: Tobias Marschner Date: Sun, 11 Feb 2024 12:35:10 +0100 Subject: [PATCH] Solution for 2022/day06-part2 --- 2022/day06-part2/Cargo.toml | 8 ++++++++ 2022/day06-part2/src/main.rs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 2022/day06-part2/Cargo.toml create mode 100644 2022/day06-part2/src/main.rs diff --git a/2022/day06-part2/Cargo.toml b/2022/day06-part2/Cargo.toml new file mode 100644 index 0000000..6ea493c --- /dev/null +++ b/2022/day06-part2/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "day06-part2" +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/2022/day06-part2/src/main.rs b/2022/day06-part2/src/main.rs new file mode 100644 index 0000000..439e1d5 --- /dev/null +++ b/2022/day06-part2/src/main.rs @@ -0,0 +1,34 @@ +use std::collections::{HashSet, VecDeque}; + +fn main() { + // Use command line arguments to specify the input filename. + let args: Vec = std::env::args().collect(); + if args.len() < 2 { + panic!("Usage: ./main \nNo input file provided. Exiting."); + } + + // Next, read the contents of the input file into a string for easier processing. + let input = std::fs::read_to_string(&args[1]).expect("Error opening file"); + + // Define the length of characters that need to be unique. + // const N: usize = 4; // part one + const N: usize = 14; // part two + + // Use a double-ended queue as a ringbuffer to keep track of the characters. + let mut deq = VecDeque::from([' '; N]); + + // Iterate through all characters, together with their respective indices. + for (i, char) in input.chars().enumerate() { + // Remove the first character from the deque. + deq.pop_front(); + // And add the next character to it. + deq.push_back(char); + // Collecting into a set, removing duplicates along the way. + let hs: HashSet = deq.iter().copied().collect(); + // Count the number of unique elements in the set. + if hs.len() >= N && !hs.contains(&' ') { + println!("Start of packet: {}", i + 1); + break; + } + } +}