diff --git a/Cargo.lock b/Cargo.lock index f0215da..4d0ff28 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -25,6 +25,7 @@ dependencies = [ "color-eyre", "criterion", "itertools 0.14.0", + "rayon", "test-log", "tracing", "tracing-error", @@ -40,6 +41,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "alloca" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4" +dependencies = [ + "cc", +] + [[package]] name = "anes" version = "0.1.6" @@ -129,6 +139,16 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" +[[package]] +name = "cc" +version = "1.2.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c481bdbf0ed3b892f6f806287d72acd515b352a4ec27a208489b8c1bc839633a" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.4" @@ -237,25 +257,24 @@ checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" [[package]] name = "criterion" -version = "0.5.1" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" +checksum = "a0dfe5e9e71bdcf4e4954f7d14da74d1cdb92a3a07686452d1509652684b1aab" dependencies = [ + "alloca", "anes", "cast", "ciborium", "clap", "criterion-plot", - "is-terminal", - "itertools 0.10.5", + "itertools 0.13.0", "num-traits", - "once_cell", "oorandom", + "page_size", "plotters", "rayon", "regex", "serde", - "serde_derive", "serde_json", "tinytemplate", "walkdir", @@ -263,12 +282,12 @@ dependencies = [ [[package]] name = "criterion-plot" -version = "0.5.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" +checksum = "5de36c2bee19fba779808f92bf5d9b0fa5a40095c277aba10c458a12b35d21d6" dependencies = [ "cast", - "itertools 0.10.5", + "itertools 0.13.0", ] [[package]] @@ -318,6 +337,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844" + [[package]] name = "gimli" version = "0.32.3" @@ -341,29 +366,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" -[[package]] -name = "hermit-abi" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" - [[package]] name = "indenter" version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5" -[[package]] -name = "is-terminal" -version = "0.4.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" -dependencies = [ - "hermit-abi", - "libc", - "windows-sys 0.61.2", -] - [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -372,9 +380,9 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itertools" -version = "0.10.5" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" dependencies = [ "either", ] @@ -497,6 +505,16 @@ version = "4.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52" +[[package]] +name = "page_size" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "pin-project-lite" version = "0.2.16" @@ -677,6 +695,12 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "smallvec" version = "1.15.1" @@ -894,6 +918,22 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -903,6 +943,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows-link" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index 73da406..3626dc9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,12 +7,13 @@ edition = "2024" clap = { version = "4.5", features = ["derive"] } color-eyre = "0.6" itertools = "0.14" +rayon = "1.11" tracing = "0.1" tracing-error = "0.2" tracing-subscriber = { version = "0.3", features = ["env-filter"] } [dev-dependencies] -criterion = "0.5.1" +criterion = "0.8.0" test-log = { version = "0.2", default-features = false, features = ["trace"] } # Improve perf on debug builds: https://docs.rs/color-eyre/latest/color_eyre/#improving-perf-on-debug-builds diff --git a/README.md b/README.md index e36c3b8..56c0aea 100644 --- a/README.md +++ b/README.md @@ -33,4 +33,4 @@ Timings are given as: [lower-bound **best-estimate** upper-bound] | Day | Part 1 | Part 2 | |-----|--------|--------| | 01 | [101.34 µs **101.95 µs** 102.61 µs] | [105.90 µs **106.40 µs** 106.95 µs] | -| 02 | [165.59 ms **166.60 ms** 167.65 ms] | [184.17 ms **185.25 ms** 186.42 ms] | +| 02 | [2.0990 ms **2.1113 ms** 2.1236 ms] | [2.0954 ms **2.1055 ms** 2.1157 ms] | diff --git a/src/day02/mod.rs b/src/day02/mod.rs index 5e42335..fdd55f5 100644 --- a/src/day02/mod.rs +++ b/src/day02/mod.rs @@ -2,9 +2,9 @@ use std::{fmt::Display, str::FromStr}; use color_eyre::{ Result, - eyre::{Error, OptionExt, eyre}, + eyre::{Error, eyre}, }; -use itertools::Itertools; +use rayon::prelude::*; use tracing::{debug, debug_span, instrument}; pub const INPUT: &str = include_str!("input/input.txt"); @@ -50,54 +50,34 @@ impl Iterator for ProductRange { } } -fn is_valid_product_id(id: i64) -> Result { - let digits: Vec = id - .to_string() - .chars() - .map(|c| { - c.to_digit(10) - .ok_or_eyre("Invalid product id: contains a non-decimal digit") - }) - .collect::>>()?; - if digits.len() % 2 != 0 { - return Ok(true); - } - Ok(digits[..digits.len() / 2] != digits[digits.len() / 2..]) -} - -fn is_valid_product_id2(id: i64) -> Result { - let digits: Vec = id - .to_string() - .chars() - .map(|c| { - c.to_digit(10) - .ok_or_eyre("Invalid product id: contains a non-decimal digit") - }) - .collect::>>()?; - let mut chunk_size = digits.len() / 2; - loop { - if chunk_size == 0 { - break; - } - if digits - .chunks(chunk_size) - .tuple_windows() - .all(|(a, b)| a == b) - { - return Ok(false); - } - chunk_size -= 1; - } - Ok(true) -} - impl ProductRange { fn invalid_ids(self) -> Result> { - let mut invalid_ids = vec![]; + let start = *self.0.start(); + let end = *self.0.end(); - for id in self { - if !is_valid_product_id(id)? { - invalid_ids.push(id); + let mut invalid_ids = Vec::new(); + + // Determine digit ranges we need to check + let start_digits = if start == 0 { 1 } else { start.ilog10() + 1 }; + let end_digits = if end == 0 { 1 } else { end.ilog10() + 1 }; + + for num_digits in start_digits..=end_digits { + // Skip odd digit counts - they're all valid + if num_digits % 2 != 0 { + continue; + } + + let half_digits = num_digits / 2; + let half_min = 10_i64.pow(half_digits - 1); + let half_max = 10_i64.pow(half_digits) - 1; + let multiplier = 10_i64.pow(half_digits) + 1; // Pre-calculate: half * multiplier = AABB pattern + + // Generate all patterns where first half == second half + for half in half_min..=half_max { + let id = half * multiplier; + if id >= start && id <= end { + invalid_ids.push(id); + } } } @@ -106,14 +86,51 @@ impl ProductRange { } fn invalid_ids2(self) -> Result> { - let mut invalid_ids = vec![]; + let start = *self.0.start(); + let end = *self.0.end(); - for id in self { - if !is_valid_product_id2(id)? { - invalid_ids.push(id); + let mut invalid_ids = std::collections::HashSet::new(); + + // Determine digit ranges we need to check + let start_digits = if start == 0 { 1 } else { start.ilog10() + 1 }; + let end_digits = if end == 0 { 1 } else { end.ilog10() + 1 }; + + for num_digits in start_digits..=end_digits { + // Try all possible chunk sizes that divide evenly + for chunk_size in 1..=num_digits / 2 { + if num_digits % chunk_size != 0 { + continue; + } + + let num_chunks = num_digits / chunk_size; + if num_chunks < 2 { + continue; + } + + // Generate all possible chunk patterns + let chunk_min = 10_i64.pow(chunk_size - 1); + let chunk_max = 10_i64.pow(chunk_size) - 1; + let chunk_power = 10_i64.pow(chunk_size); + + // Calculate multiplier for repeating pattern + // For ABCABC: chunk * (10^6 + 10^3 + 1) = chunk * 1001001 + let mut multiplier = 0_i64; + for i in 0..num_chunks { + multiplier += chunk_power.pow(i); + } + + for chunk in chunk_min..=chunk_max { + let id = chunk * multiplier; + + if id >= start && id <= end { + invalid_ids.insert(id); + } + } } } + let invalid_ids: Vec = invalid_ids.into_iter().collect(); + debug!("Invalid IDs: {:?}", &invalid_ids); Ok(invalid_ids) } @@ -121,24 +138,32 @@ impl ProductRange { #[instrument(skip(input))] pub fn part1(input: &str) -> Result { - let mut total_invalid = 0; - for range in input.trim().split(',') { - let _span = debug_span!("range", range = %range).entered(); - let range: ProductRange = range.parse()?; - total_invalid += range.invalid_ids()?.iter().sum::(); - } - Ok(total_invalid) + input + .trim() + .split(',') + .collect::>() + .into_par_iter() + .map(|range| { + let _span = debug_span!("range", range = %range).entered(); + let range: ProductRange = range.parse()?; + Ok(range.invalid_ids()?.iter().sum::()) + }) + .sum() } #[instrument(skip(input))] pub fn part2(input: &str) -> Result { - let mut total_invalid = 0; - for range in input.trim().split(',') { - let _span = debug_span!("range", range = %range).entered(); - let range: ProductRange = range.parse()?; - total_invalid += range.invalid_ids2()?.iter().sum::(); - } - Ok(total_invalid) + input + .trim() + .split(',') + .collect::>() + .into_par_iter() + .map(|range| { + let _span = debug_span!("range", range = %range).entered(); + let range: ProductRange = range.parse()?; + Ok(range.invalid_ids2()?.iter().sum::()) + }) + .sum() } #[cfg(test)]