From 3711935b4f86128bf50d759e30b543766c738f13 Mon Sep 17 00:00:00 2001 From: Luke Hubmayer-Werner Date: Fri, 30 Dec 2022 20:06:01 +1030 Subject: [PATCH] Add Rust and C++ sliding XOR window versions of Day6 --- 2022/day6.cpp | 37 ++++++++++++++++++++++++++++++++++++- 2022/day6.rs | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/2022/day6.cpp b/2022/day6.cpp index 3317947..d57c1e4 100644 --- a/2022/day6.cpp +++ b/2022/day6.cpp @@ -82,6 +82,40 @@ fourteen_found: return std::pair(four+2, fourteen+8); } + +std::pair find_first_unique_runs_xor(std::vector *s) { + size_t four = 0; + size_t fourteen = 0; + uint32_t masks[4096]; + for (int i=0; i<4096; i++) { + masks[i] = 1 << ((*s)[i]-'a'); + } + uint32_t bitset = 0; + for (int i = 0; i < 4; i++) { // No old entries to remove + bitset ^= masks[i]; + } + for (int i = 4; i < 4096; i++) { + bitset ^= masks[i]; + bitset ^= masks[i-4]; + if (std::popcount(bitset) >= 4) { + four = i; + break; + } + } + for (int i = four+1; i < four+11; i++) { // No old entries to remove while readjusting base + bitset ^= masks[i]; + } + for (int i = four+11; i < 4096; i++) { + bitset ^= masks[i]; + bitset ^= masks[i-14]; + if (std::popcount(bitset) >= 14) { + fourteen = i; + break; + } + } + return std::pair(four, fourteen); +} + int main(int argc, char **argv) { size_t iterations = 1000000; auto filename = "input/6"; @@ -110,7 +144,8 @@ int main(int argc, char **argv) { for (size_t i = 0; i) -> (Int, Int) { return (four+4, fourteen+8); } +fn find_first_unique_runs_xor(s: &Vec) -> (Int, Int) { + let mut four: Int = 0; + let mut fourteen: Int = 0; + let mut masks: [u32; 4096] = [0; 4096]; + for i in 0..4096 { + masks[i] = 1 << (s[i]-b'a'); + } + let mut bitset: u32 = 0; + for i in 0..4 { // No old entries to remove + bitset ^= masks[i]; + } + for i in 4..4096 { + bitset ^= masks[i]; + bitset ^= masks[i-4]; + if bitset.count_ones() >= 4 { + four = i; + break; + } + } + for i in (four+1)..(four+11) { // No old entries to remove while readjusting base + bitset ^= masks[i]; + } + for i in (four+11)..4096 { + bitset ^= masks[i]; + bitset ^= masks[i-14]; + if bitset.count_ones() >= 14 { + fourteen = i; + break; + } + } + return (four, fourteen); +} + fn main() { let mut filename = "input/6"; let mut iterations = 1_000_000; @@ -105,7 +138,8 @@ fn main() { for _ in 0..iterations { // four = find_first_unique_run(&s, 4, 0); // fourteen = find_first_unique_run(&s, 14, four); - (four, fourteen) = find_first_unique_runs(&s); + // (four, fourteen) = find_first_unique_runs(&s); + (four, fourteen) = find_first_unique_runs_xor(&s); } let duration = t0.elapsed(); let per_iteration = duration / iterations;