From 5587b3c0f4fc38bf4054285563feabc8d519d815 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Sun, 30 Nov 2025 22:48:56 -0800 Subject: [PATCH 01/66] repo setup for 2025 --- .gitignore | 7 + Cargo.lock | 725 ++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 27 ++ src/lib.rs | 5 + src/main.rs | 3 + utils/grid/Cargo.lock | 7 + utils/grid/Cargo.toml | 9 + utils/grid/lib.rs | 512 +++++++++++++++++++++++++++++ utils/misc/Cargo.lock | 25 ++ utils/misc/Cargo.toml | 7 + utils/misc/src/lib.rs | 98 ++++++ 11 files changed, 1425 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 utils/grid/Cargo.lock create mode 100644 utils/grid/Cargo.toml create mode 100644 utils/grid/lib.rs create mode 100644 utils/misc/Cargo.lock create mode 100644 utils/misc/Cargo.toml create mode 100644 utils/misc/src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2ad0769 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +**/target +input +flamegraph.svg +perf.data* +guesses +.aoc_tiles/* +!.aoc_tiles/tiles/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..e0b5f84 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,725 @@ +# 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", + "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", + "atoi", + "bitflags", + "cached", + "colored", + "grid", + "indicatif", + "itertools", + "lazy_static", + "misc", + "nom", + "rayon", + "regex", + "rustc-hash", + "thread_local", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[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 = "cached" +version = "0.54.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9718806c4a2fe9e8a56fd736f97b340dd10ed1be8ed733ed50449f351dc33cae" +dependencies = [ + "ahash", + "cached_proc_macro", + "cached_proc_macro_types", + "hashbrown", + "once_cell", + "thiserror", + "web-time", +] + +[[package]] +name = "cached_proc_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f42a145ed2d10dce2191e1dcf30cfccfea9026660e143662ba5eec4017d5daa" +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 = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "colored" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" +dependencies = [ + "lazy_static", + "windows-sys", +] + +[[package]] +name = "console" +version = "0.15.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" +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 = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "grid" +version = "0.1.0" + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", + "allocator-api2", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "indicatif" +version = "0.17.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235" +dependencies = [ + "console", + "number_prefix", + "portable-atomic", + "rayon", + "unicode-width", + "web-time", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[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.177" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" + +[[package]] +name = "memchr" +version = "2.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "misc" +version = "0.1.0" +dependencies = [ + "num-traits", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "number_prefix" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "portable-atomic" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" + +[[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 = "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 = "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 = "rustc-hash" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + +[[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 = "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 = "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 = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.111", +] + +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + +[[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 = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +dependencies = [ + "cfg-if", + "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 = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[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/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..81b2198 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "aoc2025" +edition = "2021" +version = "0.1.0" + +[dependencies] +aoc-runner = "0.3.0" +aoc-runner-derive = "0.3.0" +atoi = "2.0.0" +bitflags = "2.6.0" +cached = "0.54.0" +colored = "2.1.0" +grid = {version = "0.1.0", path = "utils/grid"} +indicatif = { version = "0.17.9", features = ["rayon"] } +itertools = "0.13.0" +lazy_static = "1.5.0" +misc = {path = "utils/misc"} +nom = "7.1.3" +rayon = "1.10.0" +regex = "1.11.1" +rustc-hash = "2.1.0" +thread_local = "1.1.8" + +[profile.release] +lto = true +opt-level = 3 +overflow-checks = false diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..5645c2a --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,5 @@ +pub mod day1; + +use aoc_runner_derive::aoc_lib; + +aoc_lib! { year = 2025 } diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..4207064 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,3 @@ +use aoc_runner_derive::aoc_main; + +aoc_main! { lib = aoc2025 } diff --git a/utils/grid/Cargo.lock b/utils/grid/Cargo.lock new file mode 100644 index 0000000..1c1a197 --- /dev/null +++ b/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/utils/grid/Cargo.toml b/utils/grid/Cargo.toml new file mode 100644 index 0000000..6507dcf --- /dev/null +++ b/utils/grid/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "grid" +version = "0.1.0" +edition = "2021" + +[dependencies] + +[lib] +path = "lib.rs" diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs new file mode 100644 index 0000000..ba73c4f --- /dev/null +++ b/utils/grid/lib.rs @@ -0,0 +1,512 @@ +use std::{ + fmt::{Debug, Display, Formatter, Write}, + io::{BufRead, Cursor}, + iter::repeat_n, + mem::swap, + ops::{Add, AddAssign, Sub}, + str::FromStr, +}; + +#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct Coord2d { + pub x: i64, + pub y: i64, +} + +pub trait AsCoord2d { + fn to_coord(self) -> Coord2d; + fn x(&self) -> i64; + fn y(&self) -> i64; +} + +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 { + 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.grid.coord(self.pos as i64).into() + } 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(Clone, Eq, PartialEq, Debug)] +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(&self) -> CoordIter<_> { + // CoordIter { 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; + } + return 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(&self, y: i64) -> Option> { + if (y as usize) < self.height() { + Some(GridRowIter::new(self, y)) + } else { + None + } + } + + pub fn col(&self, x: i64) -> Option> { + if let Some(iter) = self.col_iter(x) { + Some(iter.collect()) + } else { + None + } + } + + pub fn col_iter(&self, x: i64) -> Option> { + if (x as usize) < self.width() { + Some(GridColIter::new(self, x)) + } else { + None + } + } + + pub fn find(&self, haystack: &T) -> Option { + self.coord( + self.data + .iter() + .enumerate() + .find_map(|(pos, val)| if val == haystack { Some(pos as i64) } else { None }) + .unwrap_or(-1), + ) + } + 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) + } + } + + // 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 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/utils/misc/Cargo.lock b/utils/misc/Cargo.lock new file mode 100644 index 0000000..f6716d7 --- /dev/null +++ b/utils/misc/Cargo.lock @@ -0,0 +1,25 @@ +# 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 = "misc" +version = "0.1.0" +dependencies = [ + "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/utils/misc/Cargo.toml b/utils/misc/Cargo.toml new file mode 100644 index 0000000..3704ff9 --- /dev/null +++ b/utils/misc/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "misc" +version = "0.1.0" +edition = "2021" + +[dependencies] +num-traits = "0.2.19" diff --git a/utils/misc/src/lib.rs b/utils/misc/src/lib.rs new file mode 100644 index 0000000..b7d4b5c --- /dev/null +++ b/utils/misc/src/lib.rs @@ -0,0 +1,98 @@ +use num_traits::Signed; +use std::fmt::Display; +use std::ops::{Add, AddAssign}; + +/// 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 it_works() { + let result = add(2, 2); + assert_eq!(result, 4); + } +} From 485559e81a07a8ac89d4b2917a258e058f2f9b36 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Sun, 30 Nov 2025 22:49:27 -0800 Subject: [PATCH 02/66] day1: both solutions --- src/day1.rs | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 src/day1.rs diff --git a/src/day1.rs b/src/day1.rs new file mode 100644 index 0000000..3ea16c7 --- /dev/null +++ b/src/day1.rs @@ -0,0 +1,100 @@ +use aoc_runner_derive::aoc; +use std::io::{BufRead, BufReader, Lines}; +use std::time::{Duration, Instant}; + +// 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); + } +} From a70e8bc299b14960eb629f2f0d26d7c97b45894c Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 1 Dec 2025 21:31:31 -0800 Subject: [PATCH 03/66] edition 2024 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 81b2198..9609600 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "aoc2025" -edition = "2021" +edition = "2024" version = "0.1.0" [dependencies] From d50d702a2151cf51dc12d3f3383ac527189558c7 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 1 Dec 2025 21:31:49 -0800 Subject: [PATCH 04/66] day2: both solutions first attempt --- src/day2.rs | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 2 files changed, 75 insertions(+) create mode 100644 src/day2.rs diff --git a/src/day2.rs b/src/day2.rs new file mode 100644 index 0000000..916f5ab --- /dev/null +++ b/src/day2.rs @@ -0,0 +1,74 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use itertools::Itertools; +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() % 2 != 0 { + 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() % n != 0 { + continue; + } + if prod_s + .chars() + .chunks(n) + .into_iter() + .map(|c| c.collect::()) + .all_equal() + { + invalid_sum += product; + break; + } + } + } + } + invalid_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); + } +} diff --git a/src/lib.rs b/src/lib.rs index 5645c2a..ce5ab10 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +mod day2; pub mod day1; use aoc_runner_derive::aoc_lib; From 5e672d6765c595837050c24d5949f90b876697c0 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 1 Dec 2025 22:33:55 -0800 Subject: [PATCH 05/66] day2: bruteforce without string conversion --- src/day2.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/src/day2.rs b/src/day2.rs index 916f5ab..04b3447 100644 --- a/src/day2.rs +++ b/src/day2.rs @@ -1,5 +1,6 @@ use aoc_runner_derive::{aoc, aoc_generator}; use itertools::Itertools; +use std::cmp::{max, min}; use std::ops::RangeInclusive; #[aoc_generator(day2)] @@ -56,6 +57,52 @@ fn part2(input: &[RangeInclusive]) -> u64 { 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; + if n_digits % 2 != 0 { + continue; + } + + let decade = 10u64.pow(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; + + for n in 1..=n_digits / 2 { + if n_digits % n != 0 { + continue; + } + let decade = 10u64.pow(n); + let lhs = product / decade; + let rhs = product % decade; + if lhs == rhs { + invalid_sum += product + } + } + } + } + invalid_sum +} + #[cfg(test)] mod tests { use super::*; @@ -71,4 +118,13 @@ mod tests { 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)), 1227775554); + } } From 713cca69095e4944e6039873520acb9429eef811 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 1 Dec 2025 23:00:55 -0800 Subject: [PATCH 06/66] day2: add mostly arithmetic solution for part1 --- src/day2.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/day2.rs b/src/day2.rs index 04b3447..c3d0508 100644 --- a/src/day2.rs +++ b/src/day2.rs @@ -103,6 +103,36 @@ fn part2_arithmetic_brute(input: &[RangeInclusive]) -> u64 { 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; + + let mut lhs = if n_digits % 2 != 0 { + // If the number of digits is odd, we start our guess at the first possibility in the next decade + 10u64.pow(n_digits / 2) + } else { + let start_decade = 10u64.pow(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 * 10u64.pow(lhs.ilog10() + 1) + lhs; + if repeater < *r.start() { + lhs += 1 + } else if r.contains(&repeater) { + invalid_sum += repeater; + lhs += 1 + } else { + break; + } + } + } + invalid_sum +} + #[cfg(test)] mod tests { use super::*; @@ -127,4 +157,8 @@ mod tests { fn part2_arithmetic_example() { assert_eq!(part2_arithmetic_brute(&parse(EXAMPLE)), 1227775554); } + #[test] + fn part1_clever_example() { + assert_eq!(part1_clever(&parse(EXAMPLE)), 1227775554); + } } From 8dd7831caa080fd3c98140325efa1f85f30a11fc Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 2 Dec 2025 12:55:05 -0800 Subject: [PATCH 07/66] day2: fix arithmetic bruteforce algorithm & test --- src/day2.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/day2.rs b/src/day2.rs index c3d0508..b3510d7 100644 --- a/src/day2.rs +++ b/src/day2.rs @@ -88,14 +88,22 @@ fn part2_arithmetic_brute(input: &[RangeInclusive]) -> u64 { let n_digits = product.ilog10() + 1; for n in 1..=n_digits / 2 { + let repetitions = n_digits / n; if n_digits % n != 0 { continue; } - let decade = 10u64.pow(n); + let decade = 10u64.pow(n_digits - n); let lhs = product / decade; - let rhs = product % decade; - if lhs == rhs { - invalid_sum += product + let remainder = product % decade; + + // for each repetition we multiply by 10^(rep * n) + let expected_remainder = (0..repetitions - 1) + .map(|rep| lhs * 10u64.pow(rep * n)) + .sum(); + + if remainder == expected_remainder { + invalid_sum += product; + break; } } } @@ -155,7 +163,7 @@ mod tests { } #[test] fn part2_arithmetic_example() { - assert_eq!(part2_arithmetic_brute(&parse(EXAMPLE)), 1227775554); + assert_eq!(part2_arithmetic_brute(&parse(EXAMPLE)), 4174379265); } #[test] fn part1_clever_example() { From d229bb78892d92d92c275b9823edd50f8020422e Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 2 Dec 2025 13:07:30 -0800 Subject: [PATCH 08/66] add pre-commit --- .pre-commit-config.yaml | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..c354440 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,30 @@ +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 -- -D warnings + pass_filenames: false + types: [file, rust] + language: system + - repo: https://github.com/LiquidFun/aoc_tiles + rev: 0.6.4 + hooks: + - id: aoc-tiles + # 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 + # - --language-sorting=jl,kt,py,rs + # - --exclude-patterns=2021/*/*.apl,2021/*/*.py,2021/*/*.cpp From 0f2024c474a7acc9236ba1cf8da563b06d9f2a87 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 2 Dec 2025 13:07:37 -0800 Subject: [PATCH 09/66] clippies --- src/day1.rs | 8 +++----- src/day2.rs | 1 - src/lib.rs | 2 +- utils/grid/lib.rs | 18 +++++++++++++++--- 4 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/day1.rs b/src/day1.rs index 3ea16c7..f82dcfc 100644 --- a/src/day1.rs +++ b/src/day1.rs @@ -1,6 +1,4 @@ use aoc_runner_derive::aoc; -use std::io::{BufRead, BufReader, Lines}; -use std::time::{Duration, Instant}; // PROBLEM 1 solution #[aoc(day1, part1)] @@ -16,7 +14,7 @@ pub fn part1(input: &str) -> u64 { 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), + c => panic!("Invalid direction {c}"), }; val = (val + add_val) % mod_val; if val == 0 { @@ -65,7 +63,7 @@ pub fn part2(input: &str) -> i64 { 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), + c => panic!("Invalid direction {c}"), }; val = new_val; pass += add_pass; @@ -77,7 +75,7 @@ pub fn part2(input: &str) -> i64 { mod tests { use crate::day1::*; - const EXAMPLE: &str = &"L68 + const EXAMPLE: &str = "L68 L30 R48 L5 diff --git a/src/day2.rs b/src/day2.rs index b3510d7..75ce09f 100644 --- a/src/day2.rs +++ b/src/day2.rs @@ -1,6 +1,5 @@ use aoc_runner_derive::{aoc, aoc_generator}; use itertools::Itertools; -use std::cmp::{max, min}; use std::ops::RangeInclusive; #[aoc_generator(day2)] diff --git a/src/lib.rs b/src/lib.rs index ce5ab10..a228b5c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,5 @@ +mod day1; mod day2; -pub mod day1; use aoc_runner_derive::aoc_lib; diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs index ba73c4f..67f810c 100644 --- a/utils/grid/lib.rs +++ b/utils/grid/lib.rs @@ -321,7 +321,13 @@ impl Grid { self.data .iter() .enumerate() - .find_map(|(pos, val)| if val == haystack { Some(pos as i64) } else { None }) + .find_map(|(pos, val)| { + if val == haystack { + Some(pos as i64) + } else { + None + } + }) .unwrap_or(-1), ) } @@ -330,7 +336,10 @@ impl Grid { } 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()))); + 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, @@ -406,7 +415,10 @@ 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_fmt(format_args!( + "{}", + *self.get(&(x as i64, y as i64)).unwrap() as char + ))?; } f.write_char('\n')?; } From 4c1a7bf0be9c0eba3af60ee5349957a46b7c2e7a Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 2 Dec 2025 13:12:50 -0800 Subject: [PATCH 10/66] add readme --- .aoc_tiles/tiles/2025/01.png | Bin 0 -> 6725 bytes .aoc_tiles/tiles/2025/02.png | Bin 0 -> 7369 bytes README.md | 11 +++++++++++ 3 files changed, 11 insertions(+) create mode 100644 .aoc_tiles/tiles/2025/01.png create mode 100644 .aoc_tiles/tiles/2025/02.png create mode 100644 README.md diff --git a/.aoc_tiles/tiles/2025/01.png b/.aoc_tiles/tiles/2025/01.png new file mode 100644 index 0000000000000000000000000000000000000000..ec38deb523daf8129f85f08bd6da0ed2705c4c05 GIT binary patch literal 6725 zcmV-L8oK3)P)1S#I6?pwAj-={3ciR0L5oY+azBu(37o9%9!X7(YoGyAYJo$15Q&a}I; z4?D9DO^?}bo1<-xwz=!Xc6`Kk9N(5L+p=VxmPAp!Pmll!U>_huAV`7$b&}HWiTLmb ze)#_Q@xyojp`kzi3=|8JB#XY5Acz&-GUkOBg>|`kc^UE+DXbFB?F#RL@fIVj(#`D( z?}G87;?&B$-z93=#3>xhFl3Ytdt)Ov$+13;WlB1?E4&NFi^|vm03aAa4QA9}CTdsF zAaDeVo|9a{rc*4PphDi1-xV9~NyUQMx5bP$ z+x7#xs%8K{xc5Tf+86S?s<1@-oL^WR$1!OLK>-Bu3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<7pR(V_dgm>k98czK3Z&#jGgeSb^$GgPO`--s&@r1W5 vd6)QkUoqA!p753{FS;tMJf85DG4Fo^N34M|;fhhW00000NkvXXu0mjfb^D<8 literal 0 HcmV?d00001 diff --git a/README.md b/README.md new file mode 100644 index 0000000..807be67 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ + +

+ 2025 - 4 ⭐ - Rust +

+
+ + + + + + From fb24991102926d3af0c6df55751c1f8d741042ae Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 2 Dec 2025 13:38:24 -0800 Subject: [PATCH 11/66] day2: Use a LUT for pow10 operations for 50% performance improvement --- src/day2.rs | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/src/day2.rs b/src/day2.rs index 75ce09f..d5629c6 100644 --- a/src/day2.rs +++ b/src/day2.rs @@ -2,6 +2,19 @@ use aoc_runner_derive::{aoc, aoc_generator}; use itertools::Itertools; use std::ops::RangeInclusive; +const POW10MAX: usize = u64::MAX.ilog10() as usize; +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 +} + #[aoc_generator(day2)] fn parse(input: &str) -> Vec> { input @@ -62,12 +75,12 @@ fn part1_arithmetic_brute(input: &[RangeInclusive]) -> u64 { for r in input { // println!("Range: {:?}", r); for product in r.clone() { - let n_digits = product.ilog10() + 1; + let n_digits = (product.ilog10() + 1) as usize; if n_digits % 2 != 0 { continue; } - let decade = 10u64.pow(n_digits / 2); + let decade = POW10[n_digits / 2]; let lhs = product / decade; let rhs = product % decade; // println!("{product} {n_digits}: D:{decade} L:{lhs} R:{rhs}"); @@ -84,21 +97,19 @@ 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; + let n_digits = (product.ilog10() + 1) as usize; for n in 1..=n_digits / 2 { let repetitions = n_digits / n; if n_digits % n != 0 { continue; } - let decade = 10u64.pow(n_digits - n); + let decade = POW10[n_digits - n]; let lhs = product / decade; let remainder = product % decade; // for each repetition we multiply by 10^(rep * n) - let expected_remainder = (0..repetitions - 1) - .map(|rep| lhs * 10u64.pow(rep * n)) - .sum(); + let expected_remainder = (0..repetitions - 1).map(|rep| lhs * POW10[rep * n]).sum(); if remainder == expected_remainder { invalid_sum += product; @@ -114,19 +125,19 @@ fn part2_arithmetic_brute(input: &[RangeInclusive]) -> u64 { fn part1_clever(input: &[RangeInclusive]) -> u64 { let mut invalid_sum = 0; for r in input { - let n_digits = r.start().ilog10() + 1; + let n_digits = (r.start().ilog10() + 1) as usize; let mut lhs = if n_digits % 2 != 0 { // If the number of digits is odd, we start our guess at the first possibility in the next decade - 10u64.pow(n_digits / 2) + POW10[n_digits / 2] } else { - let start_decade = 10u64.pow(n_digits / 2); + 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 * 10u64.pow(lhs.ilog10() + 1) + lhs; + let repeater = lhs * POW10[(lhs.ilog10() + 1) as usize] + lhs; if repeater < *r.start() { lhs += 1 } else if r.contains(&repeater) { From 0ea40260c118ea2cd0373078248c61a5417e1cf7 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 2 Dec 2025 21:13:17 -0800 Subject: [PATCH 12/66] day3: part 1 --- src/day3.rs | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 2 files changed, 55 insertions(+) create mode 100644 src/day3.rs diff --git a/src/day3.rs b/src/day3.rs new file mode 100644 index 0000000..f3a8c64 --- /dev/null +++ b/src/day3.rs @@ -0,0 +1,54 @@ +use aoc_runner_derive::{aoc, aoc_generator}; + +type Bank = Vec; + +#[aoc_generator(day3)] +fn parse(input: &str) -> Vec { + input + .lines() + .map(|bank| bank.bytes().map(|c| c - b'0').collect()) + .collect() +} + +fn max_joltage(bank: &Bank, n: usize) -> u64 { + assert_eq!(n, 2, "unimplemented"); + let mut max = 0; + for start in 0..bank.len() - 1 { + let cur = bank[start] as u64 * 10u64.pow(n as u32 - 1) + + *bank[start + 1..].iter().max().unwrap() as u64; + if cur > max { + max = cur + } + } + max +} + +#[aoc(day3, part1)] +fn part1(input: &Vec) -> u64 { + input.iter().map(|bank| max_joltage(bank, 2)).sum() +} + +#[aoc(day3, part2)] +fn part2(input: &Vec) -> u64 { + todo!() +} + +#[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)), 0); + } +} diff --git a/src/lib.rs b/src/lib.rs index a228b5c..3a057fc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +mod day3; mod day1; mod day2; From 47f70687059a0bb8366b5e9fc183bd01d00e9636 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 2 Dec 2025 21:30:31 -0800 Subject: [PATCH 13/66] day3: part 2, add memoize --- Cargo.lock | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++--- Cargo.toml | 1 + src/day3.rs | 52 +++++++++++++++++++++++------------- 3 files changed, 108 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e0b5f84..87ad879 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,17 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ahash" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" +dependencies = [ + "getrandom", + "once_cell", + "version_check", +] + [[package]] name = "ahash" version = "0.8.12" @@ -72,6 +83,7 @@ dependencies = [ "indicatif", "itertools", "lazy_static", + "memoize", "misc", "nom", "rayon", @@ -113,10 +125,10 @@ version = "0.54.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9718806c4a2fe9e8a56fd736f97b340dd10ed1be8ed733ed50449f351dc33cae" dependencies = [ - "ahash", + "ahash 0.8.12", "cached_proc_macro", "cached_proc_macro_types", - "hashbrown", + "hashbrown 0.14.5", "once_cell", "thiserror", "web-time", @@ -247,17 +259,37 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "getrandom" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[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" +dependencies = [ + "ahash 0.7.8", +] + [[package]] name = "hashbrown" version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ - "ahash", + "ahash 0.8.12", "allocator-api2", ] @@ -318,12 +350,44 @@ version = "0.2.177" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" +[[package]] +name = "lru" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999beba7b6e8345721bd280141ed958096a2e4abdf74f67ff4ce49b4b54e47a" +dependencies = [ + "hashbrown 0.12.3", +] + [[package]] name = "memchr" version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" +[[package]] +name = "memoize" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8d1d5792299bab3f8b5d88d1b7a7cb50ad7ef039a8c4d45a6b84880a6526276" +dependencies = [ + "lazy_static", + "lru", + "memoize-inner", +] + +[[package]] +name = "memoize-inner" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dd8f89255d8ff313afabed9a3c83ef0993cc056679dfd001f5111a026f876f7" +dependencies = [ + "lazy_static", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -576,6 +640,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "wasm-bindgen" version = "0.2.106" diff --git a/Cargo.toml b/Cargo.toml index 9609600..f3cc600 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ grid = {version = "0.1.0", path = "utils/grid"} indicatif = { version = "0.17.9", features = ["rayon"] } itertools = "0.13.0" lazy_static = "1.5.0" +memoize = "0.5.1" misc = {path = "utils/misc"} nom = "7.1.3" rayon = "1.10.0" diff --git a/src/day3.rs b/src/day3.rs index f3a8c64..5cf2ada 100644 --- a/src/day3.rs +++ b/src/day3.rs @@ -1,36 +1,52 @@ -use aoc_runner_derive::{aoc, aoc_generator}; +use std::collections::HashMap; -type Bank = Vec; +use aoc_runner_derive::{aoc, aoc_generator}; +use lazy_static::lazy_static; +use memoize::memoize; + +type Bank = [u8]; #[aoc_generator(day3)] -fn parse(input: &str) -> Vec { +fn parse(input: &str) -> Vec> { input .lines() .map(|bank| bank.bytes().map(|c| c - b'0').collect()) .collect() } -fn max_joltage(bank: &Bank, n: usize) -> u64 { - assert_eq!(n, 2, "unimplemented"); - let mut max = 0; - for start in 0..bank.len() - 1 { - let cur = bank[start] as u64 * 10u64.pow(n as u32 - 1) - + *bank[start + 1..].iter().max().unwrap() as u64; - if cur > max { - max = cur - } +#[memoize] +fn max_joltage(bank: Vec, n: usize) -> u64 { + if n == 1 { + return *bank.iter().max().unwrap() as u64; } - max + + (0..bank.len() - n + 1) + .map(|start| { + bank[start] as u64 * 10u64.pow(n as u32 - 1) + + max_joltage(bank[start + 1..].to_vec(), n - 1) + }) + .max() + .unwrap() + + // let mut max = 0; + // for start in 0..bank.len() - n + 1 { + // let cur = bank[start] as u64 * 10u64.pow(n as u32 - 1) + // + *bank[start + 1..].iter().max().unwrap() as u64; + // if cur > max { + // max = cur + // } + // } + // max } #[aoc(day3, part1)] -fn part1(input: &Vec) -> u64 { - input.iter().map(|bank| max_joltage(bank, 2)).sum() +fn part1(input: &Vec>) -> u64 { + input.iter().map(|bank| max_joltage(bank.clone(), 2)).sum() } #[aoc(day3, part2)] -fn part2(input: &Vec) -> u64 { - todo!() +fn part2(input: &Vec>) -> u64 { + input.iter().map(|bank| max_joltage(bank.clone(), 12)).sum() } #[cfg(test)] @@ -49,6 +65,6 @@ mod tests { #[test] fn part2_example() { - assert_eq!(part2(&parse(EXAMPLE)), 0); + assert_eq!(part2(&parse(EXAMPLE)), 3121910778619); } } From f89bbf2bffc3288f849e1c5198b97f63bd91fdff Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 2 Dec 2025 21:35:09 -0800 Subject: [PATCH 14/66] clippies --- .aoc_tiles/tiles/2025/03.png | Bin 0 -> 7583 bytes README.md | 5 ++++- src/day2.rs | 10 +++++----- src/day3.rs | 9 ++------- src/lib.rs | 2 +- 5 files changed, 12 insertions(+), 14 deletions(-) create mode 100644 .aoc_tiles/tiles/2025/03.png diff --git a/.aoc_tiles/tiles/2025/03.png b/.aoc_tiles/tiles/2025/03.png new file mode 100644 index 0000000000000000000000000000000000000000..73761047055e0f3337c8cfad1a7b7e3906410268 GIT binary patch literal 7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NiRQs<^vZONUWKDIjv^Zb;Ev~TE0G!U n>_a5KFow7M0d66BaC=8{ChbKVpYl`O;1y6;eW6mJY#shT`F^^K literal 0 HcmV?d00001 diff --git a/README.md b/README.md index 807be67..ba3e2c6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

