diff --git a/2025/.aoc_tiles/tiles/2025/01.png b/2025/.aoc_tiles/tiles/2025/01.png new file mode 100644 index 0000000..ec38deb Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/01.png differ diff --git a/2025/.aoc_tiles/tiles/2025/02.png b/2025/.aoc_tiles/tiles/2025/02.png new file mode 100644 index 0000000..ab61816 Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/02.png differ diff --git a/2025/.aoc_tiles/tiles/2025/03.png b/2025/.aoc_tiles/tiles/2025/03.png new file mode 100644 index 0000000..7376104 Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/03.png differ diff --git a/2025/.aoc_tiles/tiles/2025/04.png b/2025/.aoc_tiles/tiles/2025/04.png new file mode 100644 index 0000000..4a614fa Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/04.png differ diff --git a/2025/.aoc_tiles/tiles/2025/05.png b/2025/.aoc_tiles/tiles/2025/05.png new file mode 100644 index 0000000..6723ab7 Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/05.png differ diff --git a/2025/.aoc_tiles/tiles/2025/06.png b/2025/.aoc_tiles/tiles/2025/06.png new file mode 100644 index 0000000..e8d999c Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/06.png differ diff --git a/2025/.aoc_tiles/tiles/2025/07.png b/2025/.aoc_tiles/tiles/2025/07.png new file mode 100644 index 0000000..3b103b6 Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/07.png differ diff --git a/2025/.aoc_tiles/tiles/2025/08.png b/2025/.aoc_tiles/tiles/2025/08.png new file mode 100644 index 0000000..8c4293a Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/08.png differ diff --git a/2025/.aoc_tiles/tiles/2025/09.png b/2025/.aoc_tiles/tiles/2025/09.png new file mode 100644 index 0000000..2e00dc3 Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/09.png differ diff --git a/2025/.aoc_tiles/tiles/2025/10.png b/2025/.aoc_tiles/tiles/2025/10.png new file mode 100644 index 0000000..60bcc90 Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/10.png differ diff --git a/2025/.aoc_tiles/tiles/2025/11.png b/2025/.aoc_tiles/tiles/2025/11.png new file mode 100644 index 0000000..cd962b6 Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/11.png differ diff --git a/2025/.aoc_tiles/tiles/2025/12.png b/2025/.aoc_tiles/tiles/2025/12.png new file mode 100644 index 0000000..efc17e5 Binary files /dev/null and b/2025/.aoc_tiles/tiles/2025/12.png differ diff --git a/2025/.cargo/config.toml b/2025/.cargo/config.toml new file mode 100644 index 0000000..ddff440 --- /dev/null +++ b/2025/.cargo/config.toml @@ -0,0 +1,2 @@ +[build] +rustflags = ["-C", "target-cpu=native"] diff --git a/2025/.gitignore b/2025/.gitignore new file mode 100644 index 0000000..2ad0769 --- /dev/null +++ b/2025/.gitignore @@ -0,0 +1,7 @@ +**/target +input +flamegraph.svg +perf.data* +guesses +.aoc_tiles/* +!.aoc_tiles/tiles/ diff --git a/2025/.pre-commit-config.yaml b/2025/.pre-commit-config.yaml new file mode 100644 index 0000000..5b2a983 --- /dev/null +++ b/2025/.pre-commit-config.yaml @@ -0,0 +1,32 @@ +repos: + - repo: local + hooks: + - id: rust-linting + name: Rust linting + entry: cargo fmt --all -- + pass_filenames: true + types: [file, rust] + language: system + - id: rust-clippy + name: Rust clippy + entry: cargo clippy --lib --all-features --tests -- + pass_filenames: false + types: [file, rust] + language: system + - repo: https://github.com/LiquidFun/aoc_tiles + rev: 0.7.2 + hooks: + - id: aoc-tiles + language: system + # Optionally use these arguments. Auto add tiles to git adds the tiles to git, + # possibly amends your commit by creating the tile images and updating the README. + # Language sorting shows the preference of the order of the languages to use. + # Exclude paterns are globs which can be used to exclude files when creating + # the tiles. See the customization section in the README for more flags. + # Simply remove the comments (#) below for args and the flags you want. + args: + - --auto-add-tiles-to-git=amend + - --overwrite-year=2025 + - --tile-width-px=200 + # - --language-sorting=jl,kt,py,rs + # - --exclude-patterns=2021/*/*.apl,2021/*/*.py,2021/*/*.cpp diff --git a/2025/Cargo.lock b/2025/Cargo.lock new file mode 100644 index 0000000..cf0d25f --- /dev/null +++ b/2025/Cargo.lock @@ -0,0 +1,1202 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if 1.0.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "aoc-runner" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d21ef9204ad206a5a3e918e9920da04e1118ad91ce4f23570be964b9d6b9dfcb" + +[[package]] +name = "aoc-runner-derive" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba8b944269d3fee645d281b1335e1797044db497bb02d0098cc3fdb8900069cc" +dependencies = [ + "aoc-runner-internal", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "aoc-runner-internal" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "274b0ba7f3669a45ec0aaacf94eb032a749de880ab776091576cca94037c9982" +dependencies = [ + "serde", + "serde_derive", + "serde_json", +] + +[[package]] +name = "aoc2025" +version = "0.1.0" +dependencies = [ + "aoc-runner", + "aoc-runner-derive", + "cached", + "grid", + "indicatif", + "itertools", + "misc", + "rayon", + "regex", + "rstest", + "rustc_data_structures", + "wide", +] + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" + +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + +[[package]] +name = "bytemuck" +version = "1.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4" + +[[package]] +name = "cached" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "801927ee168e17809ab8901d9f01f700cd7d8d6a6527997fee44e4b0327a253c" +dependencies = [ + "ahash", + "cached_proc_macro", + "cached_proc_macro_types", + "hashbrown 0.15.5", + "once_cell", + "thiserror", + "web-time", +] + +[[package]] +name = "cached_proc_macro" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9225bdcf4e4a9a4c08bf16607908eb2fbf746828d5e0b5e019726dbf6571f201" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "cached_proc_macro_types" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade8366b8bd5ba243f0a58f036cc0ca8a2f069cff1a2351ef1cac6b083e16fc0" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "console" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b430743a6eb14e9764d4260d4c0d8123087d504eeb9c48f2b2a5e810dd369df4" +dependencies = [ + "encode_unicode", + "libc", + "once_cell", + "unicode-width", + "windows-sys", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.111", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "ena" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d248bdd43ce613d87415282f69b9bb99d947d290b10962dd6c56233312c2ad5" +dependencies = [ + "log", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-macro" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-timer" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if 1.0.4", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "grid" +version = "0.1.0" + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "rustc-rayon 0.5.1", +] + +[[package]] +name = "indexmap" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", +] + +[[package]] +name = "indicatif" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9375e112e4b463ec1b1c6c011953545c65a30164fbab5b581df32b3abf0dcb88" +dependencies = [ + "console", + "portable-atomic", + "rayon", + "unicode-width", + "unit-prefix", + "web-time", +] + +[[package]] +name = "intrusive-collections" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" +dependencies = [ + "memoffset", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.178" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091" + +[[package]] +name = "linux-raw-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "memchr" +version = "2.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" + +[[package]] +name = "memmap2" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "misc" +version = "0.1.0" +dependencies = [ + "intrusive-collections", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if 1.0.4", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "portable-atomic" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" + +[[package]] +name = "proc-macro-crate" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rayon" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.10.0", +] + +[[package]] +name = "regex" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" + +[[package]] +name = "relative-path" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" + +[[package]] +name = "rstest" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5a3193c063baaa2a95a33f03035c8a72b83d97a54916055ba22d35ed3839d49" +dependencies = [ + "futures-timer", + "futures-util", + "rstest_macros", +] + +[[package]] +name = "rstest_macros" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c845311f0ff7951c5506121a9ad75aec44d083c31583b2ea5a30bcb0b0abba0" +dependencies = [ + "cfg-if 1.0.4", + "glob", + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 2.0.111", + "unicode-ident", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-rayon" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9974ab223660e61c1b4e7b43b827379df286736ca988308ce7e16f59f2d89246" +dependencies = [ + "crossbeam-deque", + "either", + "rustc-rayon-core 0.3.2", +] + +[[package]] +name = "rustc-rayon" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cd9fb077db982d7ceb42a90471e5a69a990b58f71e06f0d8340bb2cf35eb751" +dependencies = [ + "either", + "rustc-rayon-core 0.5.1", +] + +[[package]] +name = "rustc-rayon-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "564bfd27be8db888d0fa76aa4335e7851aaed0c2c11ad1e93aeb9349f6b88500" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", + "lazy_static", + "num_cpus", +] + +[[package]] +name = "rustc-rayon-core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f42932dcd3bcbe484b38a3ccf79b7906fac41c02d408b5b1bac26da3416efdb" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "rustc_data_structures" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a38bae9c6afa27015bcaa2869e03bb111ecf0d0e0edc2da559a91d4057174c9a" +dependencies = [ + "arrayvec", + "bitflags 1.3.2", + "cfg-if 0.1.10", + "ena", + "indexmap 1.9.3", + "jobserver", + "libc", + "memmap2", + "parking_lot", + "rustc-hash", + "rustc-rayon 0.3.2", + "rustc-rayon-core 0.3.2", + "stable_deref_trait", + "tempfile", + "tracing", + "winapi", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" +dependencies = [ + "bitflags 2.10.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "safe_arch" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f7caad094bd561859bcd467734a720c3c1f5d1f338995351fefe2190c45efed" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "serde_json" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", + "serde_core", +] + +[[package]] +name = "slab" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.111" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "toml_datetime" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2cdb639ebbc97961c51720f858597f7f24c4fc295327923af55b74c3c724533" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.23.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d7cbc3b4b49633d57a0509303158ca50de80ae32c265093b24c414705807832" +dependencies = [ + "indexmap 2.12.1", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0cbe268d35bdb4bb5a56a2de88d0ad0eb70af5384a99d648cd4b3d04039800e" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d15d90a0b5c19378952d479dc858407149d7bb45a14de0142f6c534b16fc647" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "tracing-core" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a04e24fab5c89c6a36eb8558c9656f30d81de51dfa4d3b45f26b21d61fa0a6c" +dependencies = [ + "once_cell", +] + +[[package]] +name = "unicode-ident" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "unit-prefix" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +dependencies = [ + "cfg-if 1.0.4", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.111", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wide" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbace5de6cfc4866f684318ad85761c89380cfb191982ae96aa65c295bf5897e" +dependencies = [ + "bytemuck", + "safe_arch", +] + +[[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-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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "0.7.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "zerocopy" +version = "0.8.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] diff --git a/2025/Cargo.toml b/2025/Cargo.toml new file mode 100644 index 0000000..b82ea82 --- /dev/null +++ b/2025/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "aoc2025" +edition = "2024" +version = "0.1.0" + +[dependencies] +aoc-runner = "0.3.0" +aoc-runner-derive = "0.3.0" +cached = "0.56.0" +grid = {version = "0.1.0", path = "utils/grid"} +indicatif = { version = "0.18.3", features = ["rayon"] } +itertools = "0.14.0" +misc = {path = "utils/misc"} +rayon = "1.11.0" +regex = "1.11.1" +rstest = "0.26.1" +rustc_data_structures = "0.1.2" +wide = "1.0.2" + +[profile.release] +lto = true +opt-level = 3 +overflow-checks = false diff --git a/2025/README.md b/2025/README.md new file mode 100644 index 0000000..414bd64 --- /dev/null +++ b/2025/README.md @@ -0,0 +1,41 @@ + +

+ 2025 - 22 ⭐ - Rust +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/2025/src/day1.rs b/2025/src/day1.rs new file mode 100644 index 0000000..f82dcfc --- /dev/null +++ b/2025/src/day1.rs @@ -0,0 +1,98 @@ +use aoc_runner_derive::aoc; + +// PROBLEM 1 solution +#[aoc(day1, part1)] +pub fn part1(input: &str) -> u64 { + let mut val = 50u64; + let mut pass = 0u64; + let mod_val = 100; + for line in input.lines() { + let line = line.trim(); + let (sign, num) = line.split_at(1); + let num_val = num.parse::().unwrap(); + + let add_val = match sign.as_bytes()[0] { + b'R' => num_val, + b'L' => mod_val - (num_val % mod_val), + c => panic!("Invalid direction {c}"), + }; + val = (val + add_val) % mod_val; + if val == 0 { + pass += 1 + } + } + pass +} + +// PROBLEM 2 solution + +fn advance(mut start: i64, mut n: i64) -> (i64, i64) { + let mut zero_crossings = 0; + while n != 0 { + if n > 0 { + start += 1; + if start == 100 { + start = 0; + zero_crossings += 1; + } + n -= 1 + } else { + start -= 1; + if start == 0 { + zero_crossings += 1; + } + if start == -1 { + start = 99; + } + n += 1 + } + } + (start, zero_crossings) +} + +#[aoc(day1, part2)] +pub fn part2(input: &str) -> i64 { + let mut val = 50; + let mut pass = 0i64; + + for line in input.lines() { + let line = line.trim(); + let (sign, num) = line.split_at(1); + let num_val = num.parse::().unwrap(); + + let (new_val, add_pass) = match sign.as_bytes()[0] { + b'R' => advance::<100>(val, num_val), + b'L' => advance::<100>(val, -num_val), + c => panic!("Invalid direction {c}"), + }; + val = new_val; + pass += add_pass; + } + pass +} + +#[cfg(test)] +mod tests { + use crate::day1::*; + + const EXAMPLE: &str = "L68 + L30 + R48 + L5 + R60 + L55 + L1 + L99 + R14 + L82"; + + #[test] + fn problem1_example() { + assert_eq!(part1(EXAMPLE), 3); + } + + #[test] + fn problem2_example() { + assert_eq!(part2(EXAMPLE), 6); + } +} diff --git a/2025/src/day10.rs b/2025/src/day10.rs new file mode 100644 index 0000000..42b6d6b --- /dev/null +++ b/2025/src/day10.rs @@ -0,0 +1,331 @@ +use std::{ + collections::{BinaryHeap, VecDeque}, + hash::Hash, + iter::{repeat, repeat_n}, +}; + +use aoc_runner_derive::{aoc, aoc_generator}; +use indicatif::{ProgressBar, ProgressStyle}; +use itertools::Itertools; +use regex::Regex; +use wide::{CmpGt, i16x16}; + +#[derive(Clone, Debug, Default)] +struct MachineDefinition { + desired: Vec, + buttons: Vec>, + buttons2: Vec, + buttons_max: i16x16, + joltages: i16x16, +} + +impl MachineDefinition { + fn create<'a>(&'a self) -> Machine<'a> { + Machine { + d: self, + lights: Vec::from_iter(repeat_n(false, self.desired.len())), + } + } + + fn create2<'a>(&'a self) -> JoltMachine<'a> { + JoltMachine { + d: self, + joltages: i16x16::splat(0), + } + } +} + +impl From<&str> for MachineDefinition { + fn from(value: &str) -> Self { + let parse_re = Regex::new( + r##"\[(?[.#]+)\] (?(\([0-9,]+\) ?)+) \{(?[0-9,]+)\}"##, + ) + .unwrap(); + + let parts = parse_re.captures(value).unwrap(); + let joltages: [i16; 16] = parts["joltages"] + .split(',') + .map(|n| n.parse().unwrap()) + .chain(repeat(0)) + .take(16) + .collect_array() + .unwrap(); + + let buttons = parts["buttons"] + .split_ascii_whitespace() + .map(|s| { + s[1..s.len() - 1] + .split(',') + .map(|n| n.parse().unwrap()) + .collect() + }) + .sorted_unstable_by_key(|s: &Vec| s.len()) + .rev() + .collect_vec(); + + let mut buttons2 = Vec::new(); + let mut buttons_max = [0i16; 16]; + + for (i, b) in buttons.iter().enumerate() { + let mut but = [0i16; 16]; + for i in b { + but[*i] = 1; + } + buttons2.push(i16x16::new(but)); + + // find the joltage this button affects with the lowest value + // it is the max number of presses for this button + buttons_max[i] = b.iter().map(|idx| joltages[*idx]).min().unwrap(); + } + + MachineDefinition { + desired: parts["desired"].chars().map(|c| c == '#').collect(), + buttons: buttons, + buttons2: buttons2, + buttons_max: i16x16::new(buttons_max), + joltages: i16x16::new(joltages), + } + } +} + +#[derive(Clone, Debug)] +struct Machine<'a> { + d: &'a MachineDefinition, + lights: Vec, +} + +#[derive(Clone, Debug)] +struct JoltMachine<'a> { + d: &'a MachineDefinition, + joltages: i16x16, +} + +impl<'a> Machine<'a> { + /// Get the state after pressing `button`, returns None if the state is as desired. + fn press(&self, button: usize) -> Option { + let mut new_state = self.lights.clone(); + for light in &self.d.buttons[button] { + new_state[*light] = !new_state[*light]; + } + if new_state == self.d.desired { + None + } else { + Some(Machine { + d: self.d, + lights: new_state, + }) + } + } + /// Get the possible states from the current position + fn next_states(&self) -> Vec<(usize, Option)> { + self.d + .buttons + .iter() + .enumerate() + .map(|(i, _but)| (i, self.press(i))) + .collect() + } +} + +impl<'a> JoltMachine<'a> { + fn press_jolts(&self, button: usize, presses: &i16x16) -> (i16x16, Option) { + // let mut new_joltage = self.joltages.clone(); + // // for jolt in &self.d.buttons[button] { + // // new_joltage[*jolt] += 1; + // // } + let new_joltage = self.joltages + self.d.buttons2[button]; + let mut new_presses = presses.clone(); + new_presses.as_mut_array()[button] += 1; + if new_joltage == self.d.joltages { + (new_presses, None) + } else { + ( + new_presses, + Some(Self { + d: self.d, + joltages: new_joltage, + }), + ) + } + } + + fn next_states_jolt(&self, presses: &i16x16) -> Vec<(i16x16, Option)> { + self.d + .buttons + .iter() + .enumerate() + .map(|(i, _but)| self.press_jolts(i, &presses)) + // .inspect(|(p, o)| println!(" {p:?} {o:?}\n")) + // joltages monotonically increase, so cull any where a joltage is higher than needed + .filter(|(presses, candidate)| { + !presses.simd_gt(self.d.buttons_max).any() + && candidate.as_ref().is_none_or(|c| { + !c.joltages.simd_gt(self.d.joltages).any() + // !c.joltages + // .iter() + // .zip(self.d.joltages.iter()) + // .any(|(candidate, expected)| candidate > expected) + }) + }) + .collect() + } +} + +#[derive(Debug, Clone)] +struct PressSet<'a> { + machine: Machine<'a>, + presses: usize, +} + +#[derive(Debug, Clone)] +struct PressSet2<'a> { + machine: JoltMachine<'a>, + presses: i16x16, +} + +// NOTE: All compares are reversed so our max heap becomes a min heap +impl<'a> Eq for PressSet<'a> {} +impl<'a> Eq for PressSet2<'a> {} + +impl<'a> PartialEq for PressSet<'a> { + fn eq(&self, other: &Self) -> bool { + other.presses.eq(&self.presses) + } +} + +impl<'a> PartialEq for PressSet2<'a> { + fn eq(&self, other: &Self) -> bool { + other.presses.eq(&self.presses) + } +} + +impl<'a> PartialOrd for PressSet<'a> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl<'a> PartialOrd for PressSet2<'a> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl<'a> Ord for PressSet<'a> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + other.presses.cmp(&self.presses) + } +} + +impl<'a> Ord for PressSet2<'a> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + other.presses.reduce_add().cmp(&self.presses.reduce_add()) + } +} + +fn find_best(md: &MachineDefinition) -> usize { + let m = md.create(); + let mut to_check = BinaryHeap::new(); + to_check.push(PressSet { + presses: 0, + machine: m, + }); + + while let Some(candidate) = to_check.pop() { + let cm = candidate.machine.clone(); + for next in cm.next_states() { + let presses = candidate.presses + 1; + if let Some(new_m) = next.1 { + to_check.push(PressSet { + presses, + machine: new_m.clone(), + }) + } else { + return presses; + } + } + } + panic!() +} + +fn find_best_jolts(md: &MachineDefinition) -> usize { + let m = md.create2(); + let mut to_check = VecDeque::new(); + to_check.push_back(PressSet2 { + presses: i16x16::splat(0), + machine: m, + }); + + let mut pb = ProgressBar::no_length() + .with_style( + ProgressStyle::with_template( + "[{elapsed_precise}/{eta_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {per_sec}", + ) + .unwrap(), + ) + .with_finish(indicatif::ProgressFinish::AndLeave); + + while let Some(candidate) = to_check.pop_front() { + pb.inc(1); + pb.set_length(to_check.len() as u64); + let cm = candidate.machine.clone(); + for (presses, next) in cm.next_states_jolt(&candidate.presses) { + if let Some(new_m) = next { + to_check.push_back(PressSet2 { + presses, + machine: new_m.clone(), + }) + } else { + return presses.reduce_add() as usize; + } + } + } + panic!() +} + +#[aoc_generator(day10)] +fn parse(input: &str) -> Vec { + input.lines().map(|l| l.into()).collect() +} + +#[aoc(day10, part1)] +fn part1(input: &[MachineDefinition]) -> u64 { + input + .iter() + .map(find_best) + // .inspect(|sol| println!(" [{sol:?}]")) + .map(|sol| sol as u64) + .sum() +} + +#[aoc(day10, part2)] +fn part2(input: &[MachineDefinition]) -> u64 { + input + .iter() + .map(find_best_jolts) + .map(|sol| sol as u64) + .sum() +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + + use super::*; + + const EXAMPLE: &str = "[.##.] (3) (1,3) (2) (2,3) (0,2) (0,1) {3,5,4,7} +[...#.] (0,2,3,4) (2,3) (0,4) (0,1,2) (1,2,3,4) {7,5,12,7,2} +[.###.#] (0,1,2,3,4) (0,3,4) (0,1,2,4,5) (1,2) {10,11,11,5,10,5}"; + + #[rstest] + #[case(EXAMPLE, 7)] + fn part1_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part1(&parse(input)), expected); + } + + #[rstest] + #[case(EXAMPLE, 33)] + fn part2_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part2(&parse(input)), expected); + } +} diff --git a/2025/src/day11.rs b/2025/src/day11.rs new file mode 100644 index 0000000..c3a302a --- /dev/null +++ b/2025/src/day11.rs @@ -0,0 +1,203 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; + +type Edges = FxHashMap>; + +#[aoc_generator(day11)] +fn parse(input: &str) -> Edges { + let mut edges: Edges = FxHashMap::default(); + for l in input.lines() { + let (k, rest) = l.split_once(": ").unwrap(); + for v in rest.split_ascii_whitespace() { + edges.entry(k.to_string()).or_default().push(v.to_string()); + } + } + + edges +} + +fn find_path(cur: &str, goal: &str, edges: &Edges) -> u64 { + if cur == goal { + return 1; + } + if let Some(nexts) = edges.get(cur) { + nexts.iter().map(|n| find_path(n, goal, edges)).sum() + } else { + 0 + } +} + +fn mark_paths<'a>( + cur: &'a str, + edges: &'a Edges, + mut reachable: FxHashSet<&'a str>, +) -> FxHashSet<&'a str> { + reachable.insert(cur); + if let Some(nexts) = edges.get(cur) { + for n in nexts { + if !reachable.contains(&n.as_str()) { + reachable = mark_paths(n, edges, reachable); + } + } + } + reachable +} + +fn count_paths_impl<'a>( + cur: &'a str, + goal: &str, + edges: &'a Edges, + memo: &mut FxHashMap<&'a str, u64>, +) -> u64 { + if cur == goal { + return 1; + } + if let Some(v) = memo.get(cur) { + return *v; + } + + if let Some(nexts) = edges.get(cur) { + let ret = nexts + .iter() + .map(|n| count_paths_impl(n, goal, edges, memo)) + .sum(); + memo.insert(cur, ret); + ret + } else { + memo.insert(cur, 0); + 0 + } +} + +fn count_paths(cur: &str, goal: &str, edges: &Edges) -> u64 { + let mut cache = FxHashMap::default(); + count_paths_impl(cur, goal, edges, &mut cache) +} + +#[aoc(day11, part1, NaiveDfs)] +fn part1(fwd: &Edges) -> u64 { + find_path("you", "out", fwd) +} + +#[aoc(day11, part1, MemoDfs)] +fn part1_memo(fwd: &Edges) -> u64 { + count_paths("you", "out", fwd) +} + +#[aoc(day11, part2, MemoDfs)] +fn part2_memo(edges: &Edges) -> u64 { + // we assume all valid paths reach svr->fft->dac->out in that order. this holds on the example and the input. + // to handle both possible orderings, we need to sum paths fft->dac and dac->fft, and then partition the graph + // (just remove the node) at dac & fft before computing the sum of dac->out and fft->out. + // + // this is our performance implementation though and it's faster to not do that work. we do the posterity for the + // naive solution + count_paths("svr", "fft", edges) + * count_paths("fft", "dac", edges) + * count_paths("dac", "out", edges) +} + +#[aoc(day11, part2, NaiveDfs)] +fn part2(edges: &Edges) -> u64 { + let mut rev = Edges::from_iter(edges.keys().map(|k| (k.to_owned(), vec![]))); + for (from, tos) in edges { + for to in tos { + rev.entry(to.to_owned()).or_default().push(from.to_owned()); + } + } + let mut reachable_dac = mark_paths("dac", edges, FxHashSet::default()); + reachable_dac = mark_paths("dac", &rev, reachable_dac); + let mut reachable_fft = mark_paths("fft", edges, FxHashSet::default()); + reachable_fft = mark_paths("fft", &rev, reachable_fft); + + let reachable: FxHashSet<&str> = reachable_dac + .intersection(&reachable_fft) + .copied() + .collect(); + + let unreachable: FxHashSet<&str> = FxHashSet::from_iter(edges.keys().map(|k| k.as_str())) + .difference(&reachable) + .copied() + .collect(); + + let mut reachable_edges = edges.clone(); + + for k in &unreachable { + reachable_edges.remove(*k); + } + for (_k, v) in reachable_edges.iter_mut() { + for ur in &unreachable { + if let Some(idx) = v.iter().position(|s| s == ur) { + v.remove(idx); + } + } + } + + // A real graph structure would probably notice that the graphs get split here + let mut reachable_edges_excl_fft = reachable_edges.clone(); + reachable_edges_excl_fft.remove("fft"); + let mut reachable_edges_excl_dac = reachable_edges.clone(); + reachable_edges_excl_dac.remove("dac"); + + find_path("svr", "fft", &reachable_edges) + // only svr->fft->dac->out paths appear in my input and in the example, but include the dac->fft ordering + // as well, for posterity. It ~doubles runtime. + * (find_path("fft", "dac", &reachable_edges) + find_path("dac", "fft", &reachable_edges)) + * (find_path("dac", "out", &reachable_edges_excl_fft) + find_path("fft", "out", &reachable_edges_excl_dac)) +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + + use super::*; + + const EXAMPLE: &str = "aaa: you hhh +you: bbb ccc +bbb: ddd eee +ccc: ddd eee fff +ddd: ggg +eee: out +fff: out +ggg: out +hhh: ccc fff iii +iii: out"; + + const EXAMPLE2: &str = "svr: aaa bbb +aaa: fft +fft: ccc +bbb: tty +tty: ccc +ccc: ddd eee +ddd: hub +hub: fff +eee: dac +dac: fff +fff: ggg hhh +ggg: out +hhh: out"; + + #[rstest] + #[case(EXAMPLE, 5)] + fn part1_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part1(&parse(input)), expected); + } + + #[rstest] + #[case(EXAMPLE, 5)] + fn part1_memo_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part1_memo(&parse(input)), expected); + } + + #[rstest] + #[case(EXAMPLE2, 2)] + fn part2_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part2(&parse(input)), expected); + } + + #[rstest] + #[case(EXAMPLE2, 2)] + fn part2_memo_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part2_memo(&parse(input)), expected); + } +} diff --git a/2025/src/day12.rs b/2025/src/day12.rs new file mode 100644 index 0000000..a0af759 --- /dev/null +++ b/2025/src/day12.rs @@ -0,0 +1,279 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use grid::{Coord2d, Grid, MirrorAxis}; +use indicatif::{ProgressBar, ProgressStyle}; +use itertools::Itertools; +use rayon::iter::IntoParallelRefIterator; +use std::collections::HashSet; +use std::fmt::Display; +use std::iter::repeat_n; + +type CellType = bool; + +#[derive(Debug, Clone)] +struct PresentShape { + variants: Vec>, +} + +impl From<&str> for PresentShape { + fn from(value: &str) -> Self { + let (_idx, rest) = value.split_once(":\n").unwrap(); + + let shape_raw: Grid = rest.parse().unwrap(); + let mut shape: Grid = shape_raw.same_shape(false); + for pos in shape_raw.find_all(&b'#') { + shape.set(&pos, true); + } + + Self { + variants: (0..4) + .map(|rot| shape.rotated(rot)) + .chain([MirrorAxis::X, MirrorAxis::Y].map(|axis| shape.mirrored(axis))) + .unique() + .collect(), + } + } +} + +impl Display for PresentShape { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("{}", self.variants[0])) + } +} + +impl PresentShape { + fn popcount(&self) -> u64 { + self.variants[0].count(&true) as u64 + } +} + +#[derive(Debug, Clone)] +struct Present { + shape: usize, +} + +#[derive(Debug, Clone)] +struct ChristmasTree { + area: Grid, + presents: Vec, +} + +#[derive(Debug, Clone)] +struct PresentsProblem { + trees: Vec, + shapes: Vec, +} + +#[aoc_generator(day12)] +fn parse(input: &str) -> PresentsProblem { + let mut parts = input.split("\n\n").collect_vec(); + let trees_s = parts.pop().unwrap(); + + let shapes: Vec = parts.into_iter().map(|p| p.into()).collect(); + let mut trees = Vec::new(); + + for l in trees_s.lines() { + let (d, el) = l.split_once(": ").unwrap(); + let (w, h) = d.split_once('x').unwrap(); + let present_counts: Vec = el + .split_ascii_whitespace() + .map(|count| count.parse().unwrap()) + .collect_vec(); + let presents = present_counts + .iter() + .enumerate() + .flat_map(|(i, count)| repeat_n(Present { shape: i }, *count)) + .collect(); + trees.push(ChristmasTree { + area: Grid::with_shape(w.parse().unwrap(), h.parse().unwrap(), false), + presents, + }); + } + + PresentsProblem { trees, shapes } +} + +// place b on a and test if any # overlap any non-. +// fn overlaps(a: &Grid, b: &Grid, p: &Coord2d) -> bool { +// b.find_all(&true) +// .any(|c| a.get(&(c + p)).is_some_and(|c| *c)) +// } + +impl PresentsProblem { + fn place_shape( + &self, + mut t: ChristmasTree, + idx: usize, + pos: Coord2d, + variant: usize, + ) -> Option { + let variant = &self.shapes[t.presents[idx].shape].variants[variant]; + + for xy in variant.find_all(&true) { + if let Some(was) = t.area.set(&(pos + &(xy)), true) + && was + { + // overlapped + return None; + } + } + Some(t) + } + + fn place_next( + &self, + t: ChristmasTree, + cur: usize, + cache: &mut HashSet<(usize, Grid)>, // impossible shapes + ) -> bool { + if cur == t.presents.len() { + // done + return true; + } + if cache.contains(&(cur, t.area.clone())) { + // doomed + return false; + } + let variants = &self.shapes[t.presents[cur].shape].variants; + for (i, _v) in variants.iter().enumerate() { + for y in 0..&t.area.height() - 2 { + for x in 0..&t.area.width() - 2 { + if let Some(new_t) = self.place_shape( + t.clone(), + cur, + Coord2d { + x: x as i64, + y: y as i64, + }, + i, + ) { + if self.place_next(new_t, cur + 1, cache) { + return true; + } + } + } + } + } + cache.insert((cur, t.area.clone())); + false + } +} + +#[aoc(day12, part1)] +fn part1(input: &PresentsProblem) -> u64 { + let input = input.clone(); + let mut count = 0; + + for (i, t) in input.trees.iter().enumerate() { + let timer = std::time::Instant::now(); + let area = (t.area.width() * t.area.height()) as u64; + let (occupied_area, present_count) = t + .presents + .iter() + .map(|p| (input.shapes[p.shape].popcount(), 1)) + .reduce(|(o_a, pc_a), (o_b, pc_b)| (o_a + o_b, pc_a + pc_b)) + .unwrap(); + if occupied_area > area { + let elapsed = timer.elapsed(); + println!("{i} - CULLED IMPOSSIBLE ({}ms)", elapsed.as_millis()); + // definitely impossible + continue; + } + let available_3x3s = (t.area.width() / 3) * (t.area.height() / 3); + if available_3x3s >= present_count { + let elapsed = timer.elapsed(); + println!("{i} - CULLED POSSIBLE ({}ms)", elapsed.as_millis()); + + // definitely_possible + count += 1; + continue; + } + if input.place_next(t.clone(), 0, &mut HashSet::new()) { + let elapsed = timer.elapsed(); + println!("{i} - SOLVED POSSIBLE ({}ms)", elapsed.as_millis()); + count += 1; + continue; + } + let elapsed = timer.elapsed(); + println!("{i} - SOLVED IMPOSSIBLE ({}ms)", elapsed.as_millis()); + } + + count +} + +#[aoc(day12, part2)] +fn part2(_input: &PresentsProblem) -> u64 { + 0 +} + +#[cfg(test)] +mod tests { + use super::*; + use rstest::rstest; + + const EXAMPLE: &str = "0: +### +##. +##. + +1: +### +##. +.## + +2: +.## +### +##. + +3: +##. +### +##. + +4: +### +#.. +### + +5: +### +.#. +### + +4x4: 0 0 0 0 2 0 +12x5: 1 0 1 0 2 2 +12x5: 1 0 1 0 3 2"; + + const EXAMPLE2: &str = "0: +.#. +### +.#. + +1: +### +#.. +### + +2: +### +#.# +### + +7x3: 1 2 0 +17x17: 37 0 0 +7x7: 1 0 4 +7x7: 0 0 5"; + + #[rstest] + #[case(EXAMPLE, 2)] + #[case(EXAMPLE2, 3)] + fn part1_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part1(&parse(input)), expected); + } + + #[rstest] + #[case(EXAMPLE, 0)] + fn part2_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part2(&parse(input)), expected); + } +} diff --git a/2025/src/day2.rs b/2025/src/day2.rs new file mode 100644 index 0000000..a9c2ae3 --- /dev/null +++ b/2025/src/day2.rs @@ -0,0 +1,217 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use itertools::Itertools; +use misc::POW10; +use std::cmp::{max, min}; +use std::ops::RangeInclusive; + +#[aoc_generator(day2)] +fn parse(input: &str) -> Vec> { + input + .split(',') + .map(|r| r.split_once('-').unwrap()) + .map(|(start, end)| RangeInclusive::new(start.parse().unwrap(), end.parse().unwrap())) + .collect() +} + +#[aoc(day2, part1, Brute)] +fn part1(input: &[RangeInclusive]) -> u64 { + let mut invalid_sum = 0; + + for r in input { + for product in r.clone() { + let prod_s = product.to_string(); + if !prod_s.len().is_multiple_of(2) { + continue; + } + let (left, right) = prod_s.split_at(prod_s.len() / 2); + if left == right { + invalid_sum += product + } + } + } + invalid_sum +} + +#[aoc(day2, part2, Brute)] +fn part2(input: &[RangeInclusive]) -> u64 { + let mut invalid_sum = 0; + for r in input { + for product in r.clone() { + let prod_s = product.to_string(); + for n in 1..=prod_s.len() / 2 { + if !prod_s.len().is_multiple_of(n) { + continue; + } + if prod_s + .chars() + .chunks(n) + .into_iter() + .map(|c| c.collect::()) + .all_equal() + { + invalid_sum += product; + break; + } + } + } + } + invalid_sum +} + +#[aoc(day2, part1, ArithmeticBrute)] +fn part1_arithmetic_brute(input: &[RangeInclusive]) -> u64 { + let mut invalid_sum = 0; + for r in input { + // println!("Range: {:?}", r); + for product in r.clone() { + let n_digits = (product.ilog10() + 1) as usize; + if !n_digits.is_multiple_of(2) { + continue; + } + + let decade = POW10[n_digits / 2]; + let lhs = product / decade; + let rhs = product % decade; + // println!("{product} {n_digits}: D:{decade} L:{lhs} R:{rhs}"); + if lhs == rhs { + invalid_sum += product + } + } + } + invalid_sum +} + +#[aoc(day2, part2, ArithmeticBrute)] +fn part2_arithmetic_brute(input: &[RangeInclusive]) -> u64 { + let mut invalid_sum = 0; + for r in input { + for product in r.clone() { + let n_digits = (product.ilog10() + 1) as usize; + + for n in 1..=n_digits / 2 { + if !n_digits.is_multiple_of(n) { + continue; + } + let repetitions = n_digits / n; + let decade = POW10[n_digits - n]; // get the power of 10 to split the leftmost n digits + let lhs = product / decade; + let remainder = product % decade; + + // for each repetition we multiply by 10^(rep * n) to add the appropriate zeros + let expected_remainder = (0..repetitions - 1).map(|rep| lhs * POW10[rep * n]).sum(); + + if remainder == expected_remainder { + invalid_sum += product; + break; + } + } + } + } + invalid_sum +} + +#[aoc(day2, part1, Clever)] +fn part1_clever(input: &[RangeInclusive]) -> u64 { + let mut invalid_sum = 0; + for r in input { + let n_digits = (r.start().ilog10() + 1) as usize; + + let mut lhs = if !n_digits.is_multiple_of(2) { + // If the number of digits is odd, we start our guess at the first possibility in the next decade + POW10[n_digits / 2] + } else { + let start_decade = POW10[n_digits / 2]; + r.start() / start_decade + }; + + // we will guess the next repeater, and check if it's in range, if not we are done. + loop { + let repeater = lhs * POW10[(lhs.ilog10() + 1) as usize] + lhs; + if repeater < *r.start() { + lhs += 1 + } else if r.contains(&repeater) { + invalid_sum += repeater; + lhs += 1 + } else { + break; + } + } + } + invalid_sum +} + +const fn n_digits(n: &u64) -> usize { + (n.ilog10() + 1) as usize +} + +fn generate_repeaters(r: &RangeInclusive, n: usize) -> Vec { + let mut invalids = Vec::new(); + for r in split_by_decade(r) { + let n_digits = n_digits(r.start()); + if !n_digits.is_multiple_of(n) || n_digits < 2 { + continue; + } + + let repetitions = n_digits / n; + let decade = POW10[n_digits - n]; + for lhs in (r.start() / decade)..=(r.end() / decade) { + let repeater = (0..repetitions) + .map(|rep| lhs * POW10[rep * n]) + .sum::(); + if r.contains(&repeater) { + invalids.push(repeater) + } + } + } + invalids +} + +fn split_by_decade(r: &RangeInclusive) -> impl Iterator> { + let (start, end) = (*r.start(), *r.end()); + (n_digits(r.start())..n_digits(r.end()) + 1) + .map(move |nd| RangeInclusive::new(max(start, POW10[nd - 1]), min(end, POW10[nd] - 1))) +} + +#[aoc(day2, part2, Clever)] +fn part2_clever(input: &[RangeInclusive]) -> u64 { + input + .iter() + .flat_map(|r| (1..=n_digits(r.end()) / 2).map(|nd| generate_repeaters(r, nd))) + .flatten() + .unique() + .sum() +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = "11-22,95-115,998-1012,1188511880-1188511890,222220-222224,1698522-1698528,446443-446449,38593856-38593862,565653-565659,824824821-824824827,2121212118-2121212124"; + + #[test] + fn part1_example() { + assert_eq!(part1(&parse(EXAMPLE)), 1227775554); + } + + #[test] + fn part2_example() { + assert_eq!(part2(&parse(EXAMPLE)), 4174379265); + } + + #[test] + fn part1_arithmetic_example() { + assert_eq!(part1_arithmetic_brute(&parse(EXAMPLE)), 1227775554); + } + #[test] + fn part2_arithmetic_example() { + assert_eq!(part2_arithmetic_brute(&parse(EXAMPLE)), 4174379265); + } + #[test] + fn part1_clever_example() { + assert_eq!(part1_clever(&parse(EXAMPLE)), 1227775554); + } + #[test] + fn part2_clever_example() { + assert_eq!(part2_clever(&parse(EXAMPLE)), 4174379265); + } +} diff --git a/2025/src/day3.rs b/2025/src/day3.rs new file mode 100644 index 0000000..e2167dc --- /dev/null +++ b/2025/src/day3.rs @@ -0,0 +1,90 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use cached::proc_macro::cached; +use misc::POW10; + +#[aoc_generator(day3)] +fn parse(input: &str) -> Vec> { + input + .lines() + .map(|bank| bank.bytes().map(|c| c - b'0').collect()) + .collect() +} + +#[cached] +fn max_joltage(bank: Vec, n: usize) -> u64 { + if n == 1 { + return *bank.iter().max().unwrap() as u64; + } + + (0..bank.len() - n + 1) + .map(|start| { + bank[start] as u64 * POW10[n - 1] + max_joltage(bank[start + 1..].to_vec(), n - 1) + }) + .max() + .unwrap() +} + +fn max_joltage_2(bank: &[u8], n: usize) -> u64 { + if n == 1 { + return *bank.iter().max().unwrap() as u64; + } + let choices = &bank[..bank.len() - (n - 1)]; + + // Note: can't use position_max() here since it returns the _last_ instance and we need the _first_. + // get the max, then find the first instance of that value. There is definitely a one-pass solution. + let max = choices.iter().max().unwrap(); + let choice = choices.iter().position(|n| max == n).unwrap(); + let rest = &bank[choice + 1..]; + + bank[choice] as u64 * POW10[n - 1] + max_joltage_2(rest, n - 1) +} + +#[aoc(day3, part1, Brute)] +fn part1(input: &[Vec]) -> u64 { + input.iter().map(|bank| max_joltage(bank.clone(), 2)).sum() +} + +#[aoc(day3, part2, Brute)] +fn part2(input: &[Vec]) -> u64 { + input.iter().map(|bank| max_joltage(bank.clone(), 12)).sum() +} + +#[aoc(day3, part1, Smart)] +fn part1_smart(input: &[Vec]) -> u64 { + input.iter().map(|bank| max_joltage_2(bank, 2)).sum() +} + +#[aoc(day3, part2, Smart)] +fn part2_smart(input: &[Vec]) -> u64 { + input.iter().map(|bank| max_joltage_2(bank, 12)).sum() +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = "987654321111111 +811111111111119 +234234234234278 +818181911112111"; + + #[test] + fn part1_example() { + assert_eq!(part1(&parse(EXAMPLE)), 357); + } + + #[test] + fn part2_example() { + assert_eq!(part2(&parse(EXAMPLE)), 3121910778619); + } + + #[test] + fn part1_smart_example() { + assert_eq!(part1_smart(&parse(EXAMPLE)), 357); + } + + #[test] + fn part2_smart_example() { + assert_eq!(part2_smart(&parse(EXAMPLE)), 3121910778619); + } +} diff --git a/2025/src/day4.rs b/2025/src/day4.rs new file mode 100644 index 0000000..d781cd6 --- /dev/null +++ b/2025/src/day4.rs @@ -0,0 +1,96 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use grid::Grid; +use itertools::Itertools; + +#[aoc_generator(day4)] +fn parse(input: &str) -> Grid { + input.parse().unwrap() +} + +#[aoc(day4, part1, Brute)] +fn part1(input: &Grid) -> u64 { + (0..input.height() * input.width()) + .filter(|i| *input.get(&input.coord(*i as i64).unwrap()).unwrap() == b'@') + .map(|i| input.adjacent_count(&input.coord(i as i64).unwrap(), |c| *c == b'@')) + .filter(|n| *n < 4) + .count() as u64 +} + +#[aoc(day4, part2, Brute)] +fn part2(input: &Grid) -> u64 { + let mut grid = input.clone(); + let mut removed = 0; + + loop { + let mut removed_iteration = 0; + for i in 0..grid.width() * grid.height() { + let pos = grid.coord(i as i64).unwrap(); + if grid.get(&pos).is_some_and(|c| *c == b'@') + && grid.adjacent_count(&pos, |c| *c == b'@') < 4 + { + // remove the roll + grid.set(&pos, b'.'); + removed_iteration += 1; + } + } + if removed_iteration == 0 { + return removed; + } + removed += removed_iteration + } +} + +#[aoc(day4, part2, RollList)] +fn part2_list(input: &Grid) -> u64 { + let mut grid = input.clone(); + let mut to_check = grid.find_all(&b'@').collect_vec(); + let mut removed = 0; + + while let Some(roll) = to_check.pop() { + if grid.get(&roll).is_none_or(|c| *c == b'.') { + continue; + } + let adjacent_rolls = grid + .adjacent_iter(&roll) + .filter_map(|i| if *i.value == b'@' { Some(i.pos) } else { None }) + .collect_vec(); + if adjacent_rolls.len() < 4 { + grid.set(&roll, b'.'); + removed += 1; + to_check.extend_from_slice(&adjacent_rolls); + } + } + + removed +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = "..@@.@@@@. +@@@.@.@.@@ +@@@@@.@.@@ +@.@@@@..@. +@@.@@@@.@@ +.@@@@@@@.@ +.@.@.@.@@@ +@.@@@.@@@@ +.@@@@@@@@. +@.@.@@@.@."; + + #[test] + fn part1_example() { + assert_eq!(part1(&parse(EXAMPLE)), 13); + } + + #[test] + fn part2_example() { + assert_eq!(part2(&parse(EXAMPLE)), 43); + } + + #[test] + fn part2_list_example() { + assert_eq!(part2_list(&parse(EXAMPLE)), 43); + } +} diff --git a/2025/src/day5.rs b/2025/src/day5.rs new file mode 100644 index 0000000..67418e5 --- /dev/null +++ b/2025/src/day5.rs @@ -0,0 +1,187 @@ +use std::cmp::max; +use std::fmt::Debug; +use std::ops::RangeInclusive; + +use aoc_runner_derive::{aoc, aoc_generator}; + +struct Database { + fresh_ingredients: Vec>, + available_ingredients: Vec, +} + +struct Database2 { + fresh_ingredients: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Span { + start: u64, + end: u64, +} + +impl From<(u64, u64)> for Span { + fn from(value: (u64, u64)) -> Self { + Self { + start: value.0, + end: value.1, + } + } +} + +impl Span { + fn len(&self) -> u64 { + self.end - self.start + 1 + } +} + +struct RangeSet { + ranges: Vec, +} + +impl RangeSet { + fn new() -> Self { + Self { ranges: Vec::new() } + } + fn simplify(&mut self) { + if self.ranges.len() < 2 { + return; + } + let mut modified = true; + while modified { + modified = false; + // sort the ranges by start + self.ranges.sort_by_key(|s| s.start); + let mut new_ranges = Vec::new(); + let mut pos = 1; + + while pos <= self.ranges.len() { + // part of a disgusting hack to avoid skipping or double adding at the end + if pos == self.ranges.len() { + pos -= 1; + } + let (l, r) = (&self.ranges[pos - 1], &self.ranges[pos]); + + if r.start <= l.end + 1 { + modified = true; + new_ranges.push((l.start, max(l.end, r.end)).into()); + // if we merged, skip checking the next range to avoid double-adding it + // this screws us up at the very end, so need the disgusting hack above + pos += 2; + } else if pos < self.ranges.len() - 1 { + // keep only the lhs if we didn't merge + new_ranges.push(l.clone()); + pos += 1; + } else { + // at the end, keep both sides, otherwise the rhs gets excluded (if it didn't merge) + new_ranges.push(l.clone()); + new_ranges.push(r.clone()); + pos += 2; + } + } + + self.ranges = new_ranges; + } + } + fn add(&mut self, s: Span) { + self.ranges.push(s); + } +} + +#[aoc_generator(day5)] +fn parse(input: &str) -> Database { + let mut fresh_ingredients = Vec::new(); + let mut available_ingredients = Vec::new(); + let mut parsing_ranges = true; + for line in input.lines() { + if line.is_empty() { + parsing_ranges = false; + continue; + } + if parsing_ranges { + let (start, end) = line.split_once('-').unwrap(); + fresh_ingredients.push(RangeInclusive::new( + start.parse().unwrap(), + end.parse().unwrap(), + )); + } else { + available_ingredients.push(line.parse().unwrap()) + } + } + Database { + fresh_ingredients, + available_ingredients, + } +} + +#[aoc(day5, part1)] +fn part1(input: &Database) -> u64 { + input + .available_ingredients + .iter() + .filter(|i| input.fresh_ingredients.iter().any(|r| r.contains(i))) + .count() as u64 +} + +#[aoc_generator(day5, part2, Naive)] +fn parse2(input: &str) -> Database2 { + let mut fresh_ingredients = Vec::new(); + for line in input.lines() { + if line.is_empty() { + return Database2 { fresh_ingredients }; + } + let (start, end) = line.split_once('-').unwrap(); + fresh_ingredients.push((start.parse().unwrap(), end.parse().unwrap()).into()); + } + Database2 { fresh_ingredients } +} + +#[aoc(day5, part2, Naive)] +fn part2(input: &Database2) -> u64 { + let mut all_ingredients = RangeSet::new(); + for r in &input.fresh_ingredients { + all_ingredients.add(r.clone()); + } + all_ingredients.simplify(); + all_ingredients.ranges.iter().map(|r| r.len()).sum::() +} + +#[aoc(day5, part2, RangeSet)] +fn part2_rangeset(input: &Database) -> u64 { + let mut all_ingredients = misc::range::RangeSet::new(); + for r in &input.fresh_ingredients { + all_ingredients.add(r); + } + all_ingredients.store.iter().map(|r| r.end - r.start).sum() +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = "3-5 +10-14 +16-20 +12-18 + +1 +5 +8 +11 +17 +32"; + + #[test] + fn part1_example() { + assert_eq!(part1(&parse(EXAMPLE)), 3); + } + + #[test] + fn part2_example() { + assert_eq!(part2(&parse2(EXAMPLE)), 14); + } + + #[test] + fn part2_set_example() { + assert_eq!(part2_rangeset(&parse(EXAMPLE)), 14); + } +} diff --git a/2025/src/day6.rs b/2025/src/day6.rs new file mode 100644 index 0000000..7ff071e --- /dev/null +++ b/2025/src/day6.rs @@ -0,0 +1,280 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use grid::Grid; +use itertools::Itertools; +use misc::POW10; +use std::{ + fmt::{Display, Write}, + iter::repeat_n, + str::FromStr, +}; + +#[repr(u8)] +enum Op { + Add = b'+', + Mul = b'*', +} + +impl From<&str> for Op { + fn from(value: &str) -> Self { + match value { + "+" => Op::Add, + "*" => Op::Mul, + c => panic!("Invalid op `{c}`"), + } + } +} + +impl From<&u8> for Op { + fn from(value: &u8) -> Self { + match value { + b'+' => Op::Add, + b'*' => Op::Mul, + c => panic!("Invalid op `{c}`"), + } + } +} + +impl Display for Op { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Op::Add => f.write_char('+'), + Op::Mul => f.write_char('*'), + } + } +} + +impl Op { + fn f(&self, lhs: &u64, rhs: &u64) -> u64 { + match self { + Op::Add => lhs + rhs, + Op::Mul => lhs * rhs, + } + } +} + +#[aoc_generator(day6, part1)] +fn parse(input: &str) -> (Grid, Vec) { + let mut rows = input + .lines() + .map(|l| l.split_ascii_whitespace().collect_vec()) + .collect_vec(); + + let ops = rows + .pop() + .unwrap() + .iter() + .map(|op| Op::from(*op)) + .collect_vec(); + let mut grid = Grid::with_shape(rows[0].len(), rows.len(), 0); + + for (y, r) in rows.iter().enumerate() { + for (x, v) in r.iter().enumerate() { + grid.set(&(x, y), v.parse().unwrap()); + } + } + + (grid, ops) +} + +#[aoc(day6, part1)] +fn part1((grid, ops): &(Grid, Vec)) -> u64 { + (0..grid.width()) + .map(|x| { + grid.col_iter(x as i64) + .unwrap() + .cloned() + .reduce(|l, r| ops[x].f(&l, &r)) + .unwrap() + }) + .sum() +} + +// fn split_digits(x: &u64) -> Vec { +// let n_digits = x.ilog10() as usize; +// (0..=n_digits) +// .rev() +// .map(|n| ((x / POW10[n]) % 10) as u8) +// .collect() +// } + +#[aoc_generator(day6, part2, Spaghett)] +fn parse2(input: &str) -> (Grid>, Vec) { + let mut rows = input.lines().collect_vec(); + let ops = rows.pop().unwrap(); + + let col_starts = ops + .chars() + .enumerate() + .filter(|(_i, c)| *c == '+' || *c == '*') + .map(|(i, _c)| i) + .collect_vec(); + + let col_lengths = col_starts + .iter() + .tuple_windows() + .map(|(l, r)| r - l - 1) + .collect_vec(); + + let split_rows = rows + .iter() + .map(|r| { + col_starts + .iter() + .zip(col_lengths.iter()) + .map(|(s, l)| &r[*s..s + l]) + .chain(repeat_n(&r[*col_starts.last().unwrap()..], 1)) + .collect_vec() + }) + .collect_vec(); + + let ops = ops.split_ascii_whitespace().map(Op::from).collect_vec(); + let mut grid = Grid::with_shape(split_rows[0].len(), split_rows.len(), Vec::new()); + for (y, r) in split_rows.iter().enumerate() { + for (x, v) in r.iter().enumerate() { + grid.set(&(x, y), v.chars().collect_vec()); + } + } + + (grid, ops) +} + +#[aoc(day6, part2, Spaghett)] +fn part2((grid, ops): &(Grid>, Vec)) -> u64 { + let mut columns = Vec::new(); + for col in 0..grid.width() { + let mut digit = 0; + let mut col_values = Vec::new(); + loop { + let val = grid + .col_iter(col as i64) + .unwrap() + .filter_map(|s| s.get(digit)) + .filter(|c| !c.is_ascii_whitespace()) + .map(|v| v.to_digit(10).unwrap() as u64) + .fold(0, |acc, n| acc * 10 + n); + if val == 0 { + columns.push(col_values); + break; + } + col_values.push(val); + digit += 1; + } + } + columns + .iter() + .enumerate() + .map(|(col, v)| v.iter().cloned().reduce(|l, r| ops[col].f(&l, &r)).unwrap()) + .sum::() +} + +#[aoc_generator(day6, part2, StateMachine)] +fn parse2_walk(input: &str) -> Grid { + Grid::from_str(input).unwrap() +} + +enum NextPos { + Advance((usize, usize)), + NewCol((usize, usize)), + Done, +} + +#[aoc(day6, part2, StateMachine)] +fn part2_walk(g: &Grid) -> u64 { + let mut accum = 0; + + // start at the bottom right + let mut pos = (g.width() - 1, g.height() - 1); + let mut digits = 0; + let mut cur_value = 0; + let mut cur_values = Vec::new(); + let mut cur_op = Op::Add; + let mut last_col = false; + + let height = g.height() - 1; + + let next_pos = |(x, y)| -> NextPos { + if y == 0 { + if x == 0 { + return NextPos::Done; + } + return NextPos::NewCol((x - 1, height)); + } + NextPos::Advance((x, y - 1)) + }; + + while let Some(cur_char) = g.get(&pos) { + match cur_char { + b'*' | b'+' => { + last_col = true; + cur_op = cur_char.into() + } + cur_char if cur_char.is_ascii_digit() => { + cur_value += (*cur_char - b'0') as u64 * POW10[digits]; + digits += 1; + } + _ => {} + } + pos = match next_pos(pos) { + NextPos::Advance(p) => p, + NextPos::NewCol(p) => { + // add the value + if cur_value != 0 { + cur_values.push(cur_value); + cur_value = 0; + } + digits = 0; + // this was a last col, so reduce and accumulate + if last_col { + accum += cur_values + .iter() + .cloned() + .reduce(|l, r| cur_op.f(&l, &r)) + .unwrap_or(0); + // clear the state + cur_values.clear(); + last_col = false; + } + p + } + NextPos::Done => { + if cur_value != 0 { + cur_values.push(cur_value); + } + // accumulate the final result + accum += cur_values + .iter() + .cloned() + .reduce(|l, r| cur_op.f(&l, &r)) + .unwrap_or(0); + return accum; + } + } + } + + unreachable!() +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = r"123 328 51 64 + 45 64 387 23 + 6 98 215 314 +* + * + "; + + #[test] + fn part1_example() { + assert_eq!(part1(&parse(EXAMPLE)), 4277556); + } + + #[test] + fn part2_example() { + assert_eq!(part2(&parse2(EXAMPLE)), 3263827); + } + + #[test] + fn part2_walk_example() { + assert_eq!(part2_walk(&parse2_walk(EXAMPLE)), 3263827); + } +} diff --git a/2025/src/day7.rs b/2025/src/day7.rs new file mode 100644 index 0000000..64150bf --- /dev/null +++ b/2025/src/day7.rs @@ -0,0 +1,102 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use grid::{Coord2d, Grid}; +use std::str::FromStr; + +#[aoc_generator(day7)] +fn parse(input: &str) -> Grid { + Grid::from_str(input).unwrap() +} + +fn emit_beams(grid: &mut Grid, pos: Coord2d) -> u64 { + match grid.set(&pos, b'|') { + None | Some(b'|') => 0, + Some(b'.') | Some(b'S') => emit_beams(grid, pos + &(0, 1)), + Some(b'^') => 1 + emit_beams(grid, pos + &(-1, 0)) + emit_beams(grid, pos + &(1, 0)), + _ => panic!(), + } +} + +#[aoc(day7, part1)] +fn part1(input: &Grid) -> u64 { + let mut grid = input.clone(); + emit_beams(&mut grid, input.find(&b'S').unwrap()) +} + +#[aoc(day7, part2)] +fn part2(input: &Grid) -> u64 { + let mut col_counts = vec![0; input.width()]; + col_counts[input.find(&b'S').unwrap().x as usize] = 1; + + // Start row is already set up + for y in 1..input.height() { + // for each column with non-zero counts + for x in 0..input.width() { + if col_counts[x] == 0 { + continue; + } + match input.get(&(x, y)) { + // if our current position is a caret, add that count to our neighbours + Some(b'^') => { + for col in [x as i64 - 1, x as i64 + 1] + .into_iter() + .filter(|x| *x >= 0 && *x < input.width() as i64) + { + col_counts[col as usize] += col_counts[x]; + } + col_counts[x] = 0; + } + // if our current position is a . do nothing, it's already counted + Some(b'.') => continue, + Some(c) => panic!("unexpected character {c}"), + None => panic!("How did we end up outside the grid?"), + } + } + } + + col_counts.iter().sum::() +} + +#[cfg(test)] +mod tests { + use super::*; + + const TRIVIAL_EXAMPLE: &str = "...S... +....... +...^... +..^.^.^ +...^.^. +....... +......."; + + const EXAMPLE: &str = ".......S....... +............... +.......^....... +............... +......^.^...... +............... +.....^.^.^..... +............... +....^.^...^.... +............... +...^.^...^.^... +............... +..^...^.....^.. +............... +.^.^.^.^.^...^. +..............."; + + #[test] + fn part1_example() { + assert_eq!(part1(&parse(EXAMPLE)), 21); + } + + #[test] + fn part2_example() { + assert_eq!(part2(&parse(EXAMPLE)), 40); + } + + #[test] + fn part2_trivial_example() { + assert_eq!(part2(&parse(TRIVIAL_EXAMPLE)), 7); + } +} diff --git a/2025/src/day8.rs b/2025/src/day8.rs new file mode 100644 index 0000000..de7e153 --- /dev/null +++ b/2025/src/day8.rs @@ -0,0 +1,249 @@ +use std::{cmp::Reverse, collections::BinaryHeap, fmt::Display}; + +use aoc_runner_derive::{aoc, aoc_generator}; +use itertools::Itertools; + +#[derive(PartialEq, Clone, Debug)] +struct Junction { + pos: (i64, i64, i64), +} + +fn squared_distance(a: &Junction, b: &Junction) -> u64 { + // if a.pos == b.pos { + // 0 + // } else { + (a.pos.0 - b.pos.0).pow(2) as u64 + + (a.pos.1 - b.pos.1).pow(2) as u64 + + (a.pos.2 - b.pos.2).pow(2) as u64 + // } +} + +impl Junction { + fn squared_distance(&self, other: &Junction) -> u64 { + squared_distance(self, other) + } +} + +impl Display for Junction { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!( + "({},{},{})", + self.pos.0, self.pos.1, self.pos.2 + )) + } +} + +impl From<&str> for Junction { + fn from(value: &str) -> Self { + Self { + pos: value + .split(',') + .map(|v| v.parse().unwrap()) + .collect_tuple() + .unwrap(), + } + } +} + +#[derive(Clone)] +struct Circuits { + junctions: Vec, + circuits: Vec>, +} + +impl Circuits { + fn find_circuit(&self, junction: usize) -> usize { + self.circuits + .iter() + .enumerate() + .find(|(_i, c)| c.contains(&junction)) + .map(|(i, _c)| i) + .unwrap() + } + fn merge_circuits(&mut self, a: usize, b: usize) { + if a == b { + return; + } + let mut items = std::mem::take(&mut self.circuits[b]); + self.circuits[a].append(&mut items); + self.circuits.remove(b); + } + + fn connect(&mut self, a: usize, b: usize) { + let a_circuit = self.find_circuit(a); + let b_circuit = self.find_circuit(b); + + self.merge_circuits(a_circuit, b_circuit); // both are already in circuits, merge them + } +} + +#[aoc_generator(day8)] +fn parse(input: &str) -> Circuits { + let junctions = input.lines().map(|l| l.into()).collect_vec(); + + Circuits { + circuits: Vec::from_iter((0..junctions.len()).map(|i| vec![i])), + junctions, + } +} + +fn part1_impl(input: &Circuits, n: usize) -> u64 { + let mut circuits = input.clone(); + for (a, b, _d) in circuits + .junctions + .iter() + .enumerate() + .tuple_combinations() + .map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.squared_distance(b))) + .sorted_unstable_by_key(|(_a_pos, _b_pos, d)| *d) + .take(n) + { + circuits.connect(a, b) + } + + circuits + .circuits + .iter() + .map(|c| c.len()) + .sorted_unstable() + .rev() + .take(3) + .reduce(|a, b| a * b) + .unwrap() as u64 +} + +#[aoc(day8, part1, Sorted)] +fn part1(input: &Circuits) -> u64 { + part1_impl(input, 1000) +} + +#[aoc(day8, part2, Sorted)] +fn part2(input: &Circuits) -> u64 { + let mut circuits = input.clone(); + + for (a, b, _d) in circuits + .junctions + .iter() + .enumerate() + .tuple_combinations() + .map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.squared_distance(b))) + .sorted_unstable_by_key(|(_a_pos, _b_pos, d)| *d) + { + circuits.connect(a, b); + if circuits.circuits.len() == 1 { + return (circuits.junctions[a].pos.0 * circuits.junctions[b].pos.0) as u64; + } + } + + panic!() +} + +#[derive(PartialEq, Eq, PartialOrd, Ord)] +struct JunctionPair { + d: u64, + a: usize, + b: usize, +} + +fn make_heap(circuits: &Circuits) -> BinaryHeap> { + BinaryHeap::from_iter( + circuits + .junctions + .iter() + .enumerate() + .tuple_combinations() + .map(|((a_pos, a), (b_pos, b))| { + Reverse(JunctionPair { + a: a_pos, + b: b_pos, + d: a.squared_distance(b), + }) + }), + ) +} + +fn part1_heaped_impl(input: &Circuits, n: usize) -> u64 { + let mut circuits = input.clone(); + let mut distances = make_heap(&circuits); + + for _ in 0..n { + let pair = distances.pop().unwrap().0; + circuits.connect(pair.a, pair.b); + } + + circuits + .circuits + .iter() + .map(|c| c.len()) + .sorted_unstable() + .rev() + .take(3) + .reduce(|a, b| a * b) + .unwrap() as u64 +} + +#[aoc(day8, part1, Heaped)] +fn part1_heaped(input: &Circuits) -> u64 { + part1_heaped_impl(input, 1000) +} + +#[aoc(day8, part2, Heaped)] +fn part2_heaped(input: &Circuits) -> u64 { + let mut circuits = input.clone(); + let mut distances = make_heap(&circuits); + + while let Some(Reverse(jp)) = distances.pop() { + circuits.connect(jp.a, jp.b); + if circuits.circuits.len() == 1 { + return (circuits.junctions[jp.a].pos.0 * circuits.junctions[jp.b].pos.0) as u64; + } + } + + panic!() +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = "162,817,812 +57,618,57 +906,360,560 +592,479,940 +352,342,300 +466,668,158 +542,29,236 +431,825,988 +739,650,466 +52,470,668 +216,146,977 +819,987,18 +117,168,530 +805,96,715 +346,949,466 +970,615,88 +941,993,340 +862,61,35 +984,92,344 +425,690,689"; + + #[test] + fn part1_example() { + assert_eq!(part1_impl(&parse(EXAMPLE), 10), 40); + } + + #[test] + fn part1_heaped_example() { + assert_eq!(part1_heaped_impl(&parse(EXAMPLE), 10), 40); + } + + #[test] + fn part2_example() { + assert_eq!(part2(&parse(EXAMPLE)), 25272); + } + + #[test] + fn part2_heaped_example() { + assert_eq!(part2_heaped(&parse(EXAMPLE)), 25272); + } +} diff --git a/2025/src/day9.rs b/2025/src/day9.rs new file mode 100644 index 0000000..393de8f --- /dev/null +++ b/2025/src/day9.rs @@ -0,0 +1,621 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use grid::{AsCoord2d, Coord2d, Grid}; +use indicatif::{ParallelProgressIterator, ProgressIterator, ProgressStyle}; +use itertools::Itertools; +use rayon::prelude::*; +use std::collections::{HashMap, VecDeque}; +use std::{ + cmp::{max, min}, + fmt::Display, +}; + +#[aoc_generator(day9)] +fn parse(input: &str) -> Vec { + input + .lines() + .map(|l| l.parse::().unwrap()) + .map(|c| Coord2d { + x: c.x + 1, // allow a buffer zone + y: c.y + 1, + }) + .collect() +} + +#[aoc(day9, part1)] +fn part1(input: &Vec) -> u64 { + input + .iter() + .tuple_combinations() + .inspect(|(a, b)| { + println!( + "{a} vs {b} = {}", + a.x().abs_diff(b.x()) * a.y().abs_diff(b.y()) + ) + }) + .map(|(a, b)| (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1)) + .sorted_unstable() + .next_back() + .unwrap() +} + +fn build_grid(reds: &Vec) -> Grid { + let width = reds.iter().map(|c| c.x()).max().unwrap() + 3; + let height = reds.iter().map(|c| c.y()).max().unwrap() + 3; + + let mut grid = Grid::with_shape(width as usize, height as usize, b'.'); + let mut prev = reds.last().unwrap(); + for c in reds { + // mark c filled + grid.set(&c, b'#'); + // build a line of green between it and the previous + if c.x() == prev.x() { + // vertical + for y in (min(c.y(), prev.y()) + 1)..max(c.y(), prev.y()) { + grid.set(&(c.x(), y), b'X'); + } + } else if c.y() == prev.y() { + // horiztonal + for x in (min(c.x(), prev.x()) + 1)..max(c.x(), prev.x()) { + grid.set(&(x, c.y()), b'X'); + } + } else { + panic!() + } + prev = c + } + + grid +} + +fn build_hashgrid(reds: &Vec) -> HashMap { + let mut grid = HashMap::new(); + let mut prev = reds.last().unwrap(); + for c in reds { + // mark c filled + grid.insert(*c, b'#'); + // build a line of green between it and the previous + if c.x() == prev.x() { + // vertical + for y in (min(c.y(), prev.y()) + 1)..max(c.y(), prev.y()) { + grid.insert(Coord2d { x: c.x(), y }, b'X'); + } + } else if c.y() == prev.y() { + // horiztonal + for x in (min(c.x(), prev.x()) + 1)..max(c.x(), prev.x()) { + grid.insert(Coord2d { x, y: c.y() }, b'X'); + } + } else { + panic!() + } + prev = c + } + + grid +} + +fn flood_fill(grid: &mut Grid, pos: Coord2d) { + if grid.get(&pos) != Some(&b'.') { + return; + } + let mut q = VecDeque::new(); + q.push_back(pos); + while let Some(next) = q.pop_front() { + let (mut lx, mut rx) = (next.x, next.x); + while grid.get(&Coord2d { + x: lx - 1, + y: next.y, + }) == Some(&b'.') + { + grid.set( + &Coord2d { + x: lx - 1, + y: next.y, + }, + b'X', + ); + lx -= 1; + } + while grid.get(&Coord2d { x: rx, y: next.y }) == Some(&b'.') { + grid.set(&Coord2d { x: rx, y: next.y }, b'X'); + rx += 1; + } + flood_scan(grid, lx, rx, next.y + 1, &mut q); + flood_scan(grid, lx, rx, next.y - 1, &mut q); + } +} + +fn flood_scan(grid: &mut Grid, lx: i64, rx: i64, y: i64, q: &mut VecDeque) { + let mut span_added = false; + for x in lx..rx { + if grid.get(&Coord2d { x, y }) != Some(&b'.') { + span_added = false + } else if !span_added { + q.push_back(Coord2d { x, y }); + span_added = true + } + } +} + +// #[aoc(day9, part2, Brute)] +fn part2(reds: &Vec) -> u64 { + let mut grid = build_grid(reds); + // Find the first red starting at top left - 'inside' must be to its bottom right + let start = grid.find(&b'#').unwrap(); + flood_fill(&mut grid, start + &(1, 1).to_coord()); + // println!("{grid}"); + + let pairs = reds + .iter() + .tuple_combinations() + .sorted_unstable_by_key(|(a, b)| (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1)) + .rev() + .progress() + .collect_vec(); + + let (a, b) = pairs + .par_iter() + .progress_with_style( + ProgressStyle::with_template( + "[{elapsed_precise}/{eta_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {per_sec}", + ) + .unwrap(), + ) + .filter(|(a, b)| (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1) < 2972065369) // FIXME: PROGRESS CAPTURE + .map(|(a, b)| { + for y in (min(a.y(), b.y()))..=max(a.y(), b.y()) { + for x in (min(a.x(), b.x()))..=max(a.x(), b.y()) { + if *grid.get(&(x, y)).unwrap() == b'.' { + return (false, a, b); + } + } + } + (true, a, b) + }) + .find_map_first(|(good, a, b)| if good { Some((a, b)) } else { None }) + .unwrap(); + // println!("win: {a} {b}"); + (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1) +} + +fn line_square_intersection( + &(l1, l2): &(<, <), + &(sq1, sq2): &(&ST, &ST), +) -> bool +where + LT: Clone + Display, + ST: Clone + Display, +{ + let min_x = min(sq1.x(), sq2.x()); + let max_x = max(sq1.x(), sq2.x()); + let min_y = min(sq1.y(), sq2.y()); + let max_y = max(sq1.y(), sq2.y()); + + // println!("({},{}) X [{},{}]", l1, l2, sq1, sq2); + // line is horizontal + if l1.y() == l2.y() { + // println!(" horizontal at y={}", l1.y()); + // above, below, or touching square + if l1.y() <= min_y || l1.y() >= max_y { + // println!(" y out of range or touching"); + false + // start inside + } else if min(l1.x(), l2.x()) >= min_x && min(l1.x(), l2.x()) <= max_x { + // println!(" start inside"); + true + //end inside + } else if max(l1.x(), l2.x()) >= min_x && max(l1.x(), l2.x()) <= max_x { + // println!(" end inside"); + true + } else { + // println!(" no overlap on x"); + false + } + // line is vertical + } else { + // println!(" vertical at x={}", l1.x()); + if l1.x() <= min_x || l1.x() >= max_x { + // println!(" x out of range or touching"); + false + // start inside + } else if min(l1.y(), l2.y()) >= min_y && min(l1.y(), l2.y()) <= max_y { + // println!(" start inside"); + true + //end inside + } else if max(l1.y(), l2.y()) >= min_y && max(l1.y(), l2.y()) <= max_y { + // println!(" end inside"); + true + } else { + // println!(" no overlap on y"); + false + } + } +} + +trait Rectangle { + fn top_left(&self) -> Coord2d; + fn bottom_right(&self) -> Coord2d; + fn in_bounds(&self, b: &T) -> bool { + b.x() >= self.top_left().x + && b.x() <= self.bottom_right().x() + && b.y() >= self.top_left().y() + && b.y() <= self.bottom_right().y() + } + fn area(&self) -> u64 { + let a = self.top_left(); + let b = self.bottom_right(); + (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1) + } +} + +impl Rectangle for (&Coord2d, &Coord2d) { + fn top_left(&self) -> Coord2d { + Coord2d { + x: min(self.0.x, self.1.x), + y: min(self.0.y, self.1.y), + } + } + fn bottom_right(&self) -> Coord2d { + Coord2d { + x: max(self.0.x, self.1.x), + y: max(self.0.y, self.1.y), + } + } +} + +// true = clockwise +fn outside_points(prev: &Coord2d, cur: &Coord2d, next: &Coord2d) -> Vec { + let l1_diff = ((cur.x - prev.x).signum(), (cur.y - prev.y).signum()); + let l2_diff = ((next.x - cur.x).signum(), (next.y - cur.y).signum()); + + match (l1_diff, l2_diff) { + // CW + ((1, 0), (0, 1)) => vec![cur + (0, -1), cur + (1, -1), cur + (1, 0)], // x^ y^ + ((0, 1), (-1, 0)) => vec![cur + (1, 0), cur + (1, 1), cur + (0, 1)], + ((-1, 0), (0, -1)) => vec![cur + (0, 1), cur + (-1, 1), cur + (-1, 0)], // xv yv + ((0, -1), (1, 0)) => vec![cur + (-1, 0), cur + (-1, -1), cur + (0, -1)], // yv x^ + // CCW + ((0, 1), (1, 0)) => vec![cur + (1, -1)], + ((1, 0), (0, -1)) => vec![cur + (-1, -1)], + ((0, -1), (-1, 0)) => vec![cur + (-1, 1)], + ((-1, 0), (0, 1)) => vec![cur + (1, 1)], + ((0, _), (0, _)) | ((_, 0), (_, 0)) => vec![], // colinear + _ => panic!( + "unexpected line arrangement {:?} {:?} @ [({},{}), ({},{}), ({},{})", + l1_diff, l2_diff, prev.x, prev.y, cur.x, cur.y, next.x, next.y + ), + } +} + +#[aoc(day9, part2, Lines)] +fn part2_lines(reds: &Vec) -> u64 { + // let mut grid = build_hashgrid(reds); + // let mut grid = build_grid(reds); + // // println!("{grid}"); + // let area: i64 = reds + // .iter() + // .circular_tuple_windows() + // .map(|(a, b)| (a.x * b.y) - (b.x * a.y)) + // .sum(); + // let outside_points: HashMap<&Coord2d, Vec> = if area < 0 { + // reds.iter() + // .rev() + // .circular_tuple_windows() + // .map(|(a, b, c)| (b, outside_points(a, b, c))) + // .collect() + // } else { + // reds.iter() + // .circular_tuple_windows() + // .map(|(a, b, c)| (b, outside_points(a, b, c))) + // .collect() + // }; + + // for corner in reds { + // for p in &outside_points[corner] { + // if *grid.get(p).unwrap() == b'.' { + // grid.set(p, b'O'); + // } + // } + // } + + // println!("{grid}"); + + // still iterate over the possible rectangles in size order + for rect in reds + .iter() + .tuple_combinations() + .sorted_unstable_by_key(|rect: &(&Coord2d, &Coord2d)| rect.area()) + .rev() + .progress_with_style( + ProgressStyle::with_template( + "[{elapsed_precise}/{eta_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {per_sec}", + ) + .unwrap(), + ) + { + let tl = rect.top_left(); + let br = rect.bottom_right(); + + let invalid = reds.iter().circular_tuple_windows().any(|(a, b)| { + // 1. A polygon vertex lies strictly inside the rectangle + let node_inside = tl.x < a.x && a.x < br.x && tl.y < a.y && a.y < br.y; + + // 2. A polygon edge slices all the way across the rectangle + let crosses_bounds = if a.x == b.x { + let (ey_min, ey_max) = (a.y.min(b.y), a.y.max(b.y)); + (tl.x < a.x && a.x < br.x) && (ey_min <= tl.y && ey_max >= br.y) + } else { + let (ex_min, ex_max) = (a.x.min(b.x), a.x.max(b.x)); + (tl.y < a.y && a.y < br.y) && (ex_min <= tl.x && ex_max >= br.x) + }; + + node_inside || crosses_bounds + }); + + if invalid { + continue; + } + + // println!( + // "win! {},{} = {}", + // rect.top_left(), + // rect.bottom_right(), + // rect.area() + // ); + // grid.set(&rect.top_left(), b'*'); + // grid.set(&rect.bottom_right(), b'*'); + + // println!("{grid}"); + return rect.area(); + } + panic!() +} + +#[cfg(test)] +mod tests { + use super::*; + use rstest::rstest; + + const EXAMPLE: &str = "7,1 +11,1 +11,7 +9,7 +9,5 +2,5 +2,3 +7,3"; + + #[test] + fn part1_example() { + assert_eq!(part1(&parse(EXAMPLE)), 50); + } + + #[test] + fn part2_example() { + assert_eq!(part2(&parse(EXAMPLE)), 24); + } + + #[rstest] + #[case( + "7,1 +11,1 +11,7 +9,7 +9,5 +2,5 +2,3 +7,3", + 24 + )] + #[case( + "4,2 +13,2 +13,4 +8,4 +8,6 +11,6 +11,10 +4,10", + 40 + )] + #[case( + "3,2 +17,2 +17,13 +13,13 +13,11 +15,11 +15,8 +11,8 +11,15 +18,15 +18,17 +4,17 +4,12 +6,12 +6,5 +3,5", + 66 + )] + #[case( + "2,2 +8,2 +8,6 +5,6 +5,4 +2,4", + 21 + )] + #[case( + "3,1 +12,1 +12,4 +9,4 +9,8 +3,8", + 56 + )] + #[case( + "7,1 +11,1 +11,3 +13,3 +13,5 +11,5 +11,7 +9,7 +9,5 +2,5 +2,3 +7,3", + 36 + )] + #[case( + "1,2 +8,2 +8,4 +6,4 +6,5 +9,5 +9,8 +1,8", + 56 + )] + #[case( + "1,1 +4,1 +4,5 +7,5 +7,1 +10,1 +10,8 +1,8", + 32 + )] + #[case( + "1,1 +5,1 +5,6 +7,6 +7,1 +11,1 +11,9 +1,9", + 45 + )] + #[case( + "1,1 +5,1 +5,7 +6,7 +6,1 +10,1 +10,9 +1,9", + 90 + )] + #[case( + "1,1 +12,1 +12,8 +10,8 +10,3 +8,3 +8,8 +6,8 +6,3 +4,3 +4,8 +1,8", + 32 + )] + #[case( + "1,1 +1,8 +10,8 +10,1 +7,1 +7,5 +4,5 +4,1", + 32 + )] + #[case( + "4,1 +7,1 +7,4 +10,4 +10,7 +7,7 +7,10 +4,10 +4,7 +1,7 +1,4 +4,4", + 40 + )] + #[case( + "1,1 +12,1 +12,10 +1,10 +1,8 +10,8 +10,3 +1,3", + 36 + )] + #[case( + "1,1 +10,1 +10,6 +4,6 +4,8 +10,8 +10,12 +1,12 +1,7 +7,7 +7,4 +1,4", + 50 + )] + #[case( + "1,1 +10,1 +10,10 +3,10 +3,4 +7,4 +7,7 +5,7 +5,6 +6,6 +6,5 +4,5 +4,9 +9,9 +9,2 +1,2", + 20 + )] + #[case( + "1,1 +5,1 +5,3 +7,3 +7,4 +2,4 +2,7 +7,7 +7,8 +3,8 +3,11 +1,11", + 16 + )] + + fn part2_lines_example(#[case] input: &str, #[case] answer: u64) { + assert_eq!(part2_lines(&parse(input)), answer); + } +} diff --git a/2025/src/lib.rs b/2025/src/lib.rs new file mode 100644 index 0000000..5ed53fe --- /dev/null +++ b/2025/src/lib.rs @@ -0,0 +1,16 @@ +mod day1; +mod day10; +mod day11; +mod day12; +mod day2; +mod day3; +mod day4; +mod day5; +mod day6; +mod day7; +mod day8; +mod day9; + +use aoc_runner_derive::aoc_lib; + +aoc_lib! { year = 2025 } diff --git a/2025/src/main.rs b/2025/src/main.rs new file mode 100644 index 0000000..4207064 --- /dev/null +++ b/2025/src/main.rs @@ -0,0 +1,3 @@ +use aoc_runner_derive::aoc_main; + +aoc_main! { lib = aoc2025 } diff --git a/2025/utils/grid/Cargo.lock b/2025/utils/grid/Cargo.lock new file mode 100644 index 0000000..1c1a197 --- /dev/null +++ b/2025/utils/grid/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "grid" +version = "0.1.0" diff --git a/2025/utils/grid/Cargo.toml b/2025/utils/grid/Cargo.toml new file mode 100644 index 0000000..a95c55e --- /dev/null +++ b/2025/utils/grid/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "grid" +version = "0.1.0" +edition = "2024" + +[dependencies] + +[lib] +path = "lib.rs" diff --git a/2025/utils/grid/lib.rs b/2025/utils/grid/lib.rs new file mode 100644 index 0000000..815c1b5 --- /dev/null +++ b/2025/utils/grid/lib.rs @@ -0,0 +1,798 @@ +use std::{ + fmt::{Debug, Display, Formatter, Write}, + io::{BufRead, Cursor}, + iter::repeat_n, + mem::swap, + ops::{Add, AddAssign, Sub}, + str::FromStr, +}; + +/// NW, N, NE, W, E, SW, S, SE +pub const ADJACENT_OFFSETS: [&(i64, i64); 8] = [ + &(-1, -1), + &(0, -1), + &(1, -1), + &(-1, 0), + &(1, 0), + &(-1, 1), + &(0, 1), + &(1, 1), +]; + +/// NESW +pub const CARDINAL_OFFSETS: [&(i64, i64); 4] = [&(0, -1), &(-1, 0), &(1, 0), &(0, 1)]; + +pub enum MirrorAxis { + X, + Y, +} + +#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] +pub struct Coord2d { + pub x: i64, + pub y: i64, +} + +impl Display for Coord2d { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("({}, {})", self.x, self.y)) + } +} + +impl FromStr for Coord2d { + type Err = Box; + fn from_str(s: &str) -> Result { + let (l, r) = s.split_once(',').ok_or("Can't split on ,")?; + Ok(Coord2d { + x: l.parse()?, + y: r.parse()?, + }) + } +} + +pub trait AsCoord2d { + fn to_coord(self) -> Coord2d; + fn x(&self) -> i64; + fn y(&self) -> i64; + + fn manhattan(&self, other: &T) -> u64 { + self.x().abs_diff(other.x()) + self.y().abs_diff(other.y()) + } +} + +impl Sub for &Coord2d { + type Output = Coord2d; + fn sub(self, rhs: T) -> Self::Output { + Coord2d { + x: self.x() - rhs.x(), + y: self.y() - rhs.y(), + } + } +} + +impl Add for &Coord2d +where + T: Copy, +{ + type Output = Coord2d; + fn add(self, rhs: T) -> Self::Output { + Coord2d { + x: self.x() + rhs.x(), + y: self.y() + rhs.y(), + } + } +} + +impl Add<&T> for Coord2d { + type Output = Coord2d; + fn add(self, rhs: &T) -> Self::Output { + Coord2d { + x: self.x() + rhs.x(), + y: self.y() + rhs.y(), + } + } +} + +impl AsCoord2d for Coord2d { + fn to_coord(self) -> Coord2d { + self + } + fn x(&self) -> i64 { + self.x + } + fn y(&self) -> i64 { + self.y + } +} + +impl AsCoord2d for &Coord2d { + fn to_coord(self) -> Coord2d { + self.to_owned() + } + fn x(&self) -> i64 { + self.x + } + fn y(&self) -> i64 { + self.y + } +} + +impl AsCoord2d for (T, T) +where + T: Copy + TryInto, + >::Error: Debug, +{ + fn to_coord(self) -> Coord2d { + Coord2d { + x: self.0.try_into().unwrap(), + y: self.1.try_into().unwrap(), + } + } + fn x(&self) -> i64 { + self.0.try_into().unwrap() + } + fn y(&self) -> i64 { + self.1.try_into().unwrap() + } +} + +impl AsCoord2d for &(T, T) +where + T: Copy + TryInto, + >::Error: Debug, +{ + fn to_coord(self) -> Coord2d { + Coord2d { + x: self.0.try_into().unwrap(), + y: self.1.try_into().unwrap(), + } + } + fn x(&self) -> i64 { + self.0.try_into().unwrap() + } + fn y(&self) -> i64 { + self.1.try_into().unwrap() + } +} + +impl From for (i64, i64) { + fn from(value: Coord2d) -> Self { + (value.x, value.y) + } +} + +#[derive(Debug)] +pub struct GridRowIter<'a, T> { + iter: std::slice::Iter<'a, T>, +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> GridRowIter<'a, T> { + fn new(grid: &'a Grid, y: i64) -> Self { + let iter = grid.data[y as usize * grid.width()..(y as usize + 1) * grid.width()].iter(); + Self { iter } + } +} + +impl<'a, T> Iterator for GridRowIter<'a, T> { + type Item = &'a T; + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } +} + +#[derive(Debug)] +pub struct CoordIter<'a, T> { + pos: usize, + grid: &'a Grid, +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for CoordIter<'a, T> { + type Item = Coord2d; + fn next(&mut self) -> Option { + if self.pos < self.grid.data.len() { + self.pos += 1; + self.grid.coord(self.pos as i64 - 1) + } else { + None + } + } +} + +#[derive(Debug)] +pub struct ItemIter<'a, T> { + pos: usize, + grid: &'a Grid, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Item<'a, T> { + pub pos: Coord2d, + pub value: &'a T, +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for ItemIter<'a, T> { + type Item = Item<'a, T>; + fn next(&mut self) -> Option { + if self.pos < self.grid.data.len() { + self.pos += 1; + Some(Item { + pos: self.grid.coord(self.pos as i64 - 1).unwrap(), + value: &self.grid.data[self.pos - 1], + }) + } else { + None + } + } +} + +#[derive(Debug)] +pub struct GridColIter<'a, T> { + grid: &'a Grid, + stride: usize, + cur: usize, +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> GridColIter<'a, T> { + fn new(grid: &'a Grid, x: i64) -> Self { + Self { + grid, + stride: grid.width(), + cur: x as usize, + } + } +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for GridColIter<'a, T> { + type Item = &'a T; + fn next(&mut self) -> Option { + let cur = self.cur; + self.cur += self.stride; + if cur < self.grid.data.len() { + Some(&self.grid.data[cur]) + } else { + None + } + } + fn size_hint(&self) -> (usize, Option) { + (self.grid.height() - 1, Some(self.grid.height() - 1)) + } +} + +#[derive(Debug)] +pub struct OffsetsIter<'a, T> { + grid: &'a Grid, + origin: Coord2d, + cur: usize, + offsets: &'a [&'a (i64, i64)], +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for OffsetsIter<'a, T> { + type Item = Item<'a, T>; + fn next(&mut self) -> Option { + while self.cur < self.offsets.len() { + let pos = self.origin + self.offsets[self.cur]; + self.cur += 1; + if let Some(value) = self.grid.get(&pos) { + return Some(Item { pos, value }); + } + } + None + } + fn size_hint(&self) -> (usize, Option) { + (0, Some(self.offsets.len() - self.cur)) + } +} + +#[derive(Clone, Eq, PartialEq, Debug, Hash)] +pub struct Grid { + pub data: Vec, + width: i64, +} + +impl Grid { + /// Returns a new [Grid] with the same shape (width x height) as `self`, filled with `fill` + pub fn same_shape(&self, fill: NT) -> Grid { + Grid::with_shape(self.width(), self.height(), fill) + } + /// Returns a new [Grid] with the given shape (width x height), filled with `fill` + pub fn with_shape(width: usize, height: usize, fill: T) -> Self { + Self { + data: Vec::from_iter(repeat_n(fill, width * height)), + width: width as i64, + } + } + pub fn width(&self) -> usize { + self.width as usize + } + pub fn height(&self) -> usize { + self.data.len() / self.width() + } + pub fn pos(&self, c: &C) -> i64 { + c.y() * self.width + c.x() + } + pub fn coord(&self, pos: i64) -> Option { + if pos < 0 || pos >= self.data.len() as i64 { + None + } else { + Some(Coord2d { + x: pos % self.width, + y: pos / self.width, + }) + } + } + pub fn coord_iter<'a>(&'a self) -> CoordIter<'a, T> { + CoordIter { pos: 0, grid: self } + } + pub fn item_iter<'a>(&'a self) -> ItemIter<'a, T> { + ItemIter { pos: 0, grid: self } + } + pub fn is_valid(&self, c: &C) -> bool { + if c.x() < 0 || c.x() >= self.width { + return false; + } + if c.y() < 0 || c.y() as usize >= self.height() { + return false; + } + true + } + fn valid_pos(&self, c: &C) -> Option { + if c.x() < 0 || c.x() >= self.width { + return None; + } + if c.y() < 0 || c.y() as usize >= self.height() { + return None; + } + let pos = self.pos(c); + if pos < 0 || pos as usize >= self.data.len() { + return None; + } + self.pos(c).try_into().ok() + } + pub fn get(&self, c: &C) -> Option<&T> { + match self.valid_pos(c) { + Some(pos) => Some(&self.data[pos]), + None => None, + } + } + pub fn get_mut(&mut self, c: &C) -> Option<&mut T> { + match self.valid_pos(c) { + Some(pos) => Some(self.data.get_mut(pos).unwrap()), + None => None, + } + } + pub fn set(&mut self, c: &C, mut val: T) -> Option { + match self.valid_pos(c) { + Some(pos) => { + swap(&mut self.data[pos], &mut val); + Some(val) + } + None => None, + } + } + pub fn increment<'a, A, C: AsCoord2d>(&'a mut self, c: &C, i: A) -> Option<&'a T> + where + T: AddAssign, + { + match self.valid_pos(c) { + Some(pos) => { + self.data[pos] += i; + Some(&self.data[pos]) + } + None => None, + } + } + pub fn row(&self, y: i64) -> Option<&[T]> { + if y < self.height() as i64 && y >= 0 { + Some(&self.data[self.pos(&(0, y)) as usize..self.pos(&(self.width, y)) as usize]) + } else { + None + } + } + + pub fn row_iter<'a>(&'a self, y: i64) -> Option> { + if (y as usize) < self.height() { + Some(GridRowIter::new(self, y)) + } else { + None + } + } + + pub fn col(&self, x: i64) -> Option> { + self.col_iter(x).map(|iter| iter.collect()) + } + + pub fn col_iter<'a>(&'a self, x: i64) -> Option> { + if (x as usize) < self.width() { + Some(GridColIter::new(self, x)) + } else { + None + } + } + + // Find the first instance of `needle` in self in storage order (row then col) + pub fn find(&self, needle: &T) -> Option { + self.coord( + self.data + .iter() + .enumerate() + .find_map(|(pos, val)| { + if val == needle { + Some(pos as i64) + } else { + None + } + }) + .unwrap_or(-1), + ) + } + /// Get all of the coordinates having value `needle` + pub fn find_all<'a>(&'a self, needle: &'a T) -> impl DoubleEndedIterator + 'a { + self.data + .iter() + .enumerate() + .filter_map(|(pos, val)| (*val == *needle).then_some(self.coord(pos as i64).unwrap())) + } + pub fn count(&self, haystack: &T) -> usize { + self.data.iter().filter(|item| *item == haystack).count() + } + + pub fn forward_slice(&self, start: &C, len: i64) -> Option<&[T]> { + let pos = ( + self.valid_pos(start), + self.valid_pos(&(start.x() + len - 1, start.y())), + ); + match pos { + (Some(pos1), Some(pos2)) => Some(&self.data[pos1..pos2 + 1]), + _ => None, + } + } + + pub fn swap(&mut self, a: A, b: B) { + if let (Some(a), Some(b)) = (self.valid_pos(&a), self.valid_pos(&b)) { + self.data.swap(a, b) + } + } + + /// Return the count of neighbours (8 directions) matching predicate p + pub fn adjacent_count(&self, c: &C, mut p: P) -> usize + where + P: FnMut(&T) -> bool, + { + self.adjacent_iter(c).filter(|i| p(i.value)).count() + } + + /// Return the count of cardinal neighbours (4 directions) matching predicate p + pub fn cardinal_count(&self, c: &C, mut p: P) -> usize + where + P: FnMut(&T) -> bool, + { + self.cardinal_iter(c).filter(|i| p(i.value)).count() + } + + /// Return an iterator over the 8 neighbours of c. The iterator skips neighbouring positions outside of the grid. + pub fn adjacent_iter<'a, C: AsCoord2d + Copy>(&'a self, c: &'a C) -> OffsetsIter<'a, T> { + OffsetsIter { + grid: self, + origin: c.to_coord(), + cur: 0, + offsets: &ADJACENT_OFFSETS, + } + } + + /// Return an iterator over the 4 cardinal neighbours of c. The iterator skips neighbouring positions outside of the grid. + pub fn cardinal_iter<'a, C: AsCoord2d + Copy>(&'a self, c: &'a C) -> OffsetsIter<'a, T> { + OffsetsIter { + grid: self, + origin: c.to_coord(), + cur: 0, + offsets: &CARDINAL_OFFSETS, + } + } + + pub fn rotated(&self, mut rot: u8) -> Self { + rot %= 4; + match rot { + 0 => self.clone(), + 1 => { + let mut n = Grid::with_shape(self.height(), self.width(), self.data[0].clone()); // fill will be overwritten anyway + for y in 0..self.height() { + for x in 0..self.width() { + n.set( + &(self.height() - y - 1, x), + self.get(&(x as u64, y as u64)).unwrap().clone(), + ); + } + } + n + } + 2 => { + let mut n = Grid::with_shape(self.height(), self.width(), self.data[0].clone()); // fill will be overwritten anyway + for y in 0..self.height() { + for x in 0..self.width() { + n.set( + &(self.width() - x - 1, self.height() - y - 1), + self.get(&(x as u64, y as u64)).unwrap().clone(), + ); + } + } + n + } + 3 => { + let mut n = Grid::with_shape(self.height(), self.width(), self.data[0].clone()); // fill will be overwritten anyway + for y in 0..self.height() { + for x in 0..self.width() { + n.set( + &(self.height() - y - 1, self.width() - x - 1), + self.get(&(x as u64, y as u64)).unwrap().clone(), + ); + } + } + n + } + _ => unreachable!("invalid rotation"), + } + } + + pub fn mirrored(&self, axis: MirrorAxis) -> Self { + match axis { + MirrorAxis::X => { + let mut n = Grid::with_shape(self.height(), self.width(), self.data[0].clone()); // fill will be overwritten anyway + for y in 0..self.height() { + for x in 0..self.width() { + n.set( + &(self.width() - x - 1, y), + self.get(&(x as u64, y as u64)).unwrap().clone(), + ); + } + } + n + } + MirrorAxis::Y => { + let mut n = Grid::with_shape(self.height(), self.width(), self.data[0].clone()); // fill will be overwritten anyway + for y in 0..self.height() { + for x in 0..self.width() { + n.set( + &(x, &self.height() - y - 1), + self.get(&(x as u64, y as u64)).unwrap().clone(), + ); + } + } + n + } + } + } + + // fn window_compare_impl(&self, needle: &[T]) -> Vec<(i64, i64)> { + // if (self.width as usize) < needle.len() { + // return Vec::new(); + // } + // let mut res = Vec::new(); + // for y in 0..self.height() as i64 { + // let mut windows_tmp = self.row(y).unwrap().windows(needle.len()); + // let windows = if REV { + // windows_tmp.rev() + // } else { + // windows_tmp + // }; + + // res.extend( + // windows + // .enumerate() + // .filter_map(|(x, w)| if w == needle { Some((x as i64, y)) } else { None }), + // ); + // } + // res + // } +} + +impl From for Grid { + fn from(input: T) -> Grid { + let mut data = Vec::new(); + let mut width = 0; + for line in input.split(b'\n').map(|i| i.unwrap()) { + if width == 0 { + width = line.len() as i64 + } else if line.len() as i64 != width { + panic!("Grids must have fixed length rows") + } + data.extend_from_slice(&line); + } + Grid { data, width } + } +} + +// Should be Grid? +impl FromStr for Grid { + type Err = Box; + fn from_str(s: &str) -> Result { + Ok(Cursor::new(s).into()) + } +} + +// impl> Display for Grid { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// for y in 0..self.height() { +// for x in 0..self.width() { +// f.write_fmt(format_args!("{}",self.get(x as i64, y as i64).unwrap() as char))?; +// } +// f.write_char('\n')?; +// } +// f.write_char('\n') +// } +// } + +impl Display for Grid { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + for y in 0..self.height() { + for x in 0..self.width() { + f.write_fmt(format_args!( + "{}", + *self.get(&(x as i64, y as i64)).unwrap() as char + ))?; + } + f.write_char('\n')?; + } + f.write_char('\n') + } +} + +impl Display for Grid { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + for y in 0..self.height() { + for x in 0..self.width() { + f.write_fmt(format_args!( + "{}", + match *self.get(&(x as i64, y as i64)).unwrap() { + true => '.', + false => '#', + } + ))?; + } + f.write_char('\n')?; + } + f.write_char('\n') + } +} + +#[cfg(test)] +mod tests { + use super::*; + + static TEST_VECTOR: &[u8] = b"ABCD +EFGH +IJKL +FBCG"; + + static TEST_VECTOR_S: &str = "ABCD +EFGH +IJKL +FBCG"; + + fn unchecked_load() -> Grid { + Grid::from(TEST_VECTOR) + } + + #[test] + fn from_string() { + let grid = unchecked_load(); + assert_eq!(grid.data, "ABCDEFGHIJKLFBCG".as_bytes()); + assert_eq!( + TEST_VECTOR_S.parse::>().unwrap().data, + "ABCDEFGHIJKLFBCG".as_bytes() + ); + } + + #[test] + fn indexing() { + let grid = unchecked_load(); + assert_eq!(grid.get(&(0, 0)), Some(b'A').as_ref()); + assert_eq!(grid.get(&(3, 3)), Some(b'G').as_ref()); + assert_eq!(grid.get(&(-1, 0)), None); + assert_eq!(grid.get(&(0, -1)), None); + assert_eq!(grid.get(&(5, 0)), None); + assert_eq!(grid.get(&(0, 5)), None); + } + + #[test] + fn forward_slice() { + let grid = unchecked_load(); + assert_eq!(grid.forward_slice(&(0, 0), 2), Some(b"AB".as_slice())); + assert_eq!(grid.forward_slice(&(2, 0), 2), Some(b"CD".as_slice())); + assert_eq!(grid.forward_slice(&(2, 0), 3), None); + assert_eq!(grid.forward_slice(&(0, 2), 4), Some(b"IJKL".as_slice())); + } + + #[test] + fn row_iter() { + let grid = unchecked_load(); + assert_eq!( + grid.row_iter(2).unwrap().collect::>(), + [&b'I', &b'J', &b'K', &b'L'] + ); + assert!(grid.row_iter(-1).is_none()); + assert!(grid.row_iter(4).is_none()); + } + + #[test] + fn col_iter() { + let grid = unchecked_load(); + assert_eq!( + grid.col_iter(2).unwrap().collect::>(), + [&b'C', &b'G', &b'K', &b'C'] + ); + assert!(grid.col_iter(-1).is_none()); + assert!(grid.col_iter(4).is_none()); + } + + #[test] + fn find_all() { + let grid = unchecked_load(); + assert_eq!( + grid.find_all(&b'G').collect::>(), + [Coord2d { x: 2, y: 1 }, Coord2d { x: 3, y: 3 }] + ) + } + + #[test] + fn neighbours_iter() { + let grid = unchecked_load(); + assert_eq!( + grid.adjacent_iter(&(0, 1)).collect::>(), + [ + Item { + pos: Coord2d { x: 0, y: 0 }, + value: &b'A' + }, + Item { + pos: Coord2d { x: 1, y: 0 }, + value: &b'B' + }, + Item { + pos: Coord2d { x: 1, y: 1 }, + value: &b'F' + }, + Item { + pos: Coord2d { x: 0, y: 2 }, + value: &b'I' + }, + Item { + pos: Coord2d { x: 1, y: 2 }, + value: &b'J' + }, + ] + ) + } + + #[test] + fn cardinal_iter() { + let grid = unchecked_load(); + assert_eq!( + grid.cardinal_iter(&(0, 1)).collect::>(), + [ + Item { + pos: Coord2d { x: 0, y: 0 }, + value: &b'A' + }, + Item { + pos: Coord2d { x: 1, y: 1 }, + value: &b'F' + }, + Item { + pos: Coord2d { x: 0, y: 2 }, + value: &b'I' + } + ] + ) + } + + // #[test] + // fn window_compare() { + // let grid = unchecked_load(); + // assert_eq!(grid.window_compare(b"IJKL"), &[(0, 2)]); + // assert_eq!(grid.window_compare(b"BC"), &[(1, 0), (1, 3)]); + // assert_eq!(grid.window_compare(b"LF").len(), 0); + // } +} diff --git a/2025/utils/misc/Cargo.lock b/2025/utils/misc/Cargo.lock new file mode 100644 index 0000000..6dfd16a --- /dev/null +++ b/2025/utils/misc/Cargo.lock @@ -0,0 +1,44 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" + +[[package]] +name = "intrusive-collections" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" +dependencies = [ + "memoffset", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "misc" +version = "0.1.0" +dependencies = [ + "intrusive-collections", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] diff --git a/2025/utils/misc/Cargo.toml b/2025/utils/misc/Cargo.toml new file mode 100644 index 0000000..cf51035 --- /dev/null +++ b/2025/utils/misc/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "misc" +version = "0.1.0" +edition = "2024" + +[dependencies] +intrusive-collections = "0.9.7" +num-traits = "0.2.19" diff --git a/2025/utils/misc/src/lib.rs b/2025/utils/misc/src/lib.rs new file mode 100644 index 0000000..97836e2 --- /dev/null +++ b/2025/utils/misc/src/lib.rs @@ -0,0 +1,115 @@ +use num_traits::Signed; +use std::fmt::Display; +use std::ops::{Add, AddAssign}; + +pub mod range; + +const POW10MAX: usize = u64::MAX.ilog10() as usize; +pub const POW10: [u64; POW10MAX] = pow10_lut(); + +const fn pow10_lut() -> [u64; N] { + let mut res = [0; N]; + let mut i = 0; + while i < N { + res[i] = 10u64.pow(i as u32); + i += 1; + } + res +} + +/// Wrapped signed integer with custom upper bound with wrapping of 0s to the upper bound +#[derive(Eq, Clone, Copy)] +pub struct CustomWrapped { + pub val: T, + pub bound: T, +} + +impl Add for CustomWrapped { + type Output = CustomWrapped; + fn add(self, rhs: T) -> Self::Output { + Self { + val: ((self.val + rhs % self.bound) + self.bound) % self.bound, + bound: self.bound, + } + } +} + +impl Add for &CustomWrapped { + type Output = CustomWrapped; + fn add(self, rhs: T) -> Self::Output { + CustomWrapped { + val: ((self.val + rhs % self.bound) + self.bound) % self.bound, + bound: self.bound, + } + } +} + +impl AddAssign for CustomWrapped { + fn add_assign(&mut self, rhs: T) { + self.val = ((self.val + rhs % self.bound) + self.bound) % self.bound + } +} + +impl CustomWrapped { + pub fn new(val: T, bound: T) -> Self { + Self { val, bound } + } +} + +impl PartialEq for CustomWrapped { + fn eq(&self, other: &Self) -> bool { + self.val.eq(&other.val) + } +} + +impl PartialOrd for CustomWrapped { + fn partial_cmp(&self, other: &Self) -> Option { + self.val.partial_cmp(&other.val) + } +} + +impl Ord for CustomWrapped { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.val.cmp(&other.val) + } +} + +impl PartialEq for CustomWrapped { + fn eq(&self, other: &T) -> bool { + self.val == *other + } +} + +impl PartialOrd for CustomWrapped { + fn partial_cmp(&self, other: &T) -> Option { + self.val.partial_cmp(other) + } +} + +impl Display for CustomWrapped +where + T: Display, +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.val.fmt(f) + } +} + +// impl Into for CustomWrapped { +// fn into(self) -> T { +// self.val +// } +// } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_pow10() { + #[allow(clippy::needless_range_loop)] + for i in 0..POW10MAX { + assert_eq!(POW10[i], 10u64.pow(i as u32)) + } + } +} diff --git a/2025/utils/misc/src/range.rs b/2025/utils/misc/src/range.rs new file mode 100644 index 0000000..b2d44f8 --- /dev/null +++ b/2025/utils/misc/src/range.rs @@ -0,0 +1,124 @@ +use intrusive_collections::Bound as IBound; +use intrusive_collections::{KeyAdapter, intrusive_adapter}; +use intrusive_collections::{RBTreeLink, rbtree::RBTree}; +use std::cmp::{max, min}; +use std::ops::{Add, Bound, RangeBounds, Sub}; + +#[derive(Debug)] +pub struct NaiveRange { + link: RBTreeLink, + pub start: T, + pub end: T, +} + +intrusive_adapter!( + pub NaiveRangeAdapter = Box>: NaiveRange { link: RBTreeLink } +); + +impl<'a, T: Ord + Clone> KeyAdapter<'a> for NaiveRangeAdapter { + type Key = T; + fn get_key(&self, node: &'a NaiveRange) -> T { + node.start.clone() + } +} + +impl NaiveRange { + fn new(start: T, end: T) -> Self { + Self { + link: RBTreeLink::new(), + start, + end, + } + } +} + +pub struct RangeSet { + pub store: RBTree>, +} + +fn normalize_range, T: Copy + Ord + Add + From>( + r: &R, +) -> NaiveRange { + let start = match r.start_bound() { + Bound::Included(x) => *x, + Bound::Excluded(x) => *x + T::from(1), + Bound::Unbounded => panic!(), + }; + let end = match r.end_bound() { + Bound::Included(x) => *x + T::from(1), + Bound::Excluded(x) => *x, + Bound::Unbounded => panic!(), + }; + + NaiveRange::new(start, end) +} + +impl + Sub + From> Default for RangeSet { + fn default() -> Self { + Self::new() + } +} + +impl + Sub + From> RangeSet { + pub fn new() -> Self { + Self { + store: RBTree::new(NaiveRangeAdapter::::new()), + } + } + pub fn add>(&mut self, r: &R) { + //normalize r to Range + let mut new_r = normalize_range(r); + + // Find the position of nearest entry >= and <= than new_r's start + let mut cur = self.store.lower_bound_mut(IBound::Included(&new_r.start)); + + while let Some(val) = cur.get() + && new_r.end >= val.start + { + // then remove them and update our new range + new_r.start = min(new_r.start, val.start); + new_r.end = max(new_r.end, val.end); + cur.remove(); // moves the cursor ahead + } + + // Move the cursor back one (this will be the element before our insertion point, 'below' start) + cur.move_prev(); + while let Some(val) = cur.get() + && new_r.start <= val.end + { + new_r.start = min(new_r.start, val.start); + new_r.end = max(new_r.end, val.end); + cur.remove(); + cur.move_prev(); + } + + // We are already in position, we just checked the previous element and it's before us + // since we fell out of the loop, so we need to go after this position + cur.insert_after(Box::new(new_r)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ranges() { + let mut set = RangeSet::new(); + // edge cases are tricky to construct, run the aoc2025 day 5 puzzle and compare :) + set.add(&(0..10)); + set.add(&(100..1000)); + set.add(&(50..100)); + set.add(&(50..100)); + set.add(&(1001..2000)); + set.add(&(2000..2001)); + set.add(&(-10..-2)); + set.add(&(-1..-1)); + let end = set + .store + .iter() + .map(|r| (r.start, r.end)) + .collect::>(); + assert_eq!(end, [(-10, 10), (50, 2001)]) + } +}