aboutsummaryrefslogtreecommitdiff
path: root/2022/src/day06.rs
diff options
context:
space:
mode:
authorAria <me@aria.rip>2023-01-02 21:58:56 +0000
committerAria <me@aria.rip>2023-01-02 21:58:56 +0000
commit5eb58ad076f2cd435b11b140820da224b60b73d5 (patch)
tree2a67939595fbf993ff04f69b9cd3f0aa20827d96 /2022/src/day06.rs
initial commit
Diffstat (limited to '2022/src/day06.rs')
-rw-r--r--2022/src/day06.rs47
1 files changed, 47 insertions, 0 deletions
diff --git a/2022/src/day06.rs b/2022/src/day06.rs
new file mode 100644
index 0000000..8bbfe6d
--- /dev/null
+++ b/2022/src/day06.rs
@@ -0,0 +1,47 @@
+mod utils;
+use utils::read_input;
+
+fn main() {
+ let input = read_input();
+
+ println!("Part 1: {}", find_chunk_nodup::<4>(&input));
+ println!("Part 2: {}", find_chunk_nodup::<14>(&input));
+}
+
+fn find_chunk_nodup<const N: usize>(input: &str) -> usize {
+ let mut window = ['a'; N];
+ let mut chars = input.chars();
+
+ // Fill up initial window
+ for item in window.iter_mut() {
+ *item = chars.next().unwrap();
+ }
+
+ for i in 0..input.len() {
+ // Shuffle everything in window down
+ for j in 0..N - 1 {
+ window[j] = window[j + 1];
+ }
+ window[N - 1] = chars.next().unwrap();
+
+ if window
+ .iter()
+ .fold(Some(0), |acc, chr| add_char(acc?, *chr))
+ .is_some()
+ {
+ return i + N + 1;
+ }
+ }
+
+ panic!("no solution!")
+}
+
+#[inline]
+fn add_char(bits: u32, chr: char) -> Option<u32> {
+ let add = 1 << (chr.to_ascii_lowercase() as u32 - 97);
+ if (bits | add) != bits {
+ Some(bits | add)
+ } else {
+ None
+ }
+}