- 2025 - 4 ⭐ - Rust + 2025 - 6 ⭐ - Rust

@@ -8,4 +8,7 @@ + + + diff --git a/src/day2.rs b/src/day2.rs index d5629c6..974fd2f 100644 --- a/src/day2.rs +++ b/src/day2.rs @@ -31,7 +31,7 @@ fn part1(input: &[RangeInclusive]) -> u64 { for r in input { for product in r.clone() { let prod_s = product.to_string(); - if prod_s.len() % 2 != 0 { + if !prod_s.len().is_multiple_of(2) { continue; } let (left, right) = prod_s.split_at(prod_s.len() / 2); @@ -50,7 +50,7 @@ fn part2(input: &[RangeInclusive]) -> u64 { for product in r.clone() { let prod_s = product.to_string(); for n in 1..=prod_s.len() / 2 { - if prod_s.len() % n != 0 { + if !prod_s.len().is_multiple_of(n) { continue; } if prod_s @@ -76,7 +76,7 @@ fn part1_arithmetic_brute(input: &[RangeInclusive]) -> u64 { // println!("Range: {:?}", r); for product in r.clone() { let n_digits = (product.ilog10() + 1) as usize; - if n_digits % 2 != 0 { + if !n_digits.is_multiple_of(2) { continue; } @@ -101,7 +101,7 @@ fn part2_arithmetic_brute(input: &[RangeInclusive]) -> u64 { for n in 1..=n_digits / 2 { let repetitions = n_digits / n; - if n_digits % n != 0 { + if !n_digits.is_multiple_of(n) { continue; } let decade = POW10[n_digits - n]; @@ -127,7 +127,7 @@ fn part1_clever(input: &[RangeInclusive]) -> u64 { for r in input { let n_digits = (r.start().ilog10() + 1) as usize; - let mut lhs = if n_digits % 2 != 0 { + 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 { diff --git a/src/day3.rs b/src/day3.rs index 5cf2ada..2be5275 100644 --- a/src/day3.rs +++ b/src/day3.rs @@ -1,11 +1,6 @@ -use std::collections::HashMap; - use aoc_runner_derive::{aoc, aoc_generator}; -use lazy_static::lazy_static; use memoize::memoize; -type Bank = [u8]; - #[aoc_generator(day3)] fn parse(input: &str) -> Vec> { input @@ -40,12 +35,12 @@ fn max_joltage(bank: Vec, n: usize) -> u64 { } #[aoc(day3, part1)] -fn part1(input: &Vec>) -> u64 { +fn part1(input: &[Vec]) -> u64 { input.iter().map(|bank| max_joltage(bank.clone(), 2)).sum() } #[aoc(day3, part2)] -fn part2(input: &Vec>) -> u64 { +fn part2(input: &[Vec]) -> u64 { input.iter().map(|bank| max_joltage(bank.clone(), 12)).sum() } diff --git a/src/lib.rs b/src/lib.rs index 3a057fc..31454ef 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ -mod day3; mod day1; mod day2; +mod day3; use aoc_runner_derive::aoc_lib; From 688846610526465bb8ddd0d1fa6823988c9003a1 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 3 Dec 2025 00:46:44 -0800 Subject: [PATCH 15/66] day3: add clever solution --- src/day3.rs | 53 +++++++++++++++++++++++++++++++------------ utils/misc/src/lib.rs | 20 +++++++++++++--- 2 files changed, 56 insertions(+), 17 deletions(-) diff --git a/src/day3.rs b/src/day3.rs index 2be5275..a8f7b4a 100644 --- a/src/day3.rs +++ b/src/day3.rs @@ -1,5 +1,6 @@ use aoc_runner_derive::{aoc, aoc_generator}; use memoize::memoize; +use misc::POW10; #[aoc_generator(day3)] fn parse(input: &str) -> Vec> { @@ -17,33 +18,47 @@ fn max_joltage(bank: Vec, n: usize) -> u64 { (0..bank.len() - n + 1) .map(|start| { - bank[start] as u64 * 10u64.pow(n as u32 - 1) - + max_joltage(bank[start + 1..].to_vec(), n - 1) + bank[start] as u64 * POW10[n - 1] + max_joltage(bank[start + 1..].to_vec(), n - 1) }) .max() .unwrap() - - // let mut max = 0; - // for start in 0..bank.len() - n + 1 { - // let cur = bank[start] as u64 * 10u64.pow(n as u32 - 1) - // + *bank[start + 1..].iter().max().unwrap() as u64; - // if cur > max { - // max = cur - // } - // } - // max } -#[aoc(day3, part1)] +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)] +#[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::*; @@ -62,4 +77,14 @@ mod tests { 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/utils/misc/src/lib.rs b/utils/misc/src/lib.rs index b7d4b5c..46d447f 100644 --- a/utils/misc/src/lib.rs +++ b/utils/misc/src/lib.rs @@ -2,6 +2,19 @@ use num_traits::Signed; use std::fmt::Display; use std::ops::{Add, AddAssign}; +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 { @@ -91,8 +104,9 @@ mod tests { use super::*; #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); + fn test_pow10() { + for i in 0..POW10MAX { + assert_eq!(POW10[i], 10u64.pow(i as u32)) + } } } From fec1fc51dd95638c14bb10d488f8b1f4c8875309 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 3 Dec 2025 00:47:03 -0800 Subject: [PATCH 16/66] chore: reference POW10 LUT in utils from day2 --- src/day2.rs | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/src/day2.rs b/src/day2.rs index 974fd2f..79dd47b 100644 --- a/src/day2.rs +++ b/src/day2.rs @@ -1,20 +1,8 @@ use aoc_runner_derive::{aoc, aoc_generator}; use itertools::Itertools; +use misc::POW10; use std::ops::RangeInclusive; -const POW10MAX: usize = u64::MAX.ilog10() as usize; -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 -} - #[aoc_generator(day2)] fn parse(input: &str) -> Vec> { input From aebea5c94d608f48905b7a923faa0a3a425264e1 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 3 Dec 2025 01:02:28 -0800 Subject: [PATCH 17/66] day3: switch to cached from memoize (faster and more mature) --- src/day3.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/day3.rs b/src/day3.rs index a8f7b4a..e2167dc 100644 --- a/src/day3.rs +++ b/src/day3.rs @@ -1,5 +1,5 @@ use aoc_runner_derive::{aoc, aoc_generator}; -use memoize::memoize; +use cached::proc_macro::cached; use misc::POW10; #[aoc_generator(day3)] @@ -10,7 +10,7 @@ fn parse(input: &str) -> Vec> { .collect() } -#[memoize] +#[cached] fn max_joltage(bank: Vec, n: usize) -> u64 { if n == 1 { return *bank.iter().max().unwrap() as u64; From fa40701adb5d9e6ebc04008294c647955e3ba1af Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 3 Dec 2025 01:02:21 -0800 Subject: [PATCH 18/66] chore: cargo update --- Cargo.lock | 168 +++++++++++++++++++---------------------------------- Cargo.toml | 11 ++-- 2 files changed, 64 insertions(+), 115 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 87ad879..b979812 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,17 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "ahash" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - [[package]] name = "ahash" version = "0.8.12" @@ -83,7 +72,6 @@ dependencies = [ "indicatif", "itertools", "lazy_static", - "memoize", "misc", "nom", "rayon", @@ -121,14 +109,14 @@ checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" [[package]] name = "cached" -version = "0.54.0" +version = "0.56.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9718806c4a2fe9e8a56fd736f97b340dd10ed1be8ed733ed50449f351dc33cae" +checksum = "801927ee168e17809ab8901d9f01f700cd7d8d6a6527997fee44e4b0327a253c" dependencies = [ - "ahash 0.8.12", + "ahash", "cached_proc_macro", "cached_proc_macro_types", - "hashbrown 0.14.5", + "hashbrown", "once_cell", "thiserror", "web-time", @@ -136,9 +124,9 @@ dependencies = [ [[package]] name = "cached_proc_macro" -version = "0.23.0" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f42a145ed2d10dce2191e1dcf30cfccfea9026660e143662ba5eec4017d5daa" +checksum = "9225bdcf4e4a9a4c08bf16607908eb2fbf746828d5e0b5e019726dbf6571f201" dependencies = [ "darling", "proc-macro2", @@ -160,25 +148,24 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "colored" -version = "2.2.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" +checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e" dependencies = [ - "lazy_static", - "windows-sys", + "windows-sys 0.59.0", ] [[package]] name = "console" -version = "0.15.11" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" +checksum = "b430743a6eb14e9764d4260d4c0d8123087d504eeb9c48f2b2a5e810dd369df4" dependencies = [ "encode_unicode", "libc", "once_cell", "unicode-width", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -253,6 +240,12 @@ 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 = "fnv" version = "1.0.7" @@ -260,15 +253,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] -name = "getrandom" -version = "0.2.16" +name = "foldhash" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" [[package]] name = "grid" @@ -276,21 +264,13 @@ version = "0.1.0" [[package]] name = "hashbrown" -version = "0.12.3" +version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ - "ahash 0.7.8", -] - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" -dependencies = [ - "ahash 0.8.12", "allocator-api2", + "equivalent", + "foldhash", ] [[package]] @@ -301,23 +281,23 @@ checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" [[package]] name = "indicatif" -version = "0.17.11" +version = "0.18.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "183b3088984b400f4cfac3620d5e076c84da5364016b4f49473de574b2586235" +checksum = "9375e112e4b463ec1b1c6c011953545c65a30164fbab5b581df32b3abf0dcb88" dependencies = [ "console", - "number_prefix", "portable-atomic", "rayon", "unicode-width", + "unit-prefix", "web-time", ] [[package]] name = "itertools" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" dependencies = [ "either", ] @@ -346,18 +326,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.177" +version = "0.2.178" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" - -[[package]] -name = "lru" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999beba7b6e8345721bd280141ed958096a2e4abdf74f67ff4ce49b4b54e47a" -dependencies = [ - "hashbrown 0.12.3", -] +checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091" [[package]] name = "memchr" @@ -365,35 +336,6 @@ version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" -[[package]] -name = "memoize" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8d1d5792299bab3f8b5d88d1b7a7cb50ad7ef039a8c4d45a6b84880a6526276" -dependencies = [ - "lazy_static", - "lru", - "memoize-inner", -] - -[[package]] -name = "memoize-inner" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dd8f89255d8ff313afabed9a3c83ef0993cc056679dfd001f5111a026f876f7" -dependencies = [ - "lazy_static", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - [[package]] name = "misc" version = "0.1.0" @@ -403,12 +345,11 @@ dependencies = [ [[package]] name = "nom" -version = "7.1.3" +version = "8.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" dependencies = [ "memchr", - "minimal-lexical", ] [[package]] @@ -420,12 +361,6 @@ dependencies = [ "autocfg", ] -[[package]] -name = "number_prefix" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" - [[package]] name = "once_cell" version = "1.21.3" @@ -595,18 +530,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.69" +version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.69" +version = "2.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" dependencies = [ "proc-macro2", "quote", @@ -634,18 +569,18 @@ 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 = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - [[package]] name = "wasm-bindgen" version = "0.2.106" @@ -701,6 +636,12 @@ dependencies = [ "wasm-bindgen", ] +[[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.59.0" @@ -710,6 +651,15 @@ dependencies = [ "windows-targets", ] +[[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 = "windows-targets" version = "0.52.6" diff --git a/Cargo.toml b/Cargo.toml index f3cc600..6528947 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,15 +8,14 @@ aoc-runner = "0.3.0" aoc-runner-derive = "0.3.0" atoi = "2.0.0" bitflags = "2.6.0" -cached = "0.54.0" -colored = "2.1.0" +cached = "0.56.0" +colored = "3.0.0" grid = {version = "0.1.0", path = "utils/grid"} -indicatif = { version = "0.17.9", features = ["rayon"] } -itertools = "0.13.0" +indicatif = { version = "0.18.3", features = ["rayon"] } +itertools = "0.14.0" lazy_static = "1.5.0" -memoize = "0.5.1" misc = {path = "utils/misc"} -nom = "7.1.3" +nom = "8.0.0" rayon = "1.10.0" regex = "1.11.1" rustc-hash = "2.1.0" From 6030065f95a13ad191b3aac0b93941dd5cead9db Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 3 Dec 2025 21:28:49 -0800 Subject: [PATCH 19/66] day4: part1 --- .aoc_tiles/tiles/2025/04.png | Bin 0 -> 6281 bytes README.md | 5 +++- src/day4.rs | 47 +++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + utils/grid/lib.rs | 22 ++++++++++++++++ 5 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 .aoc_tiles/tiles/2025/04.png create mode 100644 src/day4.rs diff --git a/.aoc_tiles/tiles/2025/04.png b/.aoc_tiles/tiles/2025/04.png new file mode 100644 index 0000000000000000000000000000000000000000..2b574ecec7196188c4510c8d48263097d4fdbdfa GIT binary patch literal 6281 zcmV;47 zd2kfhoyULOb03;Z_lXWbNXSA4ncG+f$94<^979+`;y4&NTf|jyoVY5xN!8|ZvL>}I zSFx#hH(;>6*c@vUdlegO1Gca^gbWCTkU#?6$Bbq)GaB{W-TOyFtJTxf)7>+g83}#= zlAd1or+@E#)&2VQ>t7?c4*UVc3d1nb+p5*-8SXUZq6wkiYpr~*aew&6acTUi_gX98 zQ{2t39V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g`AWe_9)fcrc_pF4n!daMH+uZZ#CCRN^Z`p71p+)$BR#vE1h zxC&VFybFclexJwOBZwNRQ0_F#dp;T5ezDW=PK&y4Trbl9IrGXR7wW5{J4S8;eNA@NER*veBb?|C$uR98_Yq25YV|MJa*7F+5)nD;y;+=%yp3~wbc zUXh<-6HVRx+R+(TiR1E|SqPnrkCH1?WW0ROSlZ%BW5t6#AN@sc%F@q&P?cGLd)=0% z`jOTKvVttdn6Yq;Cc8+Y)cBmk*kG6S>Q}ze5o!i_`Ha6kD*^-SLL z=((cj)&DD3)J=FcwuEQKuK}v?+O(2)N zu8DhMLwYOzt^)qX@_Bs#Fcvn!5YhR`o5s0|bVU`qc}oD`zh^(PXV0F7h6YwDetsNcWlU*fM@6K=q zaVHqdbpIM{ai#6z=dRo1IcNA#pZV)Cx%`gzyk75_GiTb`+D@N7T~$>j+E~-6mG40= z%~%Mco3jX!%2G=1r;HVmN)FF|^rIi`+`046p+ikgP2Jty8ja?eXPy}w8#{kq

- 2025 - 6 ⭐ - Rust + 2025 - 7 ⭐ - Rust

@@ -11,4 +11,7 @@ + + + diff --git a/src/day4.rs b/src/day4.rs new file mode 100644 index 0000000..ab98f5e --- /dev/null +++ b/src/day4.rs @@ -0,0 +1,47 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use grid::Grid; + +#[aoc_generator(day4)] +fn parse(input: &str) -> Grid { + input.parse().unwrap() +} + +#[aoc(day4, part1)] +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.neighbours_count(input.coord(i as i64).unwrap(), |c| *c == b'@')) + .filter(|n| *n < 4) + .count() as u64 +} + +#[aoc(day4, part2)] +fn part2(input: &Grid) -> u64 { + input.width() as u64 +} + +#[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)), 0); + } +} diff --git a/src/lib.rs b/src/lib.rs index 31454ef..3961a65 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ mod day1; mod day2; mod day3; +mod day4; use aoc_runner_derive::aoc_lib; diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs index 67f810c..2b0b6e3 100644 --- a/utils/grid/lib.rs +++ b/utils/grid/lib.rs @@ -352,6 +352,28 @@ impl Grid { } } + /// Return the count of neighbours (8 directions) matching predicate p + pub fn neighbours_count(&self, c: C, mut p: P) -> usize + where + P: FnMut(&T) -> bool, + { + const DIRECTIONS: [(i64, i64); 8] = [ + (-1, -1), + (0, -1), + (1, -1), + (-1, 0), + (1, 0), + (1, 1), + (0, 1), + (-1, 1), + ]; + DIRECTIONS + .iter() + .map(|d| (c.x() + d.0, c.y() + d.1)) + .filter(|c| self.get(c).is_some_and(|x| p(x))) + .count() + } + // fn window_compare_impl(&self, needle: &[T]) -> Vec<(i64, i64)> { // if (self.width as usize) < needle.len() { // return Vec::new(); From 4b51bcac08fb82828a414ca41be967be15beaef2 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 3 Dec 2025 21:36:46 -0800 Subject: [PATCH 20/66] day4: part2 --- src/day4.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/day4.rs b/src/day4.rs index ab98f5e..16315ac 100644 --- a/src/day4.rs +++ b/src/day4.rs @@ -17,7 +17,26 @@ fn part1(input: &Grid) -> u64 { #[aoc(day4, part2)] fn part2(input: &Grid) -> u64 { - input.width() as 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.neighbours_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 + } } #[cfg(test)] @@ -42,6 +61,6 @@ mod tests { #[test] fn part2_example() { - assert_eq!(part2(&parse(EXAMPLE)), 0); + assert_eq!(part2(&parse(EXAMPLE)), 43); } } From 6acb491b45e742427dd866529f88e2eef948c229 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 3 Dec 2025 22:07:36 -0800 Subject: [PATCH 21/66] grid improvements --- .aoc_tiles/tiles/2025/04.png | Bin 6281 -> 7308 bytes README.md | 2 +- utils/grid/lib.rs | 46 +++++++++++++++++++++++++++++------ 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/.aoc_tiles/tiles/2025/04.png b/.aoc_tiles/tiles/2025/04.png index 2b574ecec7196188c4510c8d48263097d4fdbdfa..4a614fa452dd8991afc04c258572c5266f8c3b06 100644 GIT binary patch literal 7308 zcmX9@1yodB7k#8i2qHsBmqw}>YA44MKXMKIC^;KSzl3Ase)VZpx(uOJ?E|LAl+Po?8_lEAGfd@=W zfY7H;zfU`{gvrCmt>?~xVBnUWrlJ-UOQsJB_Ajgn=<2b?RvC(>FWoM2&#BZG!{`uJN7VmH}K=?Rj7ns6iu z3`)`C>?p=o6ewQ8hZ>Y-iRFjtg$Sv+a^L}@V1855qLxMw-07W*F-?K?h);O3`=^o^+xZ6jwLp*XY1r4w5G) zNv->l5|(9B!)r+cw

GZP-!zWG-)Dv*LwKJX?vmzQ=Ipu?^XXA>Br`uZhC1nN2_;I z3tWygQzN|IJ%$l;^yqu$+(lW~%EP>lyg_g~((!oJeOz1>5qJw?sl~IYC68vxR2dm} zz4!R#Q<4Y$nqx;J1v$@>ot4R7llgDFtB-RoRAc#U8<)$WF%aABd zX^1#`4=?}I32_Hgenoab8#h<{j_uh%rD?t^!Wh?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⭐ - Rust

diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs index 2b0b6e3..38d395a 100644 --- a/utils/grid/lib.rs +++ b/utils/grid/lib.rs @@ -149,7 +149,34 @@ 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.grid.coord(self.pos as i64).into() + self.pos += 1; + self.grid.coord(self.pos as i64 - 1).into() + } else { + None + } + } +} + +#[derive(Debug)] +pub struct ItemIter<'a, T> { + pos: usize, + grid: &'a Grid, +} + +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 } @@ -226,9 +253,12 @@ impl Grid { }) } } - // pub fn coord_iter(&self) -> CoordIter<_> { - // CoordIter { pos: 0, grid: self } - // } + 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; @@ -292,7 +322,7 @@ impl Grid { } } - pub fn row_iter(&self, y: i64) -> Option> { + pub fn row_iter<'a>(&'a self, y: i64) -> Option> { if (y as usize) < self.height() { Some(GridRowIter::new(self, y)) } else { @@ -308,7 +338,7 @@ impl Grid { } } - pub fn col_iter(&self, x: i64) -> Option> { + pub fn col_iter<'a>(&'a self, x: i64) -> Option> { if (x as usize) < self.width() { Some(GridColIter::new(self, x)) } else { @@ -316,13 +346,13 @@ impl Grid { } } - pub fn find(&self, haystack: &T) -> Option { + pub fn find(&self, needle: &T) -> Option { self.coord( self.data .iter() .enumerate() .find_map(|(pos, val)| { - if val == haystack { + if val == needle { Some(pos as i64) } else { None From 2d9abb841ba5ea047da176fbe4d3b153312806df Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 3 Dec 2025 22:22:53 -0800 Subject: [PATCH 22/66] grid: add find_all method/iterator --- utils/grid/lib.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs index 38d395a..ff5f605 100644 --- a/utils/grid/lib.rs +++ b/utils/grid/lib.rs @@ -361,6 +361,13 @@ impl Grid { .unwrap_or(-1), ) } + /// Get all of the coordinates having value `needle` + pub fn find_all<'a>(&'a self, needle: &'a T) -> impl Iterator + '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() } @@ -566,6 +573,15 @@ FBCG"; 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 window_compare() { // let grid = unchecked_load(); From faa452149ad674f710560666231250652efd0123 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Thu, 4 Dec 2025 15:49:37 -0800 Subject: [PATCH 23/66] add neighbour and cardinal iterators to grid --- src/day4.rs | 5 +- utils/grid/lib.rs | 148 +++++++++++++++++++++++++++++++++++++++------- 2 files changed, 127 insertions(+), 26 deletions(-) diff --git a/src/day4.rs b/src/day4.rs index 16315ac..db77825 100644 --- a/src/day4.rs +++ b/src/day4.rs @@ -10,11 +10,10 @@ fn parse(input: &str) -> Grid { 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.neighbours_count(input.coord(i as i64).unwrap(), |c| *c == b'@')) + .map(|i| input.neighbours_count(&input.coord(i as i64).unwrap(), |c| *c == b'@')) .filter(|n| *n < 4) .count() as u64 } - #[aoc(day4, part2)] fn part2(input: &Grid) -> u64 { let mut grid = input.clone(); @@ -25,7 +24,7 @@ fn part2(input: &Grid) -> u64 { 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.neighbours_count(pos, |c| *c == b'@') < 4 + && grid.neighbours_count(&pos, |c| *c == b'@') < 4 { // remove the roll grid.set(&pos, b'.'); diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs index ff5f605..936e2b1 100644 --- a/utils/grid/lib.rs +++ b/utils/grid/lib.rs @@ -7,6 +7,21 @@ use std::{ str::FromStr, }; +/// NW, N, NE, W, E, SW, S, SE +const ADJACENT_OFFSETS: [&(i64, i64); 8] = [ + &(-1, -1), + &(0, -1), + &(1, -1), + &(-1, 0), + &(1, 0), + &(-1, 1), + &(0, 1), + &(1, 1), +]; + +/// NESW +const CARDINAL_OFFSETS: [&(i64, i64); 4] = [&(0, -1), &(-1, 0), &(1, 0), &(0, 1)]; + #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Coord2d { pub x: i64, @@ -29,7 +44,10 @@ impl Sub for &Coord2d { } } -impl Add for &Coord2d { +impl Add for &Coord2d +where + T: Copy, +{ type Output = Coord2d; fn add(self, rhs: T) -> Self::Output { Coord2d { @@ -39,7 +57,7 @@ impl Add for &Coord2d { } } -impl Add<&T> for Coord2d { +impl Add<&T> for Coord2d { type Output = Coord2d; fn add(self, rhs: &T) -> Self::Output { Coord2d { @@ -150,7 +168,7 @@ impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for CoordIter<'a, T> { fn next(&mut self) -> Option { if self.pos < self.grid.data.len() { self.pos += 1; - self.grid.coord(self.pos as i64 - 1).into() + self.grid.coord(self.pos as i64 - 1) } else { None } @@ -163,6 +181,7 @@ pub struct ItemIter<'a, T> { grid: &'a Grid, } +#[derive(Debug, PartialEq, Eq)] pub struct Item<'a, T> { pub pos: Coord2d, pub value: &'a T, @@ -216,6 +235,31 @@ impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for GridColIter<'a, T> { } } +#[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)] pub struct Grid { pub data: Vec, @@ -266,7 +310,7 @@ impl Grid { if c.y() < 0 || c.y() as usize >= self.height() { return false; } - return true; + true } fn valid_pos(&self, c: &C) -> Option { if c.x() < 0 || c.x() >= self.width { @@ -331,11 +375,7 @@ impl Grid { } pub fn col(&self, x: i64) -> Option> { - if let Some(iter) = self.col_iter(x) { - Some(iter.collect()) - } else { - None - } + self.col_iter(x).map(|iter| iter.collect()) } pub fn col_iter<'a>(&'a self, x: i64) -> Option> { @@ -390,27 +430,37 @@ impl Grid { } /// Return the count of neighbours (8 directions) matching predicate p - pub fn neighbours_count(&self, c: C, mut p: P) -> usize + pub fn neighbours_count(&self, c: &C, mut p: P) -> usize where P: FnMut(&T) -> bool, { - const DIRECTIONS: [(i64, i64); 8] = [ - (-1, -1), - (0, -1), - (1, -1), - (-1, 0), - (1, 0), - (1, 1), - (0, 1), - (-1, 1), - ]; - DIRECTIONS + ADJACENT_OFFSETS .iter() - .map(|d| (c.x() + d.0, c.y() + d.1)) - .filter(|c| self.get(c).is_some_and(|x| p(x))) + .map(|d| c.to_coord() + *d) + .filter(|c| self.get(c).is_some_and(&mut p)) .count() } + /// Return an iterator over the 8 neighbours of c. The iterator skips neighbouring positions outside of the grid. + pub fn neighbours_iter(&self, c: &C) -> OffsetsIter { + 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(&self, c: &C) -> OffsetsIter { + OffsetsIter { + grid: self, + origin: c.to_coord(), + cur: 0, + offsets: &CARDINAL_OFFSETS, + } + } + // fn window_compare_impl(&self, needle: &[T]) -> Vec<(i64, i64)> { // if (self.width as usize) < needle.len() { // return Vec::new(); @@ -582,6 +632,58 @@ FBCG"; ) } + #[test] + fn neighbours_iter() { + let grid = unchecked_load(); + assert_eq!( + grid.neighbours_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(); From fa7f62cacf39ca214348ad5b32d529e178e9e7b7 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Thu, 4 Dec 2025 17:28:53 -0800 Subject: [PATCH 24/66] rename neighbours to adjacent, add count impl for cardinal --- src/day4.rs | 4 ++-- utils/grid/lib.rs | 34 ++++++++++++++++++++++------------ 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/day4.rs b/src/day4.rs index db77825..41f64f2 100644 --- a/src/day4.rs +++ b/src/day4.rs @@ -10,7 +10,7 @@ fn parse(input: &str) -> Grid { 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.neighbours_count(&input.coord(i as i64).unwrap(), |c| *c == b'@')) + .map(|i| input.adjacent_count(&input.coord(i as i64).unwrap(), |c| *c == b'@')) .filter(|n| *n < 4) .count() as u64 } @@ -24,7 +24,7 @@ fn part2(input: &Grid) -> u64 { 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.neighbours_count(&pos, |c| *c == b'@') < 4 + && grid.adjacent_count(&pos, |c| *c == b'@') < 4 { // remove the roll grid.set(&pos, b'.'); diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs index 936e2b1..daed417 100644 --- a/utils/grid/lib.rs +++ b/utils/grid/lib.rs @@ -8,7 +8,7 @@ use std::{ }; /// NW, N, NE, W, E, SW, S, SE -const ADJACENT_OFFSETS: [&(i64, i64); 8] = [ +pub const ADJACENT_OFFSETS: [&(i64, i64); 8] = [ &(-1, -1), &(0, -1), &(1, -1), @@ -20,14 +20,20 @@ const ADJACENT_OFFSETS: [&(i64, i64); 8] = [ ]; /// NESW -const CARDINAL_OFFSETS: [&(i64, i64); 4] = [&(0, -1), &(-1, 0), &(1, 0), &(0, 1)]; +pub const CARDINAL_OFFSETS: [&(i64, i64); 4] = [&(0, -1), &(-1, 0), &(1, 0), &(0, 1)]; -#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct Coord2d { pub x: i64, pub y: i64, } +impl Debug for Coord2d { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("({}, {})", self.x, self.y)) + } +} + pub trait AsCoord2d { fn to_coord(self) -> Coord2d; fn x(&self) -> i64; @@ -402,7 +408,7 @@ impl Grid { ) } /// Get all of the coordinates having value `needle` - pub fn find_all<'a>(&'a self, needle: &'a T) -> impl Iterator + 'a { + pub fn find_all<'a>(&'a self, needle: &'a T) -> impl DoubleEndedIterator + 'a { self.data .iter() .enumerate() @@ -430,19 +436,23 @@ impl Grid { } /// Return the count of neighbours (8 directions) matching predicate p - pub fn neighbours_count(&self, c: &C, mut p: P) -> usize + pub fn adjacent_count(&self, c: &C, mut p: P) -> usize where P: FnMut(&T) -> bool, { - ADJACENT_OFFSETS - .iter() - .map(|d| c.to_coord() + *d) - .filter(|c| self.get(c).is_some_and(&mut p)) - .count() + 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 neighbours_iter(&self, c: &C) -> OffsetsIter { + pub fn adjacent_iter(&self, c: &C) -> OffsetsIter { OffsetsIter { grid: self, origin: c.to_coord(), @@ -636,7 +646,7 @@ FBCG"; fn neighbours_iter() { let grid = unchecked_load(); assert_eq!( - grid.neighbours_iter(&(0, 1)).collect::>(), + grid.adjacent_iter(&(0, 1)).collect::>(), [ Item { pos: Coord2d { x: 0, y: 0 }, From d49157dd7982dee0fef34633f22c513415382761 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Thu, 4 Dec 2025 17:29:12 -0800 Subject: [PATCH 25/66] day4: add removal queue implementation for part2 --- src/day4.rs | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/src/day4.rs b/src/day4.rs index 41f64f2..d781cd6 100644 --- a/src/day4.rs +++ b/src/day4.rs @@ -1,12 +1,13 @@ 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)] +#[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'@') @@ -14,7 +15,8 @@ fn part1(input: &Grid) -> u64 { .filter(|n| *n < 4) .count() as u64 } -#[aoc(day4, part2)] + +#[aoc(day4, part2, Brute)] fn part2(input: &Grid) -> u64 { let mut grid = input.clone(); let mut removed = 0; @@ -38,6 +40,30 @@ fn part2(input: &Grid) -> u64 { } } +#[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::*; @@ -62,4 +88,9 @@ mod tests { fn part2_example() { assert_eq!(part2(&parse(EXAMPLE)), 43); } + + #[test] + fn part2_list_example() { + assert_eq!(part2_list(&parse(EXAMPLE)), 43); + } } From 0ee1e316d7d0560c22fb361d4717da9beae513ff Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Thu, 4 Dec 2025 21:07:02 -0800 Subject: [PATCH 26/66] day5: part1 --- .aoc_tiles/tiles/2025/05.png | Bin 0 -> 6988 bytes README.md | 5 ++- src/day5.rs | 75 +++++++++++++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 .aoc_tiles/tiles/2025/05.png create mode 100644 src/day5.rs diff --git a/.aoc_tiles/tiles/2025/05.png b/.aoc_tiles/tiles/2025/05.png new file mode 100644 index 0000000000000000000000000000000000000000..fd91c3e724019f19641fb3535b96fb16135b5637 GIT binary patch literal 6988 zcmV-S8?)qzP)=52x_+y=x_V#I*;leb79i}4iVOp&BO=Cyao{-aay&R^?%Z?6Gc$UeJ2Thu9`Wd? zS7-E^8LtZ$(E-%K1rg8yktOU9NJt=L>!j1^^p@(is_u`1PIYy4bycU6?gpM;ov*&C zr{1rge9Qa2^%inr)II`0JV zGLqu(#^|vSREBAdnAWH+ob0z-x^``Xcn!V^T6yZ@e?HUjZ0Jwpl-Y%g@8z6A1p}1d z}FM|oQmn|t?-l)Rz^k3}Xvk4GHm0zBH!z!6V4FEEQx@gJji`(Cka>Lh< zs<=Q9ebszSV;E@sCjjIwx))Wb#*cSm?Bz%*8gH!0J577~I{FWOUAXw3%U8)ORb~}< zt$hH1sWe$Lmgq}sWlD|DZW%nf8vsgf{W()J=yA7h{4cHEIO(TPhpyMN{jGp=2mp%j z`UR#jFol-=+eR+6M3Sd|D|6tr_Q`MsrZpm{Z1hfwsx&1vBVA|5j~6Dy-bhIa@Wx&h z5(MFCKVEQiJ%U_zdT9$Qz1BX3A*=L`$1$~zDO6<@mfZ4y?d%~jtYVPjt;~!5T_4b7 zP^M64-*}fQzdTf~Et?)wSdw@%r`}+gJPX%ndWX!`la16+52u1mq0X4KRGD2OQ>gsI z1J3rNy#Knwyr^7JanCPsooV{?=_E;p%H?wTBab{%Utgb>m)GCl|HT(yeE8vqfk1$L zZVX{DtTaUi377mz2P4-S0g$3)YeT960HA3=5L3I-Mzh`2&>S z=QwwO^thEdC0X-s_YavPR}#X!`8Ta{c*$%XxBNH1`OWg>%U^owrH+n{>gwuW|N7TP zqwz0)`3t*_kg(XSD29iA(-fsCC|8Awg7G!+~RFQ(FFPP@t6^snL8W&ogv&2ptGW5yD;urg-;nDi3no$pgYKL8LtZT6Fm z%y03$@3jS1suJb3Io&UI*@1@1l)SAnWzN=?R$CF~Nv-4d;G zFc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Br|EDDh6}s&JC>-LmEmcRRI8U`kiOuVMP#C zUYTZ6tunhDLdXjofYn`){8USUa&6_n$6My^by zLvbYuG610bUefOg5-#tMS>P2hF}z}8&*gG?Zf(lV&hJQ zdBr2?J142xS25t`d7l_o4miA5YliBC^Rj!amX?;7+L}mvM}?INtt>VDYbre5Wbv~5 zs?hF@fVL*sUT&WEiD3;P#Cz4}Jx?qzX9SF?t%54~5&q(jyt)$PR&}SMdX5`Gft!MW~a6Rw&n0e#yg0lA$C21>B z_DT?z3|D2}ba&S`A4I+ak7*6K&eV7O`;p!b0PtG-m^Z4g=RF@gZ`{81IJA{Od!apS(w7y`J~{I

- 2025 - 8 ⭐ - Rust + 2025 - 9 ⭐ - Rust

@@ -14,4 +14,7 @@ + + + diff --git a/src/day5.rs b/src/day5.rs new file mode 100644 index 0000000..0ffc29a --- /dev/null +++ b/src/day5.rs @@ -0,0 +1,75 @@ +use std::ops::RangeInclusive; + +use aoc_runner_derive::{aoc, aoc_generator}; + +struct Database { + fresh_ingredients: Vec>, + available_ingredients: Vec, +} + +#[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 == "" { + parsing_ranges = false; + continue; + } + if parsing_ranges { + let (start, end) = line.split_once(|c| c == '-').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(day5, part2)] +fn part2(input: &Database) -> u64 { + 0 +} + +#[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(&parse(EXAMPLE)), 0); + } +} From 252bbf3cdae064ee1bc56ec818bb7544366a000f Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 5 Dec 2025 00:26:39 -0800 Subject: [PATCH 27/66] day5: part2 --- .aoc_tiles/tiles/2025/05.png | Bin 6988 -> 7796 bytes README.md | 2 +- src/day5.rs | 108 +++++++++++++++++++++++++++++++++-- src/lib.rs | 1 + 4 files changed, 104 insertions(+), 7 deletions(-) diff --git a/.aoc_tiles/tiles/2025/05.png b/.aoc_tiles/tiles/2025/05.png index fd91c3e724019f19641fb3535b96fb16135b5637..6723ab7eacdaf3c3743b4494c2497cb340afe414 100644 GIT binary patch literal 7796 zcmX9@1yod97rvq>At@;!As`^#-Jyi!Fhh5DgOnmI^*}(nYk;9cQo2)0YRI9xbN+en zU+czMcipwm+2@>Z?{A+kLhX|R4%TZd003}4evs8bz57wOIR+Z)sl2hR4*+jOKFUgI zd8Z%v>$p?QrXb3R?>@z?u)uPQL*khta#?kn3n0q}Rn2)ZJb#vARI}VakEVnPS&eQC zrzGcZ4f_@q6(#J%tbf|br{aiUlZ&t8AgMbd?8%@ZF*U+2mS#Isqk}L3AuP^e=VDJt z8xFx&%XnVxNWAF#+jrUe_|McYYjn#mg`CjOI=^?`mL;C@^y?K?CfPVy?f9+eCv5ujGHP6a7QkyvH` zjWRSz|8`-%s%${2UWmX0QX}(p3_!`ajZc7Ld2n4oLzNF-?#w>~SxAHpAo=I()y+?L z7OvwxWPv~`xaG>IW=AF9LNx_~4~$>;#;RpR;GG-XiV8h)X8HY1bQNBacP54k$Z&F> zG2&!26~Z>U^KRDBm6So*wUq!31|6S!^I?ww?e-3lh7mjyw-HnbMS#U6>z<3NX@cPA zlULHQutAf=ZzvCzHL2ZRMigDG^jSjPPsr$uC+fy%77_y!Ce_ zp9w8@QkVY_w2+3M7>cFZ6Y5BEzo&TC`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?hF@fVL*sUT&WEiD3;P#Cz4}Jx?qzX9SF?t%54~5&q(jyt)$PR&}SMdX5`Gft!MW~a6Rw&n0e#yg0lA$C21>B z_DT?z3|D2}ba&S`A4I+ak7*6K&eV7O`;p!b0PtG-m^Z4g=RF@gZ`{81IJA{Od!apS(w7y`J~{I

- 2025 - 9 ⭐ - Rust + 2025 - 10 ⭐ - Rust

diff --git a/src/day5.rs b/src/day5.rs index 0ffc29a..a2f6131 100644 --- a/src/day5.rs +++ b/src/day5.rs @@ -1,3 +1,5 @@ +use std::cmp::{max, min}; +use std::fmt::Debug; use std::ops::RangeInclusive; use aoc_runner_derive::{aoc, aoc_generator}; @@ -7,18 +9,94 @@ struct Database { available_ingredients: Vec, } -#[aoc_generator(day5)] +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) { + // sort the ranges by start + if self.ranges.len() < 2 { + return; + } + let mut modified = true; + while modified { + let mut new_ranges = Vec::new(); + modified = false; + self.ranges.sort_by_key(|s| s.start); + for chunk in self.ranges.chunks(2) { + if chunk.len() == 1 { + new_ranges.push(chunk[0].clone()); + continue; + } + let (l, r) = (&chunk[0], &chunk[1]); + if r.start <= l.end + 1 { + modified = true; + new_ranges.push((min(r.start, l.start), max(l.end, r.end)).into()) + } else { + new_ranges.push(l.clone()); + new_ranges.push(r.clone()); + } + } + if !self.ranges.len().is_multiple_of(2) && new_ranges.len() >= 2 { + let (l, r) = (new_ranges.pop().unwrap(), new_ranges.pop().unwrap()); + if r.start <= l.end + 1 && r.end >= l.start - 1 { + modified = true; + new_ranges.push((min(r.start, l.start), max(l.end, r.end)).into()) + } else { + new_ranges.push(l.clone()); + new_ranges.push(r.clone()); + } + } + self.ranges = new_ranges; + } + } + fn add(&mut self, s: Span) { + self.ranges.push(s); + self.simplify() + } +} + +#[aoc_generator(day5, part1)] 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 == "" { + if line.is_empty() { parsing_ranges = false; continue; } if parsing_ranges { - let (start, end) = line.split_once(|c| c == '-').unwrap(); + let (start, end) = line.split_once('-').unwrap(); fresh_ingredients.push(RangeInclusive::new( start.parse().unwrap(), end.parse().unwrap(), @@ -33,6 +111,19 @@ fn parse(input: &str) -> Database { } } +#[aoc_generator(day5, part2)] +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, part1)] fn part1(input: &Database) -> u64 { input @@ -43,8 +134,13 @@ fn part1(input: &Database) -> u64 { } #[aoc(day5, part2)] -fn part2(input: &Database) -> u64 { - 0 +fn part2(input: &Database2) -> u64 { + let mut all_ingredients = RangeSet::new(); + for r in &input.fresh_ingredients { + all_ingredients.add(r.clone()) + } + + all_ingredients.ranges.iter().map(|r| r.len()).sum::() } #[cfg(test)] @@ -70,6 +166,6 @@ mod tests { #[test] fn part2_example() { - assert_eq!(part2(&parse(EXAMPLE)), 0); + assert_eq!(part2(&parse2(EXAMPLE)), 14); } } diff --git a/src/lib.rs b/src/lib.rs index 3961a65..1bb311f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,7 @@ mod day1; mod day2; mod day3; mod day4; +mod day5; use aoc_runner_derive::aoc_lib; From 73765e857aad685ab8fc3bab451bc03395e94902 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 5 Dec 2025 01:09:32 -0800 Subject: [PATCH 28/66] day5: bugfixes for rangeset --- src/day5.rs | 62 +++++++++++++++++++++++++++-------------------------- 1 file changed, 32 insertions(+), 30 deletions(-) diff --git a/src/day5.rs b/src/day5.rs index a2f6131..50958e0 100644 --- a/src/day5.rs +++ b/src/day5.rs @@ -1,4 +1,4 @@ -use std::cmp::{max, min}; +use std::cmp::max; use std::fmt::Debug; use std::ops::RangeInclusive; @@ -43,45 +43,47 @@ impl RangeSet { Self { ranges: Vec::new() } } fn simplify(&mut self) { - // sort the ranges by start if self.ranges.len() < 2 { return; } let mut modified = true; while modified { - let mut new_ranges = Vec::new(); modified = false; + // sort the ranges by start self.ranges.sort_by_key(|s| s.start); - for chunk in self.ranges.chunks(2) { - if chunk.len() == 1 { - new_ranges.push(chunk[0].clone()); - continue; + 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) = (&chunk[0], &chunk[1]); + let (l, r) = (&self.ranges[pos - 1], &self.ranges[pos]); + if r.start <= l.end + 1 { modified = true; - new_ranges.push((min(r.start, l.start), max(l.end, r.end)).into()) - } else { + 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()); - new_ranges.push(r.clone()); - } - } - if !self.ranges.len().is_multiple_of(2) && new_ranges.len() >= 2 { - let (l, r) = (new_ranges.pop().unwrap(), new_ranges.pop().unwrap()); - if r.start <= l.end + 1 && r.end >= l.start - 1 { - modified = true; - new_ranges.push((min(r.start, l.start), max(l.end, r.end)).into()) + 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); - self.simplify() } } @@ -111,6 +113,15 @@ fn parse(input: &str) -> Database { } } +#[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)] fn parse2(input: &str) -> Database2 { let mut fresh_ingredients = Vec::new(); @@ -124,22 +135,13 @@ fn parse2(input: &str) -> Database2 { Database2 { fresh_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(day5, part2)] fn part2(input: &Database2) -> u64 { let mut all_ingredients = RangeSet::new(); for r in &input.fresh_ingredients { - all_ingredients.add(r.clone()) + all_ingredients.add(r.clone()); } - + all_ingredients.simplify(); all_ingredients.ranges.iter().map(|r| r.len()).sum::() } From 09cd17d3ff815172c2e58dba82fd31746b316a8c Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 5 Dec 2025 04:30:19 -0800 Subject: [PATCH 29/66] grid: clippies --- utils/grid/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs index daed417..f2fa866 100644 --- a/utils/grid/lib.rs +++ b/utils/grid/lib.rs @@ -452,7 +452,7 @@ impl Grid { } /// Return an iterator over the 8 neighbours of c. The iterator skips neighbouring positions outside of the grid. - pub fn adjacent_iter(&self, c: &C) -> OffsetsIter { + pub fn adjacent_iter<'a, C: AsCoord2d + Copy>(&'a self, c: &'a C) -> OffsetsIter<'a, T> { OffsetsIter { grid: self, origin: c.to_coord(), @@ -462,7 +462,7 @@ impl Grid { } /// Return an iterator over the 4 cardinal neighbours of c. The iterator skips neighbouring positions outside of the grid. - pub fn cardinal_iter(&self, c: &C) -> OffsetsIter { + pub fn cardinal_iter<'a, C: AsCoord2d + Copy>(&'a self, c: &'a C) -> OffsetsIter<'a, T> { OffsetsIter { grid: self, origin: c.to_coord(), From f51dc9c14514d7c04ce8196e6b80fbd8855e7fe6 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 5 Dec 2025 04:29:55 -0800 Subject: [PATCH 30/66] day2: clever and fast solution --- src/day2.rs | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/src/day2.rs b/src/day2.rs index 79dd47b..a9c2ae3 100644 --- a/src/day2.rs +++ b/src/day2.rs @@ -1,6 +1,7 @@ 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)] @@ -88,15 +89,15 @@ fn part2_arithmetic_brute(input: &[RangeInclusive]) -> u64 { let n_digits = (product.ilog10() + 1) as usize; for n in 1..=n_digits / 2 { - let repetitions = n_digits / n; if !n_digits.is_multiple_of(n) { continue; } - let decade = POW10[n_digits - n]; + 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) + // 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 { @@ -139,6 +140,48 @@ fn part1_clever(input: &[RangeInclusive]) -> u64 { 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::*; @@ -167,4 +210,8 @@ mod tests { fn part1_clever_example() { assert_eq!(part1_clever(&parse(EXAMPLE)), 1227775554); } + #[test] + fn part2_clever_example() { + assert_eq!(part2_clever(&parse(EXAMPLE)), 4174379265); + } } From 2158b8cf3542fa9b13769d7d7823b80c1b841f52 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 5 Dec 2025 16:26:13 -0800 Subject: [PATCH 31/66] remove unused cargo deps --- Cargo.lock | 253 ----------------------------------------------------- Cargo.toml | 9 -- 2 files changed, 262 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b979812..f20472c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -64,29 +64,11 @@ version = "0.1.0" dependencies = [ "aoc-runner", "aoc-runner-derive", - "atoi", - "bitflags", "cached", - "colored", "grid", - "indicatif", "itertools", - "lazy_static", "misc", - "nom", - "rayon", "regex", - "rustc-hash", - "thread_local", -] - -[[package]] -name = "atoi" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" -dependencies = [ - "num-traits", ] [[package]] @@ -95,12 +77,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" -[[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" @@ -146,53 +122,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" -[[package]] -name = "colored" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e" -dependencies = [ - "windows-sys 0.59.0", -] - -[[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 0.61.2", -] - -[[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" @@ -234,12 +163,6 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" -[[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" @@ -279,20 +202,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" -[[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 = "itertools" version = "0.14.0" @@ -318,18 +227,6 @@ dependencies = [ "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 = "memchr" version = "2.7.6" @@ -343,15 +240,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "nom" -version = "8.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" -dependencies = [ - "memchr", -] - [[package]] name = "num-traits" version = "0.2.19" @@ -367,12 +255,6 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" -[[package]] -name = "portable-atomic" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" - [[package]] name = "proc-macro2" version = "1.0.103" @@ -391,26 +273,6 @@ dependencies = [ "proc-macro2", ] -[[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 = "regex" version = "1.12.2" @@ -440,12 +302,6 @@ version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" -[[package]] -name = "rustc-hash" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" - [[package]] name = "rustversion" version = "1.0.22" @@ -548,33 +404,12 @@ dependencies = [ "syn 2.0.111", ] -[[package]] -name = "thread_local" -version = "1.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" -dependencies = [ - "cfg-if", -] - [[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" @@ -636,94 +471,6 @@ dependencies = [ "wasm-bindgen", ] -[[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.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets", -] - -[[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 = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - [[package]] name = "zerocopy" version = "0.8.31" diff --git a/Cargo.toml b/Cargo.toml index 6528947..392985c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,20 +6,11 @@ version = "0.1.0" [dependencies] aoc-runner = "0.3.0" aoc-runner-derive = "0.3.0" -atoi = "2.0.0" -bitflags = "2.6.0" cached = "0.56.0" -colored = "3.0.0" grid = {version = "0.1.0", path = "utils/grid"} -indicatif = { version = "0.18.3", features = ["rayon"] } itertools = "0.14.0" -lazy_static = "1.5.0" misc = {path = "utils/misc"} -nom = "8.0.0" -rayon = "1.10.0" regex = "1.11.1" -rustc-hash = "2.1.0" -thread_local = "1.1.8" [profile.release] lto = true From 324923b284d5afdc6b8ae8f3229f732854d9b5bb Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 5 Dec 2025 18:02:17 -0800 Subject: [PATCH 32/66] utils: add RangeSet early implementation based on RBTree --- Cargo.lock | 19 ++++++ utils/grid/Cargo.toml | 2 +- utils/misc/Cargo.lock | 19 ++++++ utils/misc/Cargo.toml | 3 +- utils/misc/src/lib.rs | 3 + utils/misc/src/range.rs | 124 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 168 insertions(+), 2 deletions(-) create mode 100644 utils/misc/src/range.rs diff --git a/Cargo.lock b/Cargo.lock index f20472c..1ec1aff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -202,6 +202,15 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[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" @@ -233,10 +242,20 @@ version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" +[[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", ] diff --git a/utils/grid/Cargo.toml b/utils/grid/Cargo.toml index 6507dcf..a95c55e 100644 --- a/utils/grid/Cargo.toml +++ b/utils/grid/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "grid" version = "0.1.0" -edition = "2021" +edition = "2024" [dependencies] diff --git a/utils/misc/Cargo.lock b/utils/misc/Cargo.lock index f6716d7..6dfd16a 100644 --- a/utils/misc/Cargo.lock +++ b/utils/misc/Cargo.lock @@ -8,10 +8,29 @@ 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", ] diff --git a/utils/misc/Cargo.toml b/utils/misc/Cargo.toml index 3704ff9..cf51035 100644 --- a/utils/misc/Cargo.toml +++ b/utils/misc/Cargo.toml @@ -1,7 +1,8 @@ [package] name = "misc" version = "0.1.0" -edition = "2021" +edition = "2024" [dependencies] +intrusive-collections = "0.9.7" num-traits = "0.2.19" diff --git a/utils/misc/src/lib.rs b/utils/misc/src/lib.rs index 46d447f..97836e2 100644 --- a/utils/misc/src/lib.rs +++ b/utils/misc/src/lib.rs @@ -2,6 +2,8 @@ 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(); @@ -105,6 +107,7 @@ mod tests { #[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/utils/misc/src/range.rs b/utils/misc/src/range.rs new file mode 100644 index 0000000..b2d44f8 --- /dev/null +++ b/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)]) + } +} From 57932373d6abdfabc76ba4a733da83a877b6e0f3 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 5 Dec 2025 18:02:44 -0800 Subject: [PATCH 33/66] day5: add RangeSet based impl --- src/day5.rs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/day5.rs b/src/day5.rs index 50958e0..67418e5 100644 --- a/src/day5.rs +++ b/src/day5.rs @@ -87,7 +87,7 @@ impl RangeSet { } } -#[aoc_generator(day5, part1)] +#[aoc_generator(day5)] fn parse(input: &str) -> Database { let mut fresh_ingredients = Vec::new(); let mut available_ingredients = Vec::new(); @@ -122,7 +122,7 @@ fn part1(input: &Database) -> u64 { .count() as u64 } -#[aoc_generator(day5, part2)] +#[aoc_generator(day5, part2, Naive)] fn parse2(input: &str) -> Database2 { let mut fresh_ingredients = Vec::new(); for line in input.lines() { @@ -135,7 +135,7 @@ fn parse2(input: &str) -> Database2 { Database2 { fresh_ingredients } } -#[aoc(day5, part2)] +#[aoc(day5, part2, Naive)] fn part2(input: &Database2) -> u64 { let mut all_ingredients = RangeSet::new(); for r in &input.fresh_ingredients { @@ -145,6 +145,15 @@ fn part2(input: &Database2) -> u64 { 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::*; @@ -170,4 +179,9 @@ mod tests { fn part2_example() { assert_eq!(part2(&parse2(EXAMPLE)), 14); } + + #[test] + fn part2_set_example() { + assert_eq!(part2_rangeset(&parse(EXAMPLE)), 14); + } } From bacbf3617124cb4c7812185155a83c711655a7c7 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 5 Dec 2025 23:48:15 -0800 Subject: [PATCH 34/66] day6: both solutions --- .aoc_tiles/tiles/2025/06.png | Bin 0 -> 7800 bytes README.md | 5 +- src/day6.rs | 176 +++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 4 files changed, 181 insertions(+), 1 deletion(-) create mode 100644 .aoc_tiles/tiles/2025/06.png create mode 100644 src/day6.rs diff --git a/.aoc_tiles/tiles/2025/06.png b/.aoc_tiles/tiles/2025/06.png new file mode 100644 index 0000000000000000000000000000000000000000..e8d999c04f4a6707424fe520b073bcfff28d6b47 GIT binary patch literal 7800 zcmXAubyQT}*Tyf6fFMYBNe&%KcSzU3&>fO09nvKY3P{TUA_F4~I;b#!G)UJ_5(3iF z2t&T}{k?15`s1v1@7?E|y`RssUmF={-6vrr0RZ6sQ*CtkMDtc zxsmegRi0Odpq16gZ|9MyZ-Y^HY>c;SN-;Vyj*ySW-#+bQ|RuDge)asEGsgW@Aj zs%-#xP^X$^-t93xBRtBhN@2)?mrErQKcUET0Q(vhc0Qx@JJQO+`{UwG;RLWiHS{nT~~$~bRbc1%yB0!&?OpiXg>VOg5ATDg3hLLh@3#-IR+)0WsMHvYDO5w37b?(`*t`O5u=sCekvK4D)WiW)zf2l|)+R+NSm%5(L4bF+A4?XLc@YVb#+xTJ>Dvwi5i2LS+E2!3ly0|26A(d^+1 zwEMWH9?#8jXe(e(jPPj>Wcu2n(sBTR{pF*w3w;hD@#6eZFIz;%)kLNT?7_Edy1N8J z4#;%Cx-GJYzi<|Tc~F_NBbO3-Uut+MfB6Hke85@!-8C;pz0z%_HbY7d^K57dJd&{( zX2H_#Osgy`nD+kHGMPS;XCd;Rz`oAPF&!d2UrIW->-OtZrs8uNXXDxwf|-_+sMQ!s z08o3A*_BGfc4@$(tF-4FW%4^IaQV{uBt?I`Hj1WFGR$Jz%W73&6T2Lf-5&icI-{Vt z-HzIvG_`ej`OTtgdcoW~?VsJsMEAb!NcukjxQJuM(fJ3V)_4(BD;Y-PH)Yw+{UwOv zT!QXQ>mZ_Q%uHC8p)J%rivq7Ze8mKU3p06kzX=(BVR8K0sHU6S(&(*BcG`2;#O@iH z{-1{&$PNMRM0$9}aFWww!*K#tNj9=BSQD!aX2Y;kV$ zVOz9!wD=wSf9uy{E4It6dp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::{aoc, aoc_generator}; +use grid::Grid; +use itertools::Itertools; +use std::{ + fmt::{Display, Write}, + iter::repeat_n, +}; + +#[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 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)] +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)] +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::() +} + +#[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); + } +} diff --git a/src/lib.rs b/src/lib.rs index 1bb311f..fb58f07 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ mod day2; mod day3; mod day4; mod day5; +mod day6; use aoc_runner_derive::aoc_lib; From c8e03e6d6d782031dacb5291a05304b5c83cf700 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Sat, 6 Dec 2025 00:44:36 -0800 Subject: [PATCH 35/66] day6: state machine solution, much cleaner --- src/day6.rs | 114 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 109 insertions(+), 5 deletions(-) diff --git a/src/day6.rs b/src/day6.rs index 264f7b0..7ff071e 100644 --- a/src/day6.rs +++ b/src/day6.rs @@ -1,9 +1,11 @@ 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)] @@ -22,6 +24,16 @@ impl From<&str> for Op { } } +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 { @@ -32,7 +44,7 @@ impl Display for Op { } impl Op { - fn f(&self, lhs: u64, rhs: u64) -> u64 { + fn f(&self, lhs: &u64, rhs: &u64) -> u64 { match self { Op::Add => lhs + rhs, Op::Mul => lhs * rhs, @@ -71,7 +83,7 @@ fn part1((grid, ops): &(Grid, Vec)) -> u64 { grid.col_iter(x as i64) .unwrap() .cloned() - .reduce(|l, r| ops[x].f(l, r)) + .reduce(|l, r| ops[x].f(&l, &r)) .unwrap() }) .sum() @@ -85,7 +97,7 @@ fn part1((grid, ops): &(Grid, Vec)) -> u64 { // .collect() // } -#[aoc_generator(day6, part2)] +#[aoc_generator(day6, part2, Spaghett)] fn parse2(input: &str) -> (Grid>, Vec) { let mut rows = input.lines().collect_vec(); let ops = rows.pop().unwrap(); @@ -126,7 +138,7 @@ fn parse2(input: &str) -> (Grid>, Vec) { (grid, ops) } -#[aoc(day6, part2)] +#[aoc(day6, part2, Spaghett)] fn part2((grid, ops): &(Grid>, Vec)) -> u64 { let mut columns = Vec::new(); for col in 0..grid.width() { @@ -151,10 +163,97 @@ fn part2((grid, ops): &(Grid>, Vec)) -> u64 { columns .iter() .enumerate() - .map(|(col, v)| v.iter().cloned().reduce(|l, r| ops[col].f(l, r)).unwrap()) + .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::*; @@ -173,4 +272,9 @@ mod tests { fn part2_example() { assert_eq!(part2(&parse2(EXAMPLE)), 3263827); } + + #[test] + fn part2_walk_example() { + assert_eq!(part2_walk(&parse2_walk(EXAMPLE)), 3263827); + } } From 86fd61aa15494ad0d75f304920ab35a70da4200a Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Sat, 6 Dec 2025 21:00:19 -0800 Subject: [PATCH 36/66] day7: boilerplate --- .pre-commit-config.yaml | 2 +- src/day7.rs | 32 ++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 src/day7.rs diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c354440..40583a7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,7 +9,7 @@ repos: language: system - id: rust-clippy name: Rust clippy - entry: cargo clippy --lib --all-features --tests -- -D warnings + entry: cargo clippy --lib --all-features --tests -- pass_filenames: false types: [file, rust] language: system diff --git a/src/day7.rs b/src/day7.rs new file mode 100644 index 0000000..ff15339 --- /dev/null +++ b/src/day7.rs @@ -0,0 +1,32 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +#[aoc_generator(day7)] +fn parse(input: &str) -> String { + todo!() +} + +#[aoc(day7, part1)] +fn part1(input: &str) -> u64 { + 0 +} + +#[aoc(day7, part2)] +fn part2(input: &str) -> u64 { + 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = ""; + + #[test] + fn part1_example() { + assert_eq!(part1(&parse(EXAMPLE)), 0); + } + + #[test] + fn part2_example() { + assert_eq!(part2(&parse(EXAMPLE)), 0); + } +} diff --git a/src/lib.rs b/src/lib.rs index fb58f07..e40860b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ mod day3; mod day4; mod day5; mod day6; +mod day7; use aoc_runner_derive::aoc_lib; From f99f4e766ad9cfffa834bafd44d2da986e9a4008 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Sat, 6 Dec 2025 21:17:04 -0800 Subject: [PATCH 37/66] day7: part1 --- src/day7.rs | 52 +++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 7 deletions(-) diff --git a/src/day7.rs b/src/day7.rs index ff15339..f459c4b 100644 --- a/src/day7.rs +++ b/src/day7.rs @@ -1,16 +1,39 @@ +use std::collections::HashSet; +use std::str::FromStr; + use aoc_runner_derive::{aoc, aoc_generator}; +use grid::{AsCoord2d, Grid}; + #[aoc_generator(day7)] -fn parse(input: &str) -> String { - todo!() +fn parse(input: &str) -> Grid { + Grid::from_str(input).unwrap() +} + +// +fn emit_beams(grid: &mut Grid, pos: impl AsCoord2d) -> u64 { + match grid.get(&pos) { + None | Some(b'|') => 0, + Some(b'.') | Some(b'S') => { + grid.set(&pos, b'|'); + emit_beams(grid, &(pos.x(), pos.y() + 1)) + } + Some(b'^') => { + grid.set(&pos, b'|'); + 1 + emit_beams(grid, &(pos.x() - 1, pos.y())) + + emit_beams(grid, &(pos.x() + 1, pos.y())) + } + _ => panic!(), + } } #[aoc(day7, part1)] -fn part1(input: &str) -> u64 { - 0 +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: &str) -> u64 { +fn part2(input: &Grid) -> u64 { 0 } @@ -18,11 +41,26 @@ fn part2(input: &str) -> u64 { mod tests { use super::*; - const EXAMPLE: &str = ""; + const EXAMPLE: &str = ".......S....... +............... +.......^....... +............... +......^.^...... +............... +.....^.^.^..... +............... +....^.^...^.... +............... +...^.^...^.^... +............... +..^...^.....^.. +............... +.^.^.^.^.^...^. +..............."; #[test] fn part1_example() { - assert_eq!(part1(&parse(EXAMPLE)), 0); + assert_eq!(part1(&parse(EXAMPLE)), 21); } #[test] From 8f3ac2aacd85f04b6fc10dc5b1b0e2f35da95edd Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Sun, 7 Dec 2025 00:10:29 -0800 Subject: [PATCH 38/66] day7: part2 + clippies --- .aoc_tiles/tiles/2025/07.png | Bin 0 -> 7190 bytes README.md | 5 ++- src/day7.rs | 61 +++++++++++++++++++++++++++-------- 3 files changed, 51 insertions(+), 15 deletions(-) create mode 100644 .aoc_tiles/tiles/2025/07.png diff --git a/.aoc_tiles/tiles/2025/07.png b/.aoc_tiles/tiles/2025/07.png new file mode 100644 index 0000000000000000000000000000000000000000..3b103b6ef478cf26b0ea340bb286b1ef1e263b34 GIT binary patch literal 7190 zcmV+x9O>hUP)WB`%P@Ct&8z z{pP>-n>%;z^8e7#?|usM1xb>5UrP|gL*4@Bg%^eOK`Z44kT*|ZEmLbB@-7%}KEhhQ z);{E2FkV!6w0PI|iLwUa5sqaTGMosyBO^D+@ji}ambJAHc^8Zql}HBwfM5jGnNXdH zC~r&zTw^B=f_#aWg0=JHUG@6UZod0g>aS_V`tqGGiY{U4B%6p)0e8~thz$26BmVSk zF@x2*aj&MN761_J?eJauTAEi8mPk2g7Z%5H3=JVDfFS+=ZnD=t{iDIp-bqFR^JGug(}K~w|)08tSYyABM0`Kx)d%Exjn2_UzP8CVJ4T78g)@w+~WWMpc-w_+Fgd47DTP30xtK}lK_CK$6w=9 z(y>V2@BUL~Fjc?wuc`bdzWm>0$O{0deD+OLYvd2QzWFRVdMllL*_CqK<3Ml~sxv__ zGJ7W#P1>sF=veRl;{{7hRUo&p03b;+Hqce}o#!BE<`Ys^-VpaVRK}v3eXpa0od9Sv# zE?fRNgvGOREJKrF>}~^t=}Z7X6?jE4K=IGO&b9KFoJ?i_F{TV>0__52`YH|A`^?K?Nvpa zo=kYB(!V66c}urH10z`aaolLF-S;||Oi1J}B`hH;jN+-^9Ls9U>eQCv)Dh>!!@gS= zRc3qDfyD3+n(&25h|adPVT z2P~Zc0FV>?f$p>XZ~45&`nCG1m9Ea?rQ7z4P8Dz5%Th7v{Id>_G7OXYji?Aj(CbV_ z0%}W1>TlfZ@ZR`_W0|;j%6;v$C?5`R5_g}D0#FsA)|%Ju5*|qeT-g%SbTWUYOs@po zXwz1%^!J<-)^tWy6>oWB<*RR*8rNmWL~kzJ@$7WR5jH`IPN~dxL+z@Z`RDFq0RV(A zH~>IoykA$*kTGTY+mB=BJfILfBV`yRaO4v>i_^z=N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q&06=v7_VDk2Cgf!jaZ!kJAR(;uQs(HSzvpbQ|FWrhtFCU1 zA`c<}0EQw1cdmJ^pXCQphxVYk+IuJc{}Lk^Da#+ z>uO`D(y4qGl;|8GA7LEshp zd0!Y-AqtNdRcj?8tQMZV86o!bzA&sQ6acSzg?MUQBEo6`*eerr{Jbw1E04n96)mgc zk#W?!Fzl5H^ntQ=p1dNctz|{6JJizMF&ns70y1F&y)!!Na;vL*lVqEndO>q@V#oX7=`tPph z#`I?U`aRmxT12f)ggm5k)Z24DJ&I1@sftY|BqFThI4(NHuebDE{E}lC2u37kBbKJU zGIRqpi+dcRtpQ+ZSbINsvqf0tc|-kkqNBxKV*mhhyiYpd%2KvhCa;n{76eUSI-1e3 zLNXj6oueh~PvOR*$mE^a^q6QAXNg$*kaxj&(`?tPX~_kt4r0uh?LyU2R>p z6#x*O8una2!^hiMI@UhqT`*o*!XimB=k8;Up?$p_zTOT9LA50{MQe6eKlQ`mFMbI{ z^N$HwFs1we^3GYtZdtdd>cxN2)wU{Sg;5;28y1yg=*Z;2#OaSA2sV_}ryLIWwKhDx7gM{>g&A}bB!lLJ{ZHTtGBaBDy}5-oDc<8$`2s# z93P~?zRUW$)|7h|`K+Fvb20CvxoM+r{T|$4VJI@;bxeKzq0j@Td=y?OKY+Y*`dI$! zr~KDXWn>N9xf+lRniX{nMIA#jStU@ArThT$X5K1TsMbE@T`=AZ!YW{EAM!33uUJ@x zZS6ze1>=Q=e)rRbXBFWgZ{hLI@$OV07*qoM6N<$g8Jp;Pyhe` literal 0 HcmV?d00001 diff --git a/README.md b/README.md index 05149de..7a45bf0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

- 2025 - 12 ⭐ - Rust + 2025 - 14 ⭐ - Rust

@@ -20,4 +20,7 @@ + + + diff --git a/src/day7.rs b/src/day7.rs index f459c4b..c25fefd 100644 --- a/src/day7.rs +++ b/src/day7.rs @@ -1,26 +1,19 @@ -use std::collections::HashSet; -use std::str::FromStr; - use aoc_runner_derive::{aoc, aoc_generator}; use grid::{AsCoord2d, Grid}; +use itertools::Itertools; +use std::str::FromStr; #[aoc_generator(day7)] fn parse(input: &str) -> Grid { Grid::from_str(input).unwrap() } -// fn emit_beams(grid: &mut Grid, pos: impl AsCoord2d) -> u64 { - match grid.get(&pos) { + match grid.set(&pos, b'|') { None | Some(b'|') => 0, - Some(b'.') | Some(b'S') => { - grid.set(&pos, b'|'); - emit_beams(grid, &(pos.x(), pos.y() + 1)) - } + Some(b'.') | Some(b'S') => emit_beams(grid, (pos.x(), pos.y() + 1)), Some(b'^') => { - grid.set(&pos, b'|'); - 1 + emit_beams(grid, &(pos.x() - 1, pos.y())) - + emit_beams(grid, &(pos.x() + 1, pos.y())) + 1 + emit_beams(grid, (pos.x() - 1, pos.y())) + emit_beams(grid, (pos.x() + 1, pos.y())) } _ => panic!(), } @@ -34,13 +27,48 @@ fn part1(input: &Grid) -> u64 { #[aoc(day7, part2)] fn part2(input: &Grid) -> u64 { - 0 + let mut grid = Grid::same_shape(input, 0u64); + grid.set(&input.find(&b'S').unwrap(), 1); + + // Start row is already set up + for y in 1..grid.height() { + let row_above = grid.row_iter(y as i64 - 1).unwrap().cloned().collect_vec(); + // for each column with non-zero counts in the row above get its column index and count + for (x, n) in row_above.into_iter().enumerate().filter(|(_i, n)| *n > 0) { + match input.get(&(x, y)) { + None => panic!("How did we end up outside the grid?"), + // if our current position is a caret, add that count to our neighbours + Some(b'^') => { + grid.set(&(x - 1, y), grid.get(&(x - 1, y)).unwrap() + n); + grid.set(&(x + 1, y), grid.get(&(x + 1, y)).unwrap() + n); + } + // if our current position is a . add that count here + Some(b'.') => { + grid.set(&(x, y), grid.get(&(x, y)).unwrap() + n); + } + _ => panic!(), + } + } + } + + grid.row(grid.height() as i64 - 1) + .unwrap() + .iter() + .sum::() } #[cfg(test)] mod tests { use super::*; + const TRIVIAL_EXAMPLE: &str = "...S... +....... +...^... +..^.^.^ +...^.^. +....... +......."; + const EXAMPLE: &str = ".......S....... ............... .......^....... @@ -65,6 +93,11 @@ mod tests { #[test] fn part2_example() { - assert_eq!(part2(&parse(EXAMPLE)), 0); + assert_eq!(part2(&parse(EXAMPLE)), 40); + } + + #[test] + fn part2_trivial_example() { + assert_eq!(part2(&parse(TRIVIAL_EXAMPLE)), 7); } } From 30644bcbfc61a59071347270cf0620a0c66c7fb3 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Sun, 7 Dec 2025 00:27:23 -0800 Subject: [PATCH 39/66] day7: remember to use some convenience functions from my grid --- src/day7.rs | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/day7.rs b/src/day7.rs index c25fefd..982ce4c 100644 --- a/src/day7.rs +++ b/src/day7.rs @@ -1,5 +1,5 @@ use aoc_runner_derive::{aoc, aoc_generator}; -use grid::{AsCoord2d, Grid}; +use grid::{Coord2d, Grid}; use itertools::Itertools; use std::str::FromStr; @@ -8,13 +8,11 @@ fn parse(input: &str) -> Grid { Grid::from_str(input).unwrap() } -fn emit_beams(grid: &mut Grid, pos: impl AsCoord2d) -> u64 { +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.x(), pos.y() + 1)), - Some(b'^') => { - 1 + emit_beams(grid, (pos.x() - 1, pos.y())) + emit_beams(grid, (pos.x() + 1, pos.y())) - } + 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!(), } } @@ -39,12 +37,12 @@ fn part2(input: &Grid) -> u64 { None => panic!("How did we end up outside the grid?"), // if our current position is a caret, add that count to our neighbours Some(b'^') => { - grid.set(&(x - 1, y), grid.get(&(x - 1, y)).unwrap() + n); - grid.set(&(x + 1, y), grid.get(&(x + 1, y)).unwrap() + n); + grid.increment(&(x - 1, y), n); + grid.increment(&(x + 1, y), n); } // if our current position is a . add that count here Some(b'.') => { - grid.set(&(x, y), grid.get(&(x, y)).unwrap() + n); + grid.increment(&(x, y), n); } _ => panic!(), } From ba2cfffc3f24f23e5e9099d193ebce469ae9f4d4 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Sun, 7 Dec 2025 01:14:29 -0800 Subject: [PATCH 40/66] day7: optimize away needing a second grid --- src/day7.rs | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/src/day7.rs b/src/day7.rs index 982ce4c..64150bf 100644 --- a/src/day7.rs +++ b/src/day7.rs @@ -1,6 +1,5 @@ use aoc_runner_derive::{aoc, aoc_generator}; use grid::{Coord2d, Grid}; -use itertools::Itertools; use std::str::FromStr; #[aoc_generator(day7)] @@ -25,34 +24,36 @@ fn part1(input: &Grid) -> u64 { #[aoc(day7, part2)] fn part2(input: &Grid) -> u64 { - let mut grid = Grid::same_shape(input, 0u64); - grid.set(&input.find(&b'S').unwrap(), 1); + 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..grid.height() { - let row_above = grid.row_iter(y as i64 - 1).unwrap().cloned().collect_vec(); - // for each column with non-zero counts in the row above get its column index and count - for (x, n) in row_above.into_iter().enumerate().filter(|(_i, n)| *n > 0) { + 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)) { - None => panic!("How did we end up outside the grid?"), // if our current position is a caret, add that count to our neighbours Some(b'^') => { - grid.increment(&(x - 1, y), n); - grid.increment(&(x + 1, y), n); + 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 . add that count here - Some(b'.') => { - grid.increment(&(x, y), n); - } - _ => panic!(), + // 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?"), } } } - grid.row(grid.height() as i64 - 1) - .unwrap() - .iter() - .sum::() + col_counts.iter().sum::() } #[cfg(test)] From 95b6c0ed9efdf2a3f513560330d678dc84e3d3a8 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Sun, 7 Dec 2025 21:00:14 -0800 Subject: [PATCH 41/66] day8: boilerplate --- src/day8.rs | 33 +++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 2 files changed, 34 insertions(+) create mode 100644 src/day8.rs diff --git a/src/day8.rs b/src/day8.rs new file mode 100644 index 0000000..39c283e --- /dev/null +++ b/src/day8.rs @@ -0,0 +1,33 @@ +use aoc_runner_derive::{aoc, aoc_generator}; + +#[aoc_generator(day8)] +fn parse(input: &str) -> String { + todo!() +} + +#[aoc(day8, part1)] +fn part1(input: &str) -> u64 { + 0 +} + +#[aoc(day8, part2)] +fn part2(input: &str) -> u64 { + 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = ""; + + #[test] + fn part1_example() { + assert_eq!(part1(&parse(EXAMPLE)), 0); + } + + #[test] + fn part2_example() { + assert_eq!(part2(&parse(EXAMPLE)), 0); + } +} diff --git a/src/lib.rs b/src/lib.rs index e40860b..ac83a67 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ mod day4; mod day5; mod day6; mod day7; +mod day8; use aoc_runner_derive::aoc_lib; From e97931acf33efcebe20ddeb755a91ebc7dcb63e4 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 8 Dec 2025 00:53:28 -0800 Subject: [PATCH 42/66] day8: non working progress --- src/day8.rs | 154 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 147 insertions(+), 7 deletions(-) diff --git a/src/day8.rs b/src/day8.rs index 39c283e..650693b 100644 --- a/src/day8.rs +++ b/src/day8.rs @@ -1,17 +1,138 @@ +use std::{ + collections::{HashMap, HashSet}, + f64, + fmt::{Display, Write}, + iter::repeat_n, +}; + use aoc_runner_derive::{aoc, aoc_generator}; +use cached::proc_macro::cached; +use itertools::Itertools; + +#[derive(Eq, PartialEq, Clone, Debug, Hash)] +struct Junction { + pos: (i64, i64, i64), +} + +fn distance(a: &Junction, b: &Junction) -> f64 { + if a.pos == b.pos { + f64::MAX // ugh + } else { + (((a.pos.0 - b.pos.0).pow(2) + (a.pos.1 - b.pos.1).pow(2) + (a.pos.2 - b.pos.2).pow(2)) + as f64) + .sqrt() + } +} + +impl Junction { + fn distance(&self, other: &Junction) -> f64 { + 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>, + checked: HashSet<(usize, usize)>, +} + +impl Circuits { + fn find_circuit(&self, junction: usize) -> Option { + self.circuits + .iter() + .enumerate() + .find(|(_i, c)| c.contains(&junction)) + .map(|(i, _c)| i) + } + fn merge_circuits(&mut self, a: usize, b: usize) { + if a == b { + return; + } + let mut items = Vec::new(); + std::mem::swap(&mut items, &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.checked.insert((a, b)); + + match (a_circuit, b_circuit) { + (None, None) => self.circuits.push(vec![a, b]), // both are unconnected + (Some(a_circuit), Some(b_circuit)) => { + self.merge_circuits(a_circuit, b_circuit); // both are already in circuits, merge them + } + (Some(a_circuit), None) => self.circuits[a_circuit].push(b), // one is in a circuit, so add the other to the existing circuit + (None, Some(b_circuit)) => self.circuits[b_circuit].push(a), + }; + } +} #[aoc_generator(day8)] -fn parse(input: &str) -> String { - todo!() +fn parse(input: &str) -> Circuits { + let junctions = input.lines().map(|l| l.into()).collect_vec(); + + Circuits { + junctions, + circuits: Vec::new(), + checked: HashSet::new(), + } } #[aoc(day8, part1)] -fn part1(input: &str) -> u64 { - 0 +fn part1(input: &Circuits) -> u64 { + let mut circuits = input.clone(); + for (a, b, d) in circuits + .junctions + .iter() + .enumerate() + .combinations(2) + .map(|p| (p[0].0, p[1].0, p[0].1.distance(p[1].1))) + .sorted_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) + .take(1000) + { + println!( + "connecting {} <-> {} = {d}", + circuits.junctions[a], circuits.junctions[b] + ); + circuits.connect(a, b) + } + println!("{:?}", circuits.circuits); + circuits + .circuits + .iter() + .take(3) + .map(|c| c.len()) + .reduce(|a, b| a * b) + .unwrap() as u64 } #[aoc(day8, part2)] -fn part2(input: &str) -> u64 { +fn part2(input: &Circuits) -> u64 { 0 } @@ -19,11 +140,30 @@ fn part2(input: &str) -> u64 { mod tests { use super::*; - const EXAMPLE: &str = ""; + 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(&parse(EXAMPLE)), 0); + assert_eq!(part1(&parse(EXAMPLE)), 40); } #[test] From 41f9e971ee5604c4aeccdc5330d4a10b179ba5ed Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 8 Dec 2025 00:59:29 -0800 Subject: [PATCH 43/66] day8: part1 solution --- src/day8.rs | 33 +++++++++++++-------------------- 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/src/day8.rs b/src/day8.rs index 650693b..59a12a5 100644 --- a/src/day8.rs +++ b/src/day8.rs @@ -1,12 +1,6 @@ -use std::{ - collections::{HashMap, HashSet}, - f64, - fmt::{Display, Write}, - iter::repeat_n, -}; +use std::{f64, fmt::Display}; use aoc_runner_derive::{aoc, aoc_generator}; -use cached::proc_macro::cached; use itertools::Itertools; #[derive(Eq, PartialEq, Clone, Debug, Hash)] @@ -55,7 +49,6 @@ impl From<&str> for Junction { struct Circuits { junctions: Vec, circuits: Vec>, - checked: HashSet<(usize, usize)>, } impl Circuits { @@ -79,7 +72,6 @@ impl Circuits { fn connect(&mut self, a: usize, b: usize) { let a_circuit = self.find_circuit(a); let b_circuit = self.find_circuit(b); - self.checked.insert((a, b)); match (a_circuit, b_circuit) { (None, None) => self.circuits.push(vec![a, b]), // both are unconnected @@ -99,38 +91,39 @@ fn parse(input: &str) -> Circuits { Circuits { junctions, circuits: Vec::new(), - checked: HashSet::new(), } } -#[aoc(day8, part1)] -fn part1(input: &Circuits) -> u64 { +fn part1_impl(input: &Circuits, n: usize) -> u64 { let mut circuits = input.clone(); - for (a, b, d) in circuits + for (a, b, _d) in circuits .junctions .iter() .enumerate() .combinations(2) .map(|p| (p[0].0, p[1].0, p[0].1.distance(p[1].1))) .sorted_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) - .take(1000) + .take(n) { - println!( - "connecting {} <-> {} = {d}", - circuits.junctions[a], circuits.junctions[b] - ); circuits.connect(a, b) } - println!("{:?}", circuits.circuits); + circuits .circuits .iter() + .sorted_by_key(|c| c.len()) + .rev() .take(3) .map(|c| c.len()) .reduce(|a, b| a * b) .unwrap() as u64 } +#[aoc(day8, part1)] +fn part1(input: &Circuits) -> u64 { + part1_impl(input, 1000) +} + #[aoc(day8, part2)] fn part2(input: &Circuits) -> u64 { 0 @@ -163,7 +156,7 @@ mod tests { #[test] fn part1_example() { - assert_eq!(part1(&parse(EXAMPLE)), 40); + assert_eq!(part1_impl(&parse(EXAMPLE), 10), 40); } #[test] From c97f31e0fdc9e037d08207eadddc59dc0b468033 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 8 Dec 2025 01:04:14 -0800 Subject: [PATCH 44/66] day8: part2 solution --- src/day8.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/day8.rs b/src/day8.rs index 59a12a5..9486089 100644 --- a/src/day8.rs +++ b/src/day8.rs @@ -126,7 +126,23 @@ fn part1(input: &Circuits) -> u64 { #[aoc(day8, part2)] fn part2(input: &Circuits) -> u64 { - 0 + let mut circuits = input.clone(); + circuits.circuits = Vec::from_iter((0..circuits.junctions.len()).map(|i| vec![i])); + for (a, b, _d) in circuits + .junctions + .iter() + .enumerate() + .combinations(2) + .map(|p| (p[0].0, p[1].0, p[0].1.distance(p[1].1))) + .sorted_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) + { + circuits.connect(a, b); + if circuits.circuits.len() == 1 { + return (circuits.junctions[a].pos.0 * circuits.junctions[b].pos.0) as u64; + } + } + + panic!() } #[cfg(test)] @@ -161,6 +177,6 @@ mod tests { #[test] fn part2_example() { - assert_eq!(part2(&parse(EXAMPLE)), 0); + assert_eq!(part2(&parse(EXAMPLE)), 25272); } } From 09ca512fcc9c853ed586ff1b420f49d9a185b972 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 8 Dec 2025 01:50:39 -0800 Subject: [PATCH 45/66] day8: some cleanups --- .aoc_tiles/tiles/2025/08.png | Bin 0 -> 7752 bytes README.md | 5 ++++- src/day8.rs | 22 ++++++++-------------- 3 files changed, 12 insertions(+), 15 deletions(-) create mode 100644 .aoc_tiles/tiles/2025/08.png diff --git a/.aoc_tiles/tiles/2025/08.png b/.aoc_tiles/tiles/2025/08.png new file mode 100644 index 0000000000000000000000000000000000000000..8c4293a89bd4f6895f115bb23d78ac402d09a8d2 GIT binary patch literal 7752 zcmV-O9=G9%P)JpK3Em_~0tAQ~SS`08ZW}VTGH{7s;rKCg{DXnkEX)j*vM^s{2on_D_Yveyo<(*2$TZ=K(Gwa z7!Zv?<)}}EJYy%`0mTw82WjWY+x+Uk-1+s-*gp*on;cKP$a{p!q^VSb2zk?fS8TW^ z9Sdexi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pspKQK$tntgb$JbAlh|eQ{V> ztO8zR13%JkCK=C{VRaSAD-!d~f4s7!eHgqvw<-oXt=_9cUXef^DQV})%Y(vPW@*`_ zFqc;Bdl>-Wy?!zskL1g+O1Os99X={dhs5mDtY3@3^f* zX&06^>32<>e!uR;zhSbfGRT=>m2eMY23x4-oYGO3!NdABZLY810yJ%Ddq!caNM;>( z6Xq3<Z!Y)>4Gj@*rOe~GAdY(#Ddf~ybx zm`ubc&wfY}3AxU!uiaqVdT`?8yE$2lz_M*+Cc`Qb@&C!w4`SY0DzC*!^iK2J`Z$E_TEwRag z#Pk@?inC0leayRPykZqAMWg@#@w_Q<=#ekqFg9$~IoFw+w*vs;Q^UTSXPA6D%SYPB zyo<&wO0jSpFBk)!CNqKF?m%xhBtz8pYRmd3st)~l_>=#E;t~!qXY&^Q?6PX*N04{U zCbX$_U*(H`r*XDOWrY!pjrBv5nb_q0iPP^x5UeY!F7ka>S1Uh)yqpmWf^_wpAq3Ud zw#J5gB(a*Bwplkl8R)%~@QkM-0T{*1>vmFUA}J;H92cvsl^;RgIWb7X_bzK|TB7%_ zNoDo*oK5&Ajg4D0oAzNk6G`AHziaCF@3;{-#bfog@*~JQXO0!Tc`A7GR8H2=z_sic z$y~%;Lvh!TNLB%?%2s{^d2=5XT&>bR=3O-29E!DyrG3o1XuN#ITHVq<=3O*iXz1;K zUVK&_9`mj~-Z^pJ7mbyR$GoeOcTSx5MPp_0n0K}E!b`%+;4$wi=KX&h3jZ$#(QJAE O0000

- 2025 - 14 ⭐ - Rust + 2025 - 16 ⭐ - Rust

@@ -23,4 +23,7 @@ + + + diff --git a/src/day8.rs b/src/day8.rs index 9486089..6e6f24e 100644 --- a/src/day8.rs +++ b/src/day8.rs @@ -10,7 +10,7 @@ struct Junction { fn distance(a: &Junction, b: &Junction) -> f64 { if a.pos == b.pos { - f64::MAX // ugh + 0f64 } else { (((a.pos.0 - b.pos.0).pow(2) + (a.pos.1 - b.pos.1).pow(2) + (a.pos.2 - b.pos.2).pow(2)) as f64) @@ -52,12 +52,13 @@ struct Circuits { } impl Circuits { - fn find_circuit(&self, junction: usize) -> Option { + 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 { @@ -73,14 +74,7 @@ impl Circuits { let a_circuit = self.find_circuit(a); let b_circuit = self.find_circuit(b); - match (a_circuit, b_circuit) { - (None, None) => self.circuits.push(vec![a, b]), // both are unconnected - (Some(a_circuit), Some(b_circuit)) => { - self.merge_circuits(a_circuit, b_circuit); // both are already in circuits, merge them - } - (Some(a_circuit), None) => self.circuits[a_circuit].push(b), // one is in a circuit, so add the other to the existing circuit - (None, Some(b_circuit)) => self.circuits[b_circuit].push(a), - }; + self.merge_circuits(a_circuit, b_circuit); // both are already in circuits, merge them } } @@ -89,8 +83,8 @@ 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, - circuits: Vec::new(), } } @@ -100,8 +94,8 @@ fn part1_impl(input: &Circuits, n: usize) -> u64 { .junctions .iter() .enumerate() - .combinations(2) - .map(|p| (p[0].0, p[1].0, p[0].1.distance(p[1].1))) + .tuple_combinations() + .map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.distance(b))) .sorted_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) .take(n) { @@ -127,7 +121,7 @@ fn part1(input: &Circuits) -> u64 { #[aoc(day8, part2)] fn part2(input: &Circuits) -> u64 { let mut circuits = input.clone(); - circuits.circuits = Vec::from_iter((0..circuits.junctions.len()).map(|i| vec![i])); + for (a, b, _d) in circuits .junctions .iter() From db214ca95877f8425aa3db9f20126d5b98d21e65 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 8 Dec 2025 02:55:04 -0800 Subject: [PATCH 46/66] day8: we don't need stable sort and unstable is faster --- .cargo/config.toml | 2 ++ src/day8.rs | 22 ++++++++++------------ 2 files changed, 12 insertions(+), 12 deletions(-) create mode 100644 .cargo/config.toml diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..ddff440 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[build] +rustflags = ["-C", "target-cpu=native"] diff --git a/src/day8.rs b/src/day8.rs index 6e6f24e..95dc498 100644 --- a/src/day8.rs +++ b/src/day8.rs @@ -3,17 +3,16 @@ use std::{f64, fmt::Display}; use aoc_runner_derive::{aoc, aoc_generator}; use itertools::Itertools; -#[derive(Eq, PartialEq, Clone, Debug, Hash)] +#[derive(PartialEq, Clone, Debug)] struct Junction { - pos: (i64, i64, i64), + pos: (f64, f64, f64), } fn distance(a: &Junction, b: &Junction) -> f64 { if a.pos == b.pos { 0f64 } else { - (((a.pos.0 - b.pos.0).pow(2) + (a.pos.1 - b.pos.1).pow(2) + (a.pos.2 - b.pos.2).pow(2)) - as f64) + ((a.pos.0 - b.pos.0).powi(2) + (a.pos.1 - b.pos.1).powi(2) + (a.pos.2 - b.pos.2).powi(2)) .sqrt() } } @@ -64,8 +63,7 @@ impl Circuits { if a == b { return; } - let mut items = Vec::new(); - std::mem::swap(&mut items, &mut self.circuits[b]); + let mut items = std::mem::take(&mut self.circuits[b]); self.circuits[a].append(&mut items); self.circuits.remove(b); } @@ -96,7 +94,7 @@ fn part1_impl(input: &Circuits, n: usize) -> u64 { .enumerate() .tuple_combinations() .map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.distance(b))) - .sorted_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) + .sorted_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) .take(n) { circuits.connect(a, b) @@ -105,10 +103,10 @@ fn part1_impl(input: &Circuits, n: usize) -> u64 { circuits .circuits .iter() - .sorted_by_key(|c| c.len()) + .map(|c| c.len()) + .sorted_unstable() .rev() .take(3) - .map(|c| c.len()) .reduce(|a, b| a * b) .unwrap() as u64 } @@ -126,9 +124,9 @@ fn part2(input: &Circuits) -> u64 { .junctions .iter() .enumerate() - .combinations(2) - .map(|p| (p[0].0, p[1].0, p[0].1.distance(p[1].1))) - .sorted_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) + .tuple_combinations() + .map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.distance(b))) + .sorted_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) { circuits.connect(a, b); if circuits.circuits.len() == 1 { From b5f6bcde11292ac5814bfdcd6727fae6038acf8d Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 8 Dec 2025 12:19:17 -0800 Subject: [PATCH 47/66] day8: avoid floats for performance --- src/day8.rs | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/day8.rs b/src/day8.rs index 95dc498..a0b31ea 100644 --- a/src/day8.rs +++ b/src/day8.rs @@ -1,25 +1,26 @@ -use std::{f64, fmt::Display}; +use std::fmt::Display; use aoc_runner_derive::{aoc, aoc_generator}; use itertools::Itertools; #[derive(PartialEq, Clone, Debug)] struct Junction { - pos: (f64, f64, f64), + pos: (i64, i64, i64), } -fn distance(a: &Junction, b: &Junction) -> f64 { +fn squared_distance(a: &Junction, b: &Junction) -> u64 { if a.pos == b.pos { - 0f64 + 0 } else { - ((a.pos.0 - b.pos.0).powi(2) + (a.pos.1 - b.pos.1).powi(2) + (a.pos.2 - b.pos.2).powi(2)) - .sqrt() + (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 distance(&self, other: &Junction) -> f64 { - distance(self, other) + fn squared_distance(&self, other: &Junction) -> u64 { + squared_distance(self, other) } } @@ -93,8 +94,8 @@ fn part1_impl(input: &Circuits, n: usize) -> u64 { .iter() .enumerate() .tuple_combinations() - .map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.distance(b))) - .sorted_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) + .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) @@ -125,8 +126,8 @@ fn part2(input: &Circuits) -> u64 { .iter() .enumerate() .tuple_combinations() - .map(|((a_pos, a), (b_pos, b))| (a_pos, b_pos, a.distance(b))) - .sorted_unstable_by(|a, b| a.2.partial_cmp(&b.2).unwrap()) + .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 { From 522e10a3eab301ccc2e6c1c56bff3cc757eb93d9 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 8 Dec 2025 13:16:53 -0800 Subject: [PATCH 48/66] day8: add heap-based impl --- src/day8.rs | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 92 insertions(+), 3 deletions(-) diff --git a/src/day8.rs b/src/day8.rs index a0b31ea..f4ed5a6 100644 --- a/src/day8.rs +++ b/src/day8.rs @@ -1,4 +1,4 @@ -use std::fmt::Display; +use std::{cmp::Reverse, collections::BinaryHeap, fmt::Display}; use aoc_runner_derive::{aoc, aoc_generator}; use itertools::Itertools; @@ -112,12 +112,12 @@ fn part1_impl(input: &Circuits, n: usize) -> u64 { .unwrap() as u64 } -#[aoc(day8, part1)] +#[aoc(day8, part1, Sorted)] fn part1(input: &Circuits) -> u64 { part1_impl(input, 1000) } -#[aoc(day8, part2)] +#[aoc(day8, part2, Sorted)] fn part2(input: &Circuits) -> u64 { let mut circuits = input.clone(); @@ -138,6 +138,85 @@ fn part2(input: &Circuits) -> u64 { panic!() } +struct JunctionPair { + a: usize, + b: usize, + d: u64, +} +impl Eq for JunctionPair {} +impl PartialEq for JunctionPair { + fn eq(&self, other: &Self) -> bool { + self.d == other.d + } +} +impl PartialOrd for JunctionPair { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.d.cmp(&other.d)) + } +} +impl Ord for JunctionPair { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.d.cmp(&other.d) + } +} + +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::*; @@ -168,8 +247,18 @@ mod tests { 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); + } } From 3f9f7afd2795718781f964063a9b5030f0defa27 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 8 Dec 2025 13:32:46 -0800 Subject: [PATCH 49/66] day8: avoid having to manually define all the cmp traits --- src/day8.rs | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/src/day8.rs b/src/day8.rs index f4ed5a6..0f8c360 100644 --- a/src/day8.rs +++ b/src/day8.rs @@ -138,28 +138,12 @@ fn part2(input: &Circuits) -> u64 { panic!() } +#[derive(PartialEq, Eq, PartialOrd, Ord)] struct JunctionPair { + d: u64, a: usize, b: usize, - d: u64, } -impl Eq for JunctionPair {} -impl PartialEq for JunctionPair { - fn eq(&self, other: &Self) -> bool { - self.d == other.d - } -} -impl PartialOrd for JunctionPair { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.d.cmp(&other.d)) - } -} -impl Ord for JunctionPair { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - self.d.cmp(&other.d) - } -} - fn make_heap(circuits: &Circuits) -> BinaryHeap> { BinaryHeap::from_iter( circuits From 33275b39189df2f3f278e2565c6c8bd0b3bb4d5d Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Mon, 8 Dec 2025 22:17:10 -0800 Subject: [PATCH 50/66] day9: part1 and bruteforce part 2 (some cleanups and clippies) --- .aoc_tiles/tiles/2025/09.png | Bin 0 -> 7249 bytes README.md | 5 +- src/day8.rs | 15 ++-- src/day9.rs | 141 +++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + utils/grid/lib.rs | 19 ++++- 6 files changed, 171 insertions(+), 10 deletions(-) create mode 100644 .aoc_tiles/tiles/2025/09.png create mode 100644 src/day9.rs diff --git a/.aoc_tiles/tiles/2025/09.png b/.aoc_tiles/tiles/2025/09.png new file mode 100644 index 0000000000000000000000000000000000000000..32e6986d22dd1f079cb16198a76f164abcc1e507 GIT binary patch literal 7249 zcmV-X9IoSuP)=4-zQ0x7UEN*1cRERTLiRuwNC;a%Kt*sH5M@RfM`p%RS>_$}iyl2^&U0{P&YAHY z@jSmcobf3$3OrEYDe9ms0?HOh2w)(DK=!@U>F)HtSJnGaSgBN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

- 2025 - 16 ⭐ - Rust + 2025 - 17 ⭐ - Rust

@@ -26,4 +26,7 @@ + + + diff --git a/src/day8.rs b/src/day8.rs index 0f8c360..de7e153 100644 --- a/src/day8.rs +++ b/src/day8.rs @@ -9,13 +9,13 @@ struct Junction { } 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 - } + // 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 { @@ -144,6 +144,7 @@ struct JunctionPair { a: usize, b: usize, } + fn make_heap(circuits: &Circuits) -> BinaryHeap> { BinaryHeap::from_iter( circuits diff --git a/src/day9.rs b/src/day9.rs new file mode 100644 index 0000000..20923c5 --- /dev/null +++ b/src/day9.rs @@ -0,0 +1,141 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use grid::{AsCoord2d, Coord2d, Grid}; +use itertools::Itertools; +use std::cmp::{max, min}; + +#[aoc_generator(day9, part1)] +fn parse(input: &str) -> Vec { + input.lines().map(|l| l.parse().unwrap()).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() +} + +#[aoc_generator(day9, part2)] +fn parse2(input: &str) -> (Vec, Grid) { + let reds = parse(input); + let width = reds.iter().map(|c| c.x()).max().unwrap() + 1; + let height = reds.iter().map(|c| c.y()).max().unwrap() + 1; + + 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 + } + println!("grid {}x{}", grid.width(), grid.height()); + (reds, grid) +} + +fn flood_fill(grid: &mut Grid) { + #[derive(Debug, Eq, PartialEq)] + enum State { + OffLine(bool), // Off a line(true=inside) + OnLine(bool), // On a line(previous state) + } + for y in 1..grid.height() - 1 { + let mut state = match grid.get(&(0, y)) { + Some(b'.') => State::OffLine(false), //noop + Some(b'#') | Some(b'X') => State::OnLine(true), + s => panic!("Unexpected state: {s:?}"), + }; // if the row starts with a ., we start outside + for x in 1..grid.width() - 1 { + match grid.get(&(x, y)) { + Some(b'.') => { + if state == State::OffLine(true) || state == State::OnLine(false) { + grid.set(&(x, y), b'X'); + state = State::OffLine(true) + } + } + Some(b'#') | Some(b'X') => { + state = State::OnLine(match state { + State::OnLine(s) | State::OffLine(s) => s, + }) + } + None => panic!("overran the grid"), + Some(c) => panic!("unexpected value {c}"), + } + } + } +} + +#[aoc(day9, part2)] +fn part2((reds, grid): &(Vec, Grid)) -> u64 { + let mut grid = grid.clone(); + flood_fill(&mut grid); + + 'outer: for (a, b) in 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() + { + println!( + "{a} vs {b} = {}", + a.x().abs_diff(b.x()) * a.y().abs_diff(b.y()) + ); + + 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'.' { + continue 'outer; + } + } + } + return (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1); + } + panic!() +} + +#[cfg(test)] +mod tests { + use super::*; + + 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(&parse2(EXAMPLE)), 24); + } +} diff --git a/src/lib.rs b/src/lib.rs index ac83a67..b38dc0b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ mod day5; mod day6; mod day7; mod day8; +mod day9; use aoc_runner_derive::aoc_lib; diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs index f2fa866..6e60bc5 100644 --- a/utils/grid/lib.rs +++ b/utils/grid/lib.rs @@ -22,22 +22,37 @@ pub const ADJACENT_OFFSETS: [&(i64, i64); 8] = [ /// NESW pub const CARDINAL_OFFSETS: [&(i64, i64); 4] = [&(0, -1), &(-1, 0), &(1, 0), &(0, 1)]; -#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] +#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] pub struct Coord2d { pub x: i64, pub y: i64, } -impl Debug for Coord2d { +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 { From 72d7dc1cbb72ca4fa62040f2e5b72aa7152e9dad Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 9 Dec 2025 11:36:10 -0800 Subject: [PATCH 51/66] day9: still not working but corner-based algorithm --- Cargo.lock | 303 ++++++++++++++++++++++++++++++++++++++++- Cargo.toml | 3 + src/day9.rs | 386 +++++++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 657 insertions(+), 35 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1ec1aff..1e0192d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -66,9 +66,12 @@ dependencies = [ "aoc-runner-derive", "cached", "grid", + "indicatif", "itertools", "misc", + "rayon", "regex", + "rstest", ] [[package]] @@ -92,7 +95,7 @@ dependencies = [ "ahash", "cached_proc_macro", "cached_proc_macro_types", - "hashbrown", + "hashbrown 0.15.5", "once_cell", "thiserror", "web-time", @@ -122,6 +125,44 @@ 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" @@ -163,6 +204,12 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +[[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" @@ -181,6 +228,55 @@ 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 = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + [[package]] name = "grid" version = "0.1.0" @@ -196,12 +292,42 @@ dependencies = [ "foldhash", ] +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + [[package]] name = "ident_case" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[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" @@ -236,6 +362,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "libc" +version = "0.2.178" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091" + [[package]] name = "memchr" version = "2.7.6" @@ -274,6 +406,33 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +[[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" @@ -292,6 +451,26 @@ dependencies = [ "proc-macro2", ] +[[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 = "regex" version = "1.12.2" @@ -321,6 +500,50 @@ 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", + "glob", + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 2.0.111", + "unicode-ident", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustversion" version = "1.0.22" @@ -333,6 +556,12 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" +[[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" @@ -375,6 +604,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "slab" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" + [[package]] name = "strsim" version = "0.11.1" @@ -423,12 +658,54 @@ dependencies = [ "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", + "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 = "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" @@ -490,6 +767,30 @@ dependencies = [ "wasm-bindgen", ] +[[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 = "zerocopy" version = "0.8.31" diff --git a/Cargo.toml b/Cargo.toml index 392985c..dba4132 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,9 +8,12 @@ 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" [profile.release] lto = true diff --git a/src/day9.rs b/src/day9.rs index 20923c5..b818d82 100644 --- a/src/day9.rs +++ b/src/day9.rs @@ -1,11 +1,24 @@ use aoc_runner_derive::{aoc, aoc_generator}; use grid::{AsCoord2d, Coord2d, Grid}; +use indicatif::{ParallelProgressIterator, ProgressIterator, ProgressStyle}; use itertools::Itertools; -use std::cmp::{max, min}; +use rayon::prelude::*; +use std::collections::HashMap; +use std::{ + cmp::{max, min}, + fmt::Display, +}; -#[aoc_generator(day9, part1)] +#[aoc_generator(day9)] fn parse(input: &str) -> Vec { - input.lines().map(|l| l.parse().unwrap()).collect() + 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)] @@ -25,15 +38,13 @@ fn part1(input: &Vec) -> u64 { .unwrap() } -#[aoc_generator(day9, part2)] -fn parse2(input: &str) -> (Vec, Grid) { - let reds = parse(input); - let width = reds.iter().map(|c| c.x()).max().unwrap() + 1; - let height = reds.iter().map(|c| c.y()).max().unwrap() + 1; +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 { + for c in reds { // mark c filled grid.set(&c, b'#'); // build a line of green between it and the previous @@ -52,33 +63,59 @@ fn parse2(input: &str) -> (Vec, Grid) { } prev = c } - println!("grid {}x{}", grid.width(), grid.height()); - (reds, grid) + + 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 +} + +// FIXME: TOTALLY BROKEN fn flood_fill(grid: &mut Grid) { #[derive(Debug, Eq, PartialEq)] enum State { OffLine(bool), // Off a line(true=inside) OnLine(bool), // On a line(previous state) } - for y in 1..grid.height() - 1 { - let mut state = match grid.get(&(0, y)) { - Some(b'.') => State::OffLine(false), //noop - Some(b'#') | Some(b'X') => State::OnLine(true), - s => panic!("Unexpected state: {s:?}"), - }; // if the row starts with a ., we start outside - for x in 1..grid.width() - 1 { + for y in 0..grid.height() { + let mut state = State::OffLine(false); + for x in 0..grid.width() { match grid.get(&(x, y)) { Some(b'.') => { if state == State::OffLine(true) || state == State::OnLine(false) { grid.set(&(x, y), b'X'); state = State::OffLine(true) + } else { + state = State::OffLine(false) } } Some(b'#') | Some(b'X') => { state = State::OnLine(match state { - State::OnLine(s) | State::OffLine(s) => s, + State::OnLine(s) => s, + State::OffLine(s) => s, }) } None => panic!("overran the grid"), @@ -88,30 +125,219 @@ fn flood_fill(grid: &mut Grid) { } } -#[aoc(day9, part2)] -fn part2((reds, grid): &(Vec, Grid)) -> u64 { - let mut grid = grid.clone(); +// #[aoc(day9, part2, Brute)] +fn part2(reds: &Vec) -> u64 { + let mut grid = build_grid(reds); flood_fill(&mut grid); + println!("{grid}"); - 'outer: for (a, b) in reds + 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() - { - println!( - "{a} vs {b} = {}", - a.x().abs_diff(b.x()) * a.y().abs_diff(b.y()) - ); + .progress() + .collect_vec(); - 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'.' { - continue 'outer; + 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 } - return (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1); + // 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)], // y^ xv + ((-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 outside_points: HashMap<&Coord2d, Vec> = 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(), + ) + { + println!( + "[{},{}] = {}", + rect.top_left(), + rect.bottom_right(), + rect.area() + ); + // then for each corner, check if any of its outside edges are inside and not part of another line + if reds + .iter() + .filter(|corner| rect.in_bounds(corner)) + .inspect(|c| println!(" corner: {c}")) + .any(|corner| { + outside_points[corner] + .iter() + .inspect(|p| println!(" {} = {}", p, *grid.get(p).unwrap() as char)) + .any(|p| rect.in_bounds(p) && *grid.get(p).unwrap() == b'.') + }) + { + 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!() } @@ -119,6 +345,7 @@ fn part2((reds, grid): &(Vec, Grid)) -> u64 { #[cfg(test)] mod tests { use super::*; + use rstest::rstest; const EXAMPLE: &str = "7,1 11,1 @@ -136,6 +363,97 @@ mod tests { #[test] fn part2_example() { - assert_eq!(part2(&parse2(EXAMPLE)), 24); + 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 + )] + + fn part2_lines_example(#[case] input: &str, #[case] answer: u64) { + assert_eq!(part2_lines(&parse(input)), answer); } } From 73b44b1377b668dda7114b39d6a89e861f68dc1b Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 9 Dec 2025 22:13:52 -0800 Subject: [PATCH 52/66] day10: part1 --- .aoc_tiles/tiles/2025/10.png | Bin 0 -> 5851 bytes README.md | 5 +- src/day10.rs | 185 +++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 4 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 .aoc_tiles/tiles/2025/10.png create mode 100644 src/day10.rs diff --git a/.aoc_tiles/tiles/2025/10.png b/.aoc_tiles/tiles/2025/10.png new file mode 100644 index 0000000000000000000000000000000000000000..60bcc90128d874d82c82dd7a336a8935a35e1c9d GIT binary patch literal 5851 zcmV<179{D3P) zYT@d(YE!VlEy;ysSuQ}hTzq6xAz2_~owpP6a1xn3?D#1^B+Ig_w=^^N$C&YWB#mZ9 zvL3d7e_1`<^XsqY=kA`bd%i|G_Wc&b!sqjeE{kEinkZf|!pb>oXL-}W+qk2N$va6{MQi^7E2&|okOYqV#zLcZPv>=C&rOoR zbIaOU-Zb!1l49{D=&=xqRHiY=GzQEvH{=@X{^nB$^b#A1i7KGa^tr4ruV}hmmvCRRzb*>R;D14p%NJ?!*ozmZCJS4ed~hr@;4+w z0D!WnT&^#`N@`Rk)hXwtkT!dnl8VV2S6Kdmy93{T3J9Vqt}0mdcTxog08#}uXKmx% z!~Z3u!ZS!!Y#@kk-u*JQez5rf02Hm>B2lQ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+++ b/README.md @@ -1,6 +1,6 @@

- 2025 - 17 ⭐ - Rust + 2025 - 18 ⭐ - Rust

@@ -29,4 +29,7 @@ + + + diff --git a/src/day10.rs b/src/day10.rs new file mode 100644 index 0000000..0d33b39 --- /dev/null +++ b/src/day10.rs @@ -0,0 +1,185 @@ +use std::{collections::BinaryHeap, iter::repeat_n}; + +use aoc_runner_derive::{aoc, aoc_generator}; +use itertools::Itertools; +use regex::Regex; + +#[derive(Clone, Debug, Default)] +struct MachineDefinition { + desired: Vec, + buttons: Vec>, + joltages: Vec, +} + +impl MachineDefinition { + fn create<'a>(&'a self) -> Machine<'a> { + Machine { + d: self, + lights: Vec::from_iter(repeat_n(false, self.desired.len())), + } + } +} + +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(); + + MachineDefinition { + desired: parts["desired"].chars().map(|c| c == '#').collect(), + buttons: parts["buttons"] + .split_ascii_whitespace() + .map(|s| { + s[1..s.len() - 1] + .split(',') + .map(|n| n.parse().unwrap()) + .collect() + }) + .collect(), + joltages: parts["joltages"] + .split(',') + .map(|n| n.parse().unwrap()) + .collect(), + } + } +} + +#[derive(Clone, Debug)] +struct Machine<'a> { + d: &'a MachineDefinition, + lights: Vec, +} + +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() + } +} + +#[derive(Debug, Clone)] +struct PressSet<'a> { + machine: Machine<'a>, + presses: Vec, +} + +// NOTE: All compares are reversed so our max heap becomes a min heap +impl<'a> Eq for PressSet<'a> {} + +impl<'a> PartialEq for PressSet<'a> { + fn eq(&self, other: &Self) -> bool { + other.presses.len().eq(&self.presses.len()) + } +} + +impl<'a> PartialOrd for PressSet<'a> { + fn partial_cmp(&self, other: &Self) -> Option { + other.presses.len().partial_cmp(&self.presses.len()) + } +} + +impl<'a> Ord for PressSet<'a> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + other.presses.len().cmp(&self.presses.len()) + } +} + +fn find_best<'a>(md: &'a MachineDefinition) -> Vec { + let m = md.create(); + let mut to_check = BinaryHeap::new(); + for next in m.next_states() { + if let Some(new_m) = next.1 { + to_check.push(PressSet { + presses: vec![next.0], + machine: new_m.clone(), + }) + } else { + // what we found a solution on the first move? + return vec![next.0]; + } + } + while let Some(candidate) = to_check.pop() { + let cm = candidate.machine.clone(); + for next in cm.next_states() { + let mut presses = candidate.presses.clone(); + presses.push(next.0); + if let Some(new_m) = next.1 { + to_check.push(PressSet { + presses, + machine: new_m.clone(), + }) + } else { + return presses; + } + } + } + panic!() +} + +#[aoc_generator(day10)] +fn parse(input: &str) -> Vec { + input.lines().map(|l| l.into()).collect() +} + +#[aoc(day10, part1)] +fn part1(input: &Vec) -> u64 { + input + .into_iter() + .map(|md| find_best(md)) + // .inspect(|sol| println!(" [{sol:?}]")) + .map(|sol| sol.len() as u64) + .sum() +} + +#[aoc(day10, part2)] +fn part2(input: &Vec) -> u64 { + 0 +} + +#[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, 0)] + fn part2_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part2(&parse(input)), expected); + } +} diff --git a/src/lib.rs b/src/lib.rs index b38dc0b..4831a4d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ mod day1; +mod day10; mod day2; mod day3; mod day4; From 0a5e5c8798fae491b2107c0d707b2090a19e5dd3 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 9 Dec 2025 22:45:33 -0800 Subject: [PATCH 53/66] day10: small performance boost --- src/day10.rs | 46 +++++++++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/src/day10.rs b/src/day10.rs index 0d33b39..8474e41 100644 --- a/src/day10.rs +++ b/src/day10.rs @@ -1,7 +1,6 @@ -use std::{collections::BinaryHeap, iter::repeat_n}; +use std::{collections::BinaryHeap, hash::Hash, iter::repeat_n}; use aoc_runner_derive::{aoc, aoc_generator}; -use itertools::Itertools; use regex::Regex; #[derive(Clone, Debug, Default)] @@ -54,6 +53,19 @@ struct Machine<'a> { lights: Vec, } +impl<'a> Eq for Machine<'a> {} +impl<'a> PartialEq for Machine<'a> { + fn eq(&self, other: &Self) -> bool { + self.lights == other.lights + } +} + +impl<'a> Hash for Machine<'a> { + fn hash(&self, state: &mut H) { + self.lights.hash(state) + } +} + impl<'a> Machine<'a> { /// Get the state after pressing `button`, returns None if the state is as desired fn press(&self, button: usize) -> Option { @@ -85,7 +97,7 @@ impl<'a> Machine<'a> { #[derive(Debug, Clone)] struct PressSet<'a> { machine: Machine<'a>, - presses: Vec, + presses: usize, } // NOTE: All compares are reversed so our max heap becomes a min heap @@ -93,41 +105,41 @@ impl<'a> Eq for PressSet<'a> {} impl<'a> PartialEq for PressSet<'a> { fn eq(&self, other: &Self) -> bool { - other.presses.len().eq(&self.presses.len()) + other.presses.eq(&self.presses) } } impl<'a> PartialOrd for PressSet<'a> { fn partial_cmp(&self, other: &Self) -> Option { - other.presses.len().partial_cmp(&self.presses.len()) + Some(self.cmp(other)) } } impl<'a> Ord for PressSet<'a> { fn cmp(&self, other: &Self) -> std::cmp::Ordering { - other.presses.len().cmp(&self.presses.len()) + other.presses.cmp(&self.presses) } } -fn find_best<'a>(md: &'a MachineDefinition) -> Vec { +fn find_best(md: &MachineDefinition) -> usize { let m = md.create(); let mut to_check = BinaryHeap::new(); + for next in m.next_states() { if let Some(new_m) = next.1 { to_check.push(PressSet { - presses: vec![next.0], + presses: 1, machine: new_m.clone(), }) } else { // what we found a solution on the first move? - return vec![next.0]; + return 1; } } while let Some(candidate) = to_check.pop() { let cm = candidate.machine.clone(); for next in cm.next_states() { - let mut presses = candidate.presses.clone(); - presses.push(next.0); + let presses = candidate.presses + 1; if let Some(new_m) = next.1 { to_check.push(PressSet { presses, @@ -147,17 +159,17 @@ fn parse(input: &str) -> Vec { } #[aoc(day10, part1)] -fn part1(input: &Vec) -> u64 { +fn part1(input: &[MachineDefinition]) -> u64 { input - .into_iter() - .map(|md| find_best(md)) + .iter() + .map(find_best) // .inspect(|sol| println!(" [{sol:?}]")) - .map(|sol| sol.len() as u64) + .map(|sol| sol as u64) .sum() } #[aoc(day10, part2)] -fn part2(input: &Vec) -> u64 { +fn part2(input: &[MachineDefinition]) -> u64 { 0 } @@ -178,7 +190,7 @@ mod tests { } #[rstest] - #[case(EXAMPLE, 0)] + #[case(EXAMPLE, 33)] fn part2_example(#[case] input: &str, #[case] expected: u64) { assert_eq!(part2(&parse(input)), expected); } From 866544d416cb758ef4cfdbf275f416e837bb5528 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 10 Dec 2025 10:14:57 -0800 Subject: [PATCH 54/66] day10: working but way too slow simd implementation --- Cargo.lock | 26 ++++++ Cargo.toml | 1 + src/day10.rs | 218 +++++++++++++++++++++++++++++++++++++++++---------- 3 files changed, 203 insertions(+), 42 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1e0192d..dc466c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -72,6 +72,7 @@ dependencies = [ "rayon", "regex", "rstest", + "wide", ] [[package]] @@ -86,6 +87,12 @@ 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" @@ -556,6 +563,15 @@ 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 = "semver" version = "1.0.27" @@ -767,6 +783,16 @@ dependencies = [ "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 = "windows-link" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index dba4132..c34d956 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ misc = {path = "utils/misc"} rayon = "1.11.0" regex = "1.11.1" rstest = "0.26.1" +wide = "1.0.2" [profile.release] lto = true diff --git a/src/day10.rs b/src/day10.rs index 8474e41..42b6d6b 100644 --- a/src/day10.rs +++ b/src/day10.rs @@ -1,13 +1,22 @@ -use std::{collections::BinaryHeap, hash::Hash, iter::repeat_n}; +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>, - joltages: Vec, + buttons2: Vec, + buttons_max: i16x16, + joltages: i16x16, } impl MachineDefinition { @@ -17,6 +26,13 @@ impl MachineDefinition { 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 { @@ -27,22 +43,47 @@ impl From<&str> for MachineDefinition { .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: parts["buttons"] - .split_ascii_whitespace() - .map(|s| { - s[1..s.len() - 1] - .split(',') - .map(|n| n.parse().unwrap()) - .collect() - }) - .collect(), - joltages: parts["joltages"] - .split(',') - .map(|n| n.parse().unwrap()) - .collect(), + buttons: buttons, + buttons2: buttons2, + buttons_max: i16x16::new(buttons_max), + joltages: i16x16::new(joltages), } } } @@ -53,25 +94,18 @@ struct Machine<'a> { lights: Vec, } -impl<'a> Eq for Machine<'a> {} -impl<'a> PartialEq for Machine<'a> { - fn eq(&self, other: &Self) -> bool { - self.lights == other.lights - } -} - -impl<'a> Hash for Machine<'a> { - fn hash(&self, state: &mut H) { - self.lights.hash(state) - } +#[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 + /// 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] + new_state[*light] = !new_state[*light]; } if new_state == self.d.desired { None @@ -82,9 +116,8 @@ impl<'a> Machine<'a> { }) } } - /// Get the possible states from the current position - fn next_states(&self) -> Vec<(usize, Option>)> { + fn next_states(&self) -> Vec<(usize, Option)> { self.d .buttons .iter() @@ -94,14 +127,65 @@ impl<'a> Machine<'a> { } } +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 { @@ -109,33 +193,44 @@ impl<'a> PartialEq for PressSet<'a> { } } +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, + }); - for next in m.next_states() { - if let Some(new_m) = next.1 { - to_check.push(PressSet { - presses: 1, - machine: new_m.clone(), - }) - } else { - // what we found a solution on the first move? - return 1; - } - } while let Some(candidate) = to_check.pop() { let cm = candidate.machine.clone(); for next in cm.next_states() { @@ -153,6 +248,41 @@ fn find_best(md: &MachineDefinition) -> usize { 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() @@ -170,7 +300,11 @@ fn part1(input: &[MachineDefinition]) -> u64 { #[aoc(day10, part2)] fn part2(input: &[MachineDefinition]) -> u64 { - 0 + input + .iter() + .map(find_best_jolts) + .map(|sol| sol as u64) + .sum() } #[cfg(test)] From ef4de807d4a143f8a9d15afd0d59904d8d0ced2f Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 10 Dec 2025 21:26:21 -0800 Subject: [PATCH 55/66] day11: part1 --- .aoc_tiles/tiles/2025/11.png | Bin 0 -> 4874 bytes README.md | 5 +- src/day11.rs | 88 +++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 4 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 .aoc_tiles/tiles/2025/11.png create mode 100644 src/day11.rs diff --git a/.aoc_tiles/tiles/2025/11.png b/.aoc_tiles/tiles/2025/11.png new file mode 100644 index 0000000000000000000000000000000000000000..a3e9c6376d7212ae9e51b552e31daeebcfebcaef GIT binary patch literal 4874 zcmV+l6ZPzgP) zdvp|4p2vUH?{~WMevlUl0ue$$1O&y1>o6*4BxY4+d|^Njauhju&Ybm+)pK-r;hg0k z*0bymj3R@)Msu9OQB**JWFTZgNC=4`5c2Fi=|{TySylT-VWm?2s;=&?u6}&~>b`ZW zK6QWf&8=IvZhnp2Joq7S6^f#q_f@G>DQ*IDMKPf!Ta=TH`|_R>68@>l7UiVk*6nH_ zxm=7DcdbovdEnOVYM^tc87rsyIaPi+y@bFq47Iwy8) z2Pbc}x+m{=A6BZ%$XL8un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Jr9!`(tH)wZ+Xw?hRO|9RC`0X6(UlZJhLEsWu3LB-E!d@iCX6}kKWych)SN= zfZ1&WXTQXpcDXJit!zQ|{j2*=9fnli^RT%bWQ2Y)_e8|VfA$Jn6xW-Fxfo=1Yqd2XG9w<6fyPzLV^GTeN^+f@MI zwwh4m?c8Ng$kH+=2fFOTy|p`!2B3x{Aza-Ua>@G|w>LJVxA=Dzus4>==>h=TV7H&` zM9(*WGTd{Yu5_Mm&QbvQ-|~OjyLWGMbF)t>dkN&~#+Dn-d%&2u3RoHoMNwI>It1o< zbmJcYKrWZxci(-lz4qF^ef!q0U*FyB&x@?MocB!_SH&rJnz7OsKB}2nIdSQS$y==< zQD6G+Z)LK(-g7#gO-)Umoto~O7G;ZEgwPvt#NaU;n6e{ukU0qG&$-T(jq07*qoM6N<$f+|?6Z2$lO literal 0 HcmV?d00001 diff --git a/README.md b/README.md index 8897295..3d75012 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

- 2025 - 18 ⭐ - Rust + 2025 - 19 ⭐ - Rust

@@ -32,4 +32,7 @@ + + + diff --git a/src/day11.rs b/src/day11.rs new file mode 100644 index 0000000..308ea7a --- /dev/null +++ b/src/day11.rs @@ -0,0 +1,88 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use cached::proc_macro::cached; +use indicatif::{ProgressBar, ProgressFinish, ProgressStyle}; +use itertools::Itertools; +use std::collections::HashMap; + +type Edges = HashMap>; + +#[aoc_generator(day11)] +fn parse(input: &str) -> (Edges, Edges) { + let mut edges: Edges = HashMap::new(); + let mut rev_edges: Edges = HashMap::new(); + 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()); + rev_edges + .entry(v.to_string()) + .or_default() + .push(k.to_string()); + } + } + + (edges, rev_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 + } +} + +#[aoc(day11, part1)] +fn part1((fwd, rev): &(Edges, Edges)) -> u64 { + let mut count = 0u64; + let mut to_check = Vec::from_iter(rev["out"].iter()); + + 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); + + find_path("you", "out", fwd) +} + +#[aoc(day11, part2)] +fn part2(input: &(Edges, Edges)) -> u64 { + 0 +} + +#[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"; + + #[rstest] + #[case(EXAMPLE, 5)] + 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/src/lib.rs b/src/lib.rs index 4831a4d..8afe3bf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ mod day1; mod day10; +mod day11; mod day2; mod day3; mod day4; From 292638ea1da3f20974da54abe0d06ca48a025cae Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Thu, 11 Dec 2025 00:23:22 -0800 Subject: [PATCH 56/66] day11: part2 --- .aoc_tiles/tiles/2025/11.png | Bin 4874 -> 5813 bytes README.md | 2 +- src/day11.rs | 106 ++++++++++++++++++++++++++--------- 3 files changed, 80 insertions(+), 28 deletions(-) diff --git a/.aoc_tiles/tiles/2025/11.png b/.aoc_tiles/tiles/2025/11.png index a3e9c6376d7212ae9e51b552e31daeebcfebcaef..cd962b6c2cc1def3beae1767de5996214dc4fd9b 100644 GI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aNIYXDu&YQhyd_LmL4p}8;ax?_XTK#VS3x2fD@j~Mit-j? zPC+290-rxNE~qFAD(`tqOAGy9=Xm3Ki{vuqsD$Gx@P4Hu99Jb+-t%a1D=I1k*jJI7 zW-Nh3IU)0&M}tf6vD(|)gL;e4_C_Ypd!(YAzw_?)Xu=2cz8RfXkdmfIW>ME+l z+gq`^zT6l3g+ookyyp?&27Lx(cq@kO}G=T$VEn)Yfp)cZJ_xwmp_+ zW~E`?Lw$e!SeBlfcJD*VoFd$5AHC9er=yvyAk`YO7d@)ZD-|o$F3T8dyglCflgoOC zIzp1?Jr9!`(tH)wZ+Xw?hRO|9RC`0X6(UlZJhLEsWu3LB-E!d@iCX6}kKWych)SN= zfZ1&WXTQXpcDXJit!zQ|{j2*=9fnli^RT%bWQ2Y)_e8|VfA$Jn6xW-Fxfo=1Yqd2XG9w<6fyPzLV^GTeN^+f@MI zwwh4m?c8Ng$kH+=2fFOTy|p`!2B3x{Aza-Ua>@G|w>LJVxA=Dzus4>==>h=TV7H&` zM9(*WGTd{Yu5_Mm&QbvQ-|~OjyLWGMbF)t>dkN&~#+Dn-d%&2u3RoHoMNwI>It1o< zbmJcYKrWZxci(-lz4qF^ef!q0U*FyB&x@?MocB!_SH&rJnz7OsKB}2nIdSQS$y==< zQD6G+Z)LK(-g7#gO-)Umoto~O7G;ZEgwPvt#NaU;n6e{ukU0qG&$-T(jq07*qoM6N<$f+|?6Z2$lO diff --git a/README.md b/README.md index 3d75012..923f7eb 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

- 2025 - 19 ⭐ - Rust + 2025 - 20 ⭐ - Rust

diff --git a/src/day11.rs b/src/day11.rs index 308ea7a..2bf1e7d 100644 --- a/src/day11.rs +++ b/src/day11.rs @@ -1,27 +1,19 @@ use aoc_runner_derive::{aoc, aoc_generator}; -use cached::proc_macro::cached; -use indicatif::{ProgressBar, ProgressFinish, ProgressStyle}; -use itertools::Itertools; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; type Edges = HashMap>; #[aoc_generator(day11)] -fn parse(input: &str) -> (Edges, Edges) { +fn parse(input: &str) -> Edges { let mut edges: Edges = HashMap::new(); - let mut rev_edges: Edges = HashMap::new(); 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()); - rev_edges - .entry(v.to_string()) - .or_default() - .push(k.to_string()); } } - (edges, rev_edges) + edges } fn find_path(cur: &str, goal: &str, edges: &Edges) -> u64 { @@ -35,26 +27,72 @@ fn find_path(cur: &str, goal: &str, edges: &Edges) -> u64 { } } +fn mark_paths<'a>( + cur: &'a str, + edges: &'a Edges, + mut reachable: HashSet<&'a str>, +) -> HashSet<&'a str> { + reachable.insert(cur); + if let Some(nexts) = edges.get(cur) { + for n in nexts { + if !reachable.contains(&n.as_str()) { + // reachable.insert(n); + reachable = mark_paths(n, edges, reachable); + } + } + } + reachable +} + #[aoc(day11, part1)] -fn part1((fwd, rev): &(Edges, Edges)) -> u64 { - let mut count = 0u64; - let mut to_check = Vec::from_iter(rev["out"].iter()); - - 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); - +fn part1(fwd: &Edges) -> u64 { find_path("you", "out", fwd) } #[aoc(day11, part2)] -fn part2(input: &(Edges, Edges)) -> u64 { - 0 +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, HashSet::new()); + reachable_dac = mark_paths("dac", &rev, reachable_dac); + let mut reachable_fft = mark_paths("fft", edges, HashSet::new()); + reachable_fft = mark_paths("fft", &rev, reachable_fft); + + let reachable: HashSet<&str> = reachable_dac + .intersection(&reachable_fft) + .copied() + .collect(); + + let unreachable: HashSet<&str> = HashSet::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); + } + } + } + + // This is a bit of a cheat from viewing the graph and realizing all paths are ordered this way. + // However, knowing that fact that we can partition in this way, we could use a shortest-path algo + // to determine which order fft and dac are in. + // + // The assumption holds on my data and the example, so I think it's probably true of all inputs. + find_path("svr", "fft", &reachable_edges) + * find_path("fft", "dac", &reachable_edges) + * find_path("dac", "out", &reachable_edges) } #[cfg(test)] @@ -74,6 +112,20 @@ 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) { @@ -81,7 +133,7 @@ iii: out"; } #[rstest] - #[case(EXAMPLE, 0)] + #[case(EXAMPLE2, 2)] fn part2_example(#[case] input: &str, #[case] expected: u64) { assert_eq!(part2(&parse(input)), expected); } From 19426d1dc866f6385c4baa873c2cba563127ba7d Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Thu, 11 Dec 2025 00:36:58 -0800 Subject: [PATCH 57/66] day11: cleanup --- src/day11.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/day11.rs b/src/day11.rs index 2bf1e7d..013edb8 100644 --- a/src/day11.rs +++ b/src/day11.rs @@ -36,7 +36,6 @@ fn mark_paths<'a>( if let Some(nexts) = edges.get(cur) { for n in nexts { if !reachable.contains(&n.as_str()) { - // reachable.insert(n); reachable = mark_paths(n, edges, reachable); } } From 8cb33180ad0fa0f0c43d2ec7882f6edcba4d05a8 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Thu, 11 Dec 2025 21:00:02 -0800 Subject: [PATCH 58/66] day12: boilerplate --- src/day12.rs | 36 ++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 2 files changed, 37 insertions(+) create mode 100644 src/day12.rs diff --git a/src/day12.rs b/src/day12.rs new file mode 100644 index 0000000..b473287 --- /dev/null +++ b/src/day12.rs @@ -0,0 +1,36 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use rstest::rstest; + +#[aoc_generator(day12)] +fn parse(input: &str) -> String { + todo!() +} + +#[aoc(day12, part1)] +fn part1(input: &str) -> u64 { + todo!() +} + +#[aoc(day12, part2)] +fn part2(input: &str) -> u64 { + todo!() +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = ""; + + #[rstest] + #[case(EXAMPLE, 0)] + fn part1_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part1(&parse(EXAMPLE)), 0); + } + + #[rstest] + #[case(EXAMPLE, 0)] + fn part2_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part2(&parse(EXAMPLE)), 0); + } +} diff --git a/src/lib.rs b/src/lib.rs index 8afe3bf..5ed53fe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ mod day1; mod day10; mod day11; +mod day12; mod day2; mod day3; mod day4; From d0c14d004f9b64e7fe093987852d4904fa015352 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 12 Dec 2025 00:15:11 -0800 Subject: [PATCH 59/66] grid: add rotated/mirrored --- .aoc_tiles/tiles/2025/12.png | Bin 0 -> 5442 bytes README.md | 5 ++- utils/grid/lib.rs | 80 ++++++++++++++++++++++++++++++++++- 3 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 .aoc_tiles/tiles/2025/12.png diff --git a/.aoc_tiles/tiles/2025/12.png b/.aoc_tiles/tiles/2025/12.png new file mode 100644 index 0000000000000000000000000000000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i@-=RZ? zOeWLj&6{6;{q^GFV!Pdb>(;G3d-im6bny7bBQMLNkc%{Z^&VI1sI7Z0oVf$S=W?s_ zK34a9jLVYCw$A%l-SaUnCvNOI?_+h($GAMW(dxX9)jelu?5#}f6~4~%|IC^rHG&hf1^@s607*qoM6N<$g3Ef)cmMzZ literal 0 HcmV?d00001 diff --git a/README.md b/README.md index 923f7eb..e6d0a16 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

- 2025 - 20 ⭐ - Rust + 2025 - 21 ⭐ - Rust

@@ -35,4 +35,7 @@ + + + diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs index 6e60bc5..69205ad 100644 --- a/utils/grid/lib.rs +++ b/utils/grid/lib.rs @@ -22,6 +22,11 @@ pub const ADJACENT_OFFSETS: [&(i64, i64); 8] = [ /// 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, @@ -281,7 +286,7 @@ impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for OffsetsIter<'a, T> { } } -#[derive(Clone, Eq, PartialEq, Debug)] +#[derive(Clone, Eq, PartialEq, Debug, Hash)] pub struct Grid { pub data: Vec, width: i64, @@ -486,6 +491,79 @@ impl Grid { } } + 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(); From 004591374c79a90212b78f4b55e10e0aeeed5c4b Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 12 Dec 2025 00:15:36 -0800 Subject: [PATCH 60/66] day12: part1. salty about this one, here's all my useless code --- src/day12.rs | 244 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 235 insertions(+), 9 deletions(-) diff --git a/src/day12.rs b/src/day12.rs index b473287..9b2c739 100644 --- a/src/day12.rs +++ b/src/day12.rs @@ -1,31 +1,257 @@ +use std::iter::repeat_n; +use std::{collections::BinaryHeap, f64::consts, fmt::Display}; + use aoc_runner_derive::{aoc, aoc_generator}; -use rstest::rstest; +use grid::{Coord2d, Grid, MirrorAxis}; +use itertools::{Format, Itertools}; + +#[derive(Debug, Clone)] +struct PresentShape { + idx: u8, + shape: Grid, + variants: Vec>, +} + +impl From<&str> for PresentShape { + fn from(value: &str) -> Self { + let (idx, rest) = value.split_once(":\n").unwrap(); + + let shape: Grid = rest.parse().unwrap(); + + Self { + idx: idx.parse().unwrap(), + variants: (0..4) + .map(|rot| shape.rotated(rot)) + .chain([MirrorAxis::X, MirrorAxis::Y].map(|axis| shape.mirrored(axis))) + .unique() + .collect(), + shape, + } + } +} + +impl Display for PresentShape { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("{}:\n", self.idx))?; + f.write_fmt(format_args!("{}", self.shape)) + } +} + +impl PresentShape { + fn make(&self) -> Present { + Present { + shape: self.clone(), + location: None, + variant: 0, + } + } + fn popcount(&self) -> u64 { + self.shape.data.iter().filter(|c| **c != b'.').count() as u64 + } +} + +#[derive(Debug, Clone)] +struct Present { + shape: PresentShape, + location: Option, + variant: usize, +} + +#[derive(Debug, Clone)] +struct ChristmasTree { + area: Grid, + presents: Vec, +} + +impl ChristmasTree {} + +impl Display for ChristmasTree { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("{}", self.area))?; + for (i, p) in self.presents.iter().enumerate() { + f.write_fmt(format_args!(" {i}: @{:?} rot {}\n", p.location, p.variant))?; + f.write_fmt(format_args!("{}", p.shape.variants[p.variant]))?; + } + std::fmt::Result::Ok(()) + } +} + +#[derive(Debug, Clone)] +struct PresentsProblem { + shapes: Vec, + trees: Vec, +} + +impl PresentsProblem { + fn present(&self, idx: usize) -> Present { + Present { + shape: self.shapes[idx].clone(), + location: None, + variant: 0, + } + } + fn add_tree(&mut self, w: usize, h: usize, presents: Vec) { + self.trees.push(ChristmasTree { + area: Grid::with_shape(w, h, b'.'), + presents, + }) + } +} #[aoc_generator(day12)] -fn parse(input: &str) -> String { - todo!() +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(shapes[i].make(), *count)) + .collect(); + trees.push(ChristmasTree { + area: Grid::with_shape(w.parse().unwrap(), h.parse().unwrap(), b'.'), + presents, + }); + } + + PresentsProblem { shapes, trees } +} + +// place b on a and test if any # overlap any non-. +fn overlaps(a: &Grid, b: &Grid, p: &Coord2d) -> bool { + b.find_all(&b'#') + .any(|c| a.get(&(c + p)).is_some_and(|c| *c != b'.')) +} + +fn place_shape( + mut t: ChristmasTree, + idx: usize, + pos: Coord2d, + variant: usize, +) -> Option { + let variant = &t.presents[idx].shape.variants[variant]; + + if !overlaps(&t.area, variant, &pos) { + for xy in variant.find_all(&b'#') { + t.area.set(&(pos + &(xy)), b'0' + idx as u8).unwrap(); + } + + Some(t) + } else { + None + } +} + +fn place_next(mut t: ChristmasTree, cur: usize) -> Option { + if cur == t.presents.len() { + return Some(t); + } + let variants = &t.presents[cur].shape.variants; + 'variant: for (i, _v) in variants.iter().enumerate() { + //make sure the longest 'bar' can fit + for y in 0..&t.area.height() - 2 { + for x in 0..&t.area.width() - 2 { + if let Some(new_t) = place_shape( + t.clone(), + cur, + Coord2d { + x: x as i64, + y: y as i64, + }, + i, + ) { + if let Some(solution) = place_next(new_t, cur + 1) { + return Some(solution); + } + } + } + } + } + None } #[aoc(day12, part1)] -fn part1(input: &str) -> u64 { - todo!() +fn part1(input: &PresentsProblem) -> u64 { + let input = input.clone(); + let mut count = 0; + // for t in input.trees[0..2].iter() { + // println!("trying:\n{t}"); + // if let Some(r) = place_next(t.clone(), 0) { + // count += 1; + // println!("ok!\n{r}"); + // } else { + // println!("failed :("); + // } + // } + for t in input.trees.iter() { + let area = (t.area.width() * t.area.height()) as u64; + let occupied_area = t.presents.iter().map(|p| p.shape.popcount()).sum::(); + if occupied_area <= area { + count += 1 + } + } + + count } #[aoc(day12, part2)] -fn part2(input: &str) -> u64 { - todo!() +fn part2(input: &PresentsProblem) -> u64 { + 0 } #[cfg(test)] mod tests { use super::*; + use rstest::rstest; - const EXAMPLE: &str = ""; + 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"; #[rstest] #[case(EXAMPLE, 0)] fn part1_example(#[case] input: &str, #[case] expected: u64) { - assert_eq!(part1(&parse(EXAMPLE)), 0); + assert_eq!(part1(&parse(EXAMPLE)), 2); } #[rstest] From fd6b0c846bbb5d38c707570089fa5c10115dfc9a Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 12 Dec 2025 03:10:27 -0800 Subject: [PATCH 61/66] day12: cleanup and speedup --- src/day12.rs | 212 ++++++++++++++++++++++++--------------------------- 1 file changed, 100 insertions(+), 112 deletions(-) diff --git a/src/day12.rs b/src/day12.rs index 9b2c739..f3fd20b 100644 --- a/src/day12.rs +++ b/src/day12.rs @@ -1,101 +1,64 @@ -use std::iter::repeat_n; -use std::{collections::BinaryHeap, f64::consts, fmt::Display}; - use aoc_runner_derive::{aoc, aoc_generator}; use grid::{Coord2d, Grid, MirrorAxis}; -use itertools::{Format, Itertools}; +use itertools::Itertools; +use std::collections::HashSet; +use std::fmt::Display; +use std::iter::repeat_n; + +type CellType = bool; #[derive(Debug, Clone)] struct PresentShape { - idx: u8, - shape: Grid, - variants: Vec>, + variants: Vec>, } impl From<&str> for PresentShape { fn from(value: &str) -> Self { - let (idx, rest) = value.split_once(":\n").unwrap(); + let (_idx, rest) = value.split_once(":\n").unwrap(); - let shape: Grid = rest.parse().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 { - idx: idx.parse().unwrap(), variants: (0..4) .map(|rot| shape.rotated(rot)) .chain([MirrorAxis::X, MirrorAxis::Y].map(|axis| shape.mirrored(axis))) .unique() .collect(), - shape, } } } impl Display for PresentShape { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_fmt(format_args!("{}:\n", self.idx))?; - f.write_fmt(format_args!("{}", self.shape)) + f.write_fmt(format_args!("{}", self.variants[0])) } } impl PresentShape { - fn make(&self) -> Present { - Present { - shape: self.clone(), - location: None, - variant: 0, - } - } fn popcount(&self) -> u64 { - self.shape.data.iter().filter(|c| **c != b'.').count() as u64 + self.variants[0].count(&true) as u64 } } #[derive(Debug, Clone)] struct Present { - shape: PresentShape, - location: Option, - variant: usize, + shape: usize, } #[derive(Debug, Clone)] struct ChristmasTree { - area: Grid, + area: Grid, presents: Vec, } -impl ChristmasTree {} - -impl Display for ChristmasTree { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_fmt(format_args!("{}", self.area))?; - for (i, p) in self.presents.iter().enumerate() { - f.write_fmt(format_args!(" {i}: @{:?} rot {}\n", p.location, p.variant))?; - f.write_fmt(format_args!("{}", p.shape.variants[p.variant]))?; - } - std::fmt::Result::Ok(()) - } -} - #[derive(Debug, Clone)] struct PresentsProblem { - shapes: Vec, trees: Vec, -} - -impl PresentsProblem { - fn present(&self, idx: usize) -> Present { - Present { - shape: self.shapes[idx].clone(), - location: None, - variant: 0, - } - } - fn add_tree(&mut self, w: usize, h: usize, presents: Vec) { - self.trees.push(ChristmasTree { - area: Grid::with_shape(w, h, b'.'), - presents, - }) - } + shapes: Vec, } #[aoc_generator(day12)] @@ -116,88 +79,113 @@ fn parse(input: &str) -> PresentsProblem { let presents = present_counts .iter() .enumerate() - .flat_map(|(i, count)| repeat_n(shapes[i].make(), *count)) + .flat_map(|(i, count)| repeat_n(Present { shape: i }, *count)) .collect(); trees.push(ChristmasTree { - area: Grid::with_shape(w.parse().unwrap(), h.parse().unwrap(), b'.'), + area: Grid::with_shape(w.parse().unwrap(), h.parse().unwrap(), false), presents, }); } - PresentsProblem { shapes, trees } + 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(&b'#') - .any(|c| a.get(&(c + p)).is_some_and(|c| *c != b'.')) -} +// fn overlaps(a: &Grid, b: &Grid, p: &Coord2d) -> bool { +// b.find_all(&true) +// .any(|c| a.get(&(c + p)).is_some_and(|c| *c)) +// } -fn place_shape( - mut t: ChristmasTree, - idx: usize, - pos: Coord2d, - variant: usize, -) -> Option { - let variant = &t.presents[idx].shape.variants[variant]; +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]; - if !overlaps(&t.area, variant, &pos) { - for xy in variant.find_all(&b'#') { - t.area.set(&(pos + &(xy)), b'0' + idx as u8).unwrap(); + for xy in variant.find_all(&true) { + if let Some(was) = t.area.set(&(pos + &(xy)), true) + && was + { + // overlapped + return None; + } } - Some(t) - } else { - None } -} -fn place_next(mut t: ChristmasTree, cur: usize) -> Option { - if cur == t.presents.len() { - return Some(t); - } - let variants = &t.presents[cur].shape.variants; - 'variant: for (i, _v) in variants.iter().enumerate() { - //make sure the longest 'bar' can fit - for y in 0..&t.area.height() - 2 { - for x in 0..&t.area.width() - 2 { - if let Some(new_t) = place_shape( - t.clone(), - cur, - Coord2d { - x: x as i64, - y: y as i64, - }, - i, - ) { - if let Some(solution) = place_next(new_t, cur + 1) { - return Some(solution); + fn place_next( + &self, + t: ChristmasTree, + cur: usize, + cache: &mut HashSet<(usize, Grid)>, // impossible shapes + ) -> Option { + if cur == t.presents.len() { + // done + return Some(t); + } + if cache.contains(&(cur, t.area.clone())) { + // doomed + return None; + } + 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 let Some(solution) = self.place_next(new_t, cur + 1, cache) { + return Some(solution); + } else { + cache.insert((cur, t.area.clone())); + } } } } } + None } - None } #[aoc(day12, part1)] fn part1(input: &PresentsProblem) -> u64 { let input = input.clone(); let mut count = 0; - // for t in input.trees[0..2].iter() { - // println!("trying:\n{t}"); - // if let Some(r) = place_next(t.clone(), 0) { - // count += 1; - // println!("ok!\n{r}"); - // } else { - // println!("failed :("); - // } - // } + for t in input.trees.iter() { let area = (t.area.width() * t.area.height()) as u64; - let occupied_area = t.presents.iter().map(|p| p.shape.popcount()).sum::(); - if occupied_area <= area { - count += 1 + 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 { + // definitely impossible + continue; + } + let available_3x3s = (t.area.width() / 3) * (t.area.height() / 3); + if available_3x3s >= present_count { + // definitely_possible + count += 1; + continue; + } + if input + .place_next(t.clone(), 0, &mut HashSet::new()) + .is_some() + { + count += 1; + continue; } } @@ -205,7 +193,7 @@ fn part1(input: &PresentsProblem) -> u64 { } #[aoc(day12, part2)] -fn part2(input: &PresentsProblem) -> u64 { +fn part2(_input: &PresentsProblem) -> u64 { 0 } @@ -251,12 +239,12 @@ mod tests { #[rstest] #[case(EXAMPLE, 0)] fn part1_example(#[case] input: &str, #[case] expected: u64) { - assert_eq!(part1(&parse(EXAMPLE)), 2); + assert_eq!(part1(&parse(input)), expected); } #[rstest] #[case(EXAMPLE, 0)] fn part2_example(#[case] input: &str, #[case] expected: u64) { - assert_eq!(part2(&parse(EXAMPLE)), 0); + assert_eq!(part2(&parse(input)), expected); } } From 845138dd2d682a83d85f048f7461d8a03cd0ca87 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 12 Dec 2025 03:42:42 -0800 Subject: [PATCH 62/66] day12: cache and bool --- src/day12.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/day12.rs b/src/day12.rs index f3fd20b..96d30e8 100644 --- a/src/day12.rs +++ b/src/day12.rs @@ -146,13 +146,12 @@ impl PresentsProblem { ) { if let Some(solution) = self.place_next(new_t, cur + 1, cache) { return Some(solution); - } else { - cache.insert((cur, t.area.clone())); } } } } } + cache.insert((cur, t.area.clone())); None } } @@ -237,7 +236,7 @@ mod tests { 12x5: 1 0 1 0 3 2"; #[rstest] - #[case(EXAMPLE, 0)] + #[case(EXAMPLE, 2)] fn part1_example(#[case] input: &str, #[case] expected: u64) { assert_eq!(part1(&parse(input)), expected); } From c35270a6a20ee059b2fe63dc7648e86988a20caf Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Fri, 12 Dec 2025 11:46:25 -0800 Subject: [PATCH 63/66] day11: perf --- Cargo.lock | 372 ++++++++++++++++++++++++++++++++++++++++++++++++++- Cargo.toml | 1 + src/day11.rs | 100 +++++++++++--- 3 files changed, 451 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dc466c3..cf0d25f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,7 +8,7 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "once_cell", "version_check", "zerocopy", @@ -72,15 +72,34 @@ dependencies = [ "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" @@ -126,6 +145,12 @@ 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" @@ -211,6 +236,15 @@ 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" @@ -223,6 +257,22 @@ 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" @@ -278,6 +328,18 @@ dependencies = [ "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" @@ -288,6 +350,12 @@ checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" 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" @@ -305,12 +373,29 @@ 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" @@ -359,6 +444,16 @@ 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" @@ -369,18 +464,54 @@ dependencies = [ "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" @@ -407,12 +538,45 @@ 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" @@ -458,6 +622,12 @@ 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" @@ -478,6 +648,15 @@ dependencies = [ "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" @@ -530,7 +709,7 @@ version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c845311f0ff7951c5506121a9ad75aec44d083c31583b2ea5a30bcb0b0abba0" dependencies = [ - "cfg-if", + "cfg-if 1.0.4", "glob", "proc-macro-crate", "proc-macro2", @@ -542,6 +721,79 @@ dependencies = [ "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" @@ -551,6 +803,19 @@ 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" @@ -572,6 +837,12 @@ 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" @@ -626,6 +897,18 @@ 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" @@ -654,6 +937,19 @@ dependencies = [ "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" @@ -689,7 +985,7 @@ version = "0.23.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d7cbc3b4b49633d57a0509303158ca50de80ae32c265093b24c414705807832" dependencies = [ - "indexmap", + "indexmap 2.12.1", "toml_datetime", "toml_parser", "winnow", @@ -704,6 +1000,37 @@ 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" @@ -728,13 +1055,22 @@ 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", + "cfg-if 1.0.4", "once_cell", "rustversion", "wasm-bindgen-macro", @@ -793,6 +1129,28 @@ dependencies = [ "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" @@ -817,6 +1175,12 @@ 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" diff --git a/Cargo.toml b/Cargo.toml index c34d956..b82ea82 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ 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] diff --git a/src/day11.rs b/src/day11.rs index 013edb8..c3a302a 100644 --- a/src/day11.rs +++ b/src/day11.rs @@ -1,11 +1,11 @@ use aoc_runner_derive::{aoc, aoc_generator}; -use std::collections::{HashMap, HashSet}; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -type Edges = HashMap>; +type Edges = FxHashMap>; #[aoc_generator(day11)] fn parse(input: &str) -> Edges { - let mut edges: Edges = HashMap::new(); + 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() { @@ -30,8 +30,8 @@ fn find_path(cur: &str, goal: &str, edges: &Edges) -> u64 { fn mark_paths<'a>( cur: &'a str, edges: &'a Edges, - mut reachable: HashSet<&'a str>, -) -> HashSet<&'a str> { + mut reachable: FxHashSet<&'a str>, +) -> FxHashSet<&'a str> { reachable.insert(cur); if let Some(nexts) = edges.get(cur) { for n in nexts { @@ -43,12 +43,61 @@ fn mark_paths<'a>( reachable } -#[aoc(day11, part1)] +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, part2)] +#[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 { @@ -56,17 +105,17 @@ fn part2(edges: &Edges) -> u64 { rev.entry(to.to_owned()).or_default().push(from.to_owned()); } } - let mut reachable_dac = mark_paths("dac", edges, HashSet::new()); + 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, HashSet::new()); + let mut reachable_fft = mark_paths("fft", edges, FxHashSet::default()); reachable_fft = mark_paths("fft", &rev, reachable_fft); - let reachable: HashSet<&str> = reachable_dac + let reachable: FxHashSet<&str> = reachable_dac .intersection(&reachable_fft) .copied() .collect(); - let unreachable: HashSet<&str> = HashSet::from_iter(edges.keys().map(|k| k.as_str())) + let unreachable: FxHashSet<&str> = FxHashSet::from_iter(edges.keys().map(|k| k.as_str())) .difference(&reachable) .copied() .collect(); @@ -84,14 +133,17 @@ fn part2(edges: &Edges) -> u64 { } } - // This is a bit of a cheat from viewing the graph and realizing all paths are ordered this way. - // However, knowing that fact that we can partition in this way, we could use a shortest-path algo - // to determine which order fft and dac are in. - // - // The assumption holds on my data and the example, so I think it's probably true of all inputs. + // 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) - * find_path("fft", "dac", &reachable_edges) - * find_path("dac", "out", &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)] @@ -131,9 +183,21 @@ hhh: out"; 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); + } } From 77c3c20ad03c6e1cb690368ddd6ddfa38d892f94 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 1 Dec 2026 01:46:52 -0700 Subject: [PATCH 64/66] day9: cheated from others for part 2, still a mess --- src/day9.rs | 294 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 228 insertions(+), 66 deletions(-) diff --git a/src/day9.rs b/src/day9.rs index b818d82..393de8f 100644 --- a/src/day9.rs +++ b/src/day9.rs @@ -3,7 +3,7 @@ use grid::{AsCoord2d, Coord2d, Grid}; use indicatif::{ParallelProgressIterator, ProgressIterator, ProgressStyle}; use itertools::Itertools; use rayon::prelude::*; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::{ cmp::{max, min}, fmt::Display, @@ -93,34 +93,45 @@ fn build_hashgrid(reds: &Vec) -> HashMap { grid } -// FIXME: TOTALLY BROKEN -fn flood_fill(grid: &mut Grid) { - #[derive(Debug, Eq, PartialEq)] - enum State { - OffLine(bool), // Off a line(true=inside) - OnLine(bool), // On a line(previous state) +fn flood_fill(grid: &mut Grid, pos: Coord2d) { + if grid.get(&pos) != Some(&b'.') { + return; } - for y in 0..grid.height() { - let mut state = State::OffLine(false); - for x in 0..grid.width() { - match grid.get(&(x, y)) { - Some(b'.') => { - if state == State::OffLine(true) || state == State::OnLine(false) { - grid.set(&(x, y), b'X'); - state = State::OffLine(true) - } else { - state = State::OffLine(false) - } - } - Some(b'#') | Some(b'X') => { - state = State::OnLine(match state { - State::OnLine(s) => s, - State::OffLine(s) => s, - }) - } - None => panic!("overran the grid"), - Some(c) => panic!("unexpected value {c}"), - } + 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 } } } @@ -128,8 +139,10 @@ fn flood_fill(grid: &mut Grid) { // #[aoc(day9, part2, Brute)] fn part2(reds: &Vec) -> u64 { let mut grid = build_grid(reds); - flood_fill(&mut grid); - println!("{grid}"); + // 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() @@ -160,7 +173,7 @@ fn part2(reds: &Vec) -> u64 { }) .find_map_first(|(good, a, b)| if good { Some((a, b)) } else { None }) .unwrap(); - println!("win: {a} {b}"); + // println!("win: {a} {b}"); (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1) } @@ -257,7 +270,7 @@ fn outside_points(prev: &Coord2d, cur: &Coord2d, next: &Coord2d) -> Vec 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)], // y^ xv + ((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 @@ -276,13 +289,26 @@ fn outside_points(prev: &Coord2d, cur: &Coord2d, next: &Coord2d) -> Vec #[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 outside_points: HashMap<&Coord2d, Vec> = reds - .iter() - .circular_tuple_windows() - .map(|(a, b, c)| (b, outside_points(a, b, c))) - .collect(); + // 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'.' { @@ -306,37 +332,39 @@ fn part2_lines(reds: &Vec) -> u64 { .unwrap(), ) { - println!( - "[{},{}] = {}", - rect.top_left(), - rect.bottom_right(), - rect.area() - ); - // then for each corner, check if any of its outside edges are inside and not part of another line - if reds - .iter() - .filter(|corner| rect.in_bounds(corner)) - .inspect(|c| println!(" corner: {c}")) - .any(|corner| { - outside_points[corner] - .iter() - .inspect(|p| println!(" {} = {}", p, *grid.get(p).unwrap() as char)) - .any(|p| rect.in_bounds(p) && *grid.get(p).unwrap() == b'.') - }) - { + 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!( + // "win! {},{} = {}", + // rect.top_left(), + // rect.bottom_right(), + // rect.area() + // ); + // grid.set(&rect.top_left(), b'*'); + // grid.set(&rect.bottom_right(), b'*'); - println!("{grid}"); + // println!("{grid}"); return rect.area(); } panic!() @@ -452,6 +480,140 @@ mod tests { 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); From 645f3683c9a177b0f9cc4e789dfe6a6c2d67a67f Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 1 Dec 2026 01:50:57 -0700 Subject: [PATCH 65/66] aoc-tiles update --- .aoc_tiles/tiles/2025/09.png | Bin 7249 -> 7915 bytes .pre-commit-config.yaml | 4 +++- README.md | 26 +++++++++++++------------- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/.aoc_tiles/tiles/2025/09.png b/.aoc_tiles/tiles/2025/09.png index 32e6986d22dd1f079cb16198a76f164abcc1e507..2e00dc3f30861a713b05f5b478eabe89c9d85c8f 100644 GIT binary patch literal 7915 zcmX9@1yoee+g?zlOV~w9LCK{-K)R)yU6vA-5NVPA(J3H;q;yK{($Xv~-5}jv!V=Q; zt>6EgxpU8%Gw0lyJI_4t^S)1nmWCoR0Sy5F03cRYlGnk!dohnC9yX>|+t@J%0G?MV z%gg9_rXTp)e59Su*xsj*UT;x4l4On)Ws7WNGpOP=tztH+>~YU!f>`u854{)At${Q_ zjMC=jc;aX0(0zaGnZ+X3BY@rxv%@o0js|sXD!C+aqHIe{;c0JZr5`Oezeu$eqLI#{ zMX}#WVv&|FmoIxuxwfu9-1~o68F|2q#8Hk@FjXb{C9q^QNXUb?KQYy>$>cX?zojRvRqmFYsevdDrpKgBbpiIiK;g=0XjpaCg`pY;ls@hmP;<^2mDzO(A z5McIrGDRyRq6j8~Bk{^QI>0=FO3uN$w`nWb^y2nj|5ksZzczAv`Kd|A4_zXl=96aj zRsm5@9$>~GH%I_hn)Yt$%^m=db3-3kHZhKhtWcU0X{~@IJc7`i&e^0cKcAl=m#koDB}xBrd2C>xdD3WMT~q!vYkk+I`H+U~~GNAUr6_^SNtc z*eew1LEJb@k45%_9a-n(O|MN30LUxo9r}46r7aJAgGeTsb7(#aB2qWfDjoA(bpc54 zM%S4ozCZM&f{0Oh0(D7aPe5mzDhaW(ClD1X8<}LS_%hkZlM<=1HIJ?b| zk%$$ro^_C!<+TPlt$K2(GWN!$hY*y4kcPvtq~k1aj}J~VJ~MoAD@c#&bA92v8nB9F@3FU)yrnUY$OImukSvE*oo#4wT zc0C=Ks}jWvi<7ioIX5_j$2ym~(!YTwv?>V@8gswOi{Xc=hI)ttxxgTBAGXsJFTmcd_4Y;Y>W0@fd6zvDPNF z7;3s+CIbKr{IKqz^@xee6nRS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+96cj-O0DuL3j+U#|hBFaA%L$yg zyddfT`|8!J*REYVd$!=P;U16Y$dMx-ee_Xp?}%$PpIWZ3ucseGp)m35MpTbQX(**s z1!4&+J}U&tjRlIla#?x~XD9?B8n|NZw@S65e5ROt0w zK^X=I2OAn1PMkP#;>3wSVAS~{p0&&>tjSu9q-!hHR0UXtCD>O`f*`s~kz55MG7N|S z0C*^Xh5QkpJ762&I3mV}S5Vw@gTYWxP>`9Ksn_deG8qIxZnxXzaycB1=H_OrHBQ{D zxQG_kaU zePUP{VDR3p5vr5UOYgConwsKjYa;C(5mqYH^4%SwI=Q^`zKYtt;n3Cu+bf-#Vm+=OStF4K*cT}AB31cNe@=l)!)#Icp>US({O^UtZNv!257omDA7*|zM zDbd=RtoG#_2`#y-zxzPgcTkeWdsp^VbTG6viS`O~OCK}qhW8HLQ&nQTJXaQ?*W$;> zD-@)?e0wZqVWn=){XJjrK=eke&)Np3_r*9`qRJx4$s}!aJkxUVCS$*a% z+x2rH_sBQdrg_}+G4cvpucG>`SbI?Xd4+)Mwyc-19N>Ca?;+aN$DA?^KYsk{{FWsyK>Vi4y(!~IP4~rk(xpQY-T^%bcf22t3PA>0Q_5mkFRe-0kd_Er%FAsr5 zR&DtM06;30E?BT&)22=T{O3P6Zrs?`CLq{VG;hN9-ZiS4qP(MorJuJ-Sy*Yma>COw z5_5(R>vR7&iXeBi7Yqh#YHDuXx^?#K*{Z6lgoSlC)$%mtr3njy)H4@AVu`9~9wn@} ztmN?gg%@6U>7|$U@893h(9qr8txzbQd+s@}*GqZ*3dLPk%hQl|R18w*txKxH3U})j zKCJW^-^U+++|<e(q%04{&00000NkvXXu0mjf)(!>! diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 40583a7..5b2a983 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,9 +14,10 @@ repos: types: [file, rust] language: system - repo: https://github.com/LiquidFun/aoc_tiles - rev: 0.6.4 + 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. @@ -26,5 +27,6 @@ repos: 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/README.md b/README.md index e6d0a16..414bd64 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,41 @@

- 2025 - 21 ⭐ - Rust + 2025 - 22 ⭐ - Rust

- + - + - + - + - + - + - + - + - + - + - + - + From 0446debff449c0efa1007ce98779ede5acff90d9 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Wed, 2 Dec 2026 13:10:46 -0700 Subject: [PATCH 66/66] fixes --- src/day12.rs | 52 +++++++++++++++++++++++++++++++++++++---------- utils/grid/lib.rs | 1 + 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/src/day12.rs b/src/day12.rs index 96d30e8..a0af759 100644 --- a/src/day12.rs +++ b/src/day12.rs @@ -1,6 +1,8 @@ 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; @@ -122,14 +124,14 @@ impl PresentsProblem { t: ChristmasTree, cur: usize, cache: &mut HashSet<(usize, Grid)>, // impossible shapes - ) -> Option { + ) -> bool { if cur == t.presents.len() { // done - return Some(t); + return true; } if cache.contains(&(cur, t.area.clone())) { // doomed - return None; + return false; } let variants = &self.shapes[t.presents[cur].shape].variants; for (i, _v) in variants.iter().enumerate() { @@ -144,15 +146,15 @@ impl PresentsProblem { }, i, ) { - if let Some(solution) = self.place_next(new_t, cur + 1, cache) { - return Some(solution); + if self.place_next(new_t, cur + 1, cache) { + return true; } } } } } cache.insert((cur, t.area.clone())); - None + false } } @@ -161,7 +163,8 @@ fn part1(input: &PresentsProblem) -> u64 { let input = input.clone(); let mut count = 0; - for t in input.trees.iter() { + 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 @@ -170,22 +173,28 @@ fn part1(input: &PresentsProblem) -> u64 { .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()) - .is_some() - { + 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 @@ -235,8 +244,29 @@ mod tests { 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); } diff --git a/utils/grid/lib.rs b/utils/grid/lib.rs index 69205ad..815c1b5 100644 --- a/utils/grid/lib.rs +++ b/utils/grid/lib.rs @@ -412,6 +412,7 @@ impl Grid { } } + // 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