diff --git a/2024/.aoc_tiles/tiles/2024/01.png b/2024/.aoc_tiles/tiles/2024/01.png
new file mode 100644
index 0000000..ada1270
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/01.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/02.png b/2024/.aoc_tiles/tiles/2024/02.png
new file mode 100644
index 0000000..3ee0952
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/02.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/03.png b/2024/.aoc_tiles/tiles/2024/03.png
new file mode 100644
index 0000000..5b345a6
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/03.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/04.png b/2024/.aoc_tiles/tiles/2024/04.png
new file mode 100644
index 0000000..648716c
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/04.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/05.png b/2024/.aoc_tiles/tiles/2024/05.png
new file mode 100644
index 0000000..b1b0f32
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/05.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/06.png b/2024/.aoc_tiles/tiles/2024/06.png
new file mode 100644
index 0000000..9c20d7b
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/06.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/07.png b/2024/.aoc_tiles/tiles/2024/07.png
new file mode 100644
index 0000000..9fea9f8
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/07.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/08.png b/2024/.aoc_tiles/tiles/2024/08.png
new file mode 100644
index 0000000..78b9352
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/08.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/09.png b/2024/.aoc_tiles/tiles/2024/09.png
new file mode 100644
index 0000000..8dda323
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/09.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/10.png b/2024/.aoc_tiles/tiles/2024/10.png
new file mode 100644
index 0000000..71d23e4
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/10.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/11.png b/2024/.aoc_tiles/tiles/2024/11.png
new file mode 100644
index 0000000..1b44144
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/11.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/12.png b/2024/.aoc_tiles/tiles/2024/12.png
new file mode 100644
index 0000000..8989329
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/12.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/13.png b/2024/.aoc_tiles/tiles/2024/13.png
new file mode 100644
index 0000000..a014355
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/13.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/14.png b/2024/.aoc_tiles/tiles/2024/14.png
new file mode 100644
index 0000000..e4f0551
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/14.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/15.png b/2024/.aoc_tiles/tiles/2024/15.png
new file mode 100644
index 0000000..8a0a40a
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/15.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/16.png b/2024/.aoc_tiles/tiles/2024/16.png
new file mode 100644
index 0000000..2e96a98
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/16.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/17.png b/2024/.aoc_tiles/tiles/2024/17.png
new file mode 100644
index 0000000..7606912
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/17.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/18.png b/2024/.aoc_tiles/tiles/2024/18.png
new file mode 100644
index 0000000..9e04ed3
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/18.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/19.png b/2024/.aoc_tiles/tiles/2024/19.png
new file mode 100644
index 0000000..9da34f0
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/19.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/20.png b/2024/.aoc_tiles/tiles/2024/20.png
new file mode 100644
index 0000000..5d13312
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/20.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/21.png b/2024/.aoc_tiles/tiles/2024/21.png
new file mode 100644
index 0000000..007aeb9
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/21.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/22.png b/2024/.aoc_tiles/tiles/2024/22.png
new file mode 100644
index 0000000..56fdee5
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/22.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/23.png b/2024/.aoc_tiles/tiles/2024/23.png
new file mode 100644
index 0000000..bc4cac9
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/23.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/24.png b/2024/.aoc_tiles/tiles/2024/24.png
new file mode 100644
index 0000000..b966019
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/24.png differ
diff --git a/2024/.aoc_tiles/tiles/2024/25.png b/2024/.aoc_tiles/tiles/2024/25.png
new file mode 100644
index 0000000..a1daeb8
Binary files /dev/null and b/2024/.aoc_tiles/tiles/2024/25.png differ
diff --git a/2024/.github/workflows/test.yaml b/2024/.github/workflows/test.yaml
new file mode 100644
index 0000000..06f7f02
--- /dev/null
+++ b/2024/.github/workflows/test.yaml
@@ -0,0 +1,62 @@
+name: test
+
+on:
+ push:
+ branches: [ main ]
+
+env:
+ CARGO_TERM_COLOR: always
+
+jobs:
+ tests:
+ name: AoC 2024
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+ - name: setup toolchain
+ uses: actions-rust-lang/setup-rust-toolchain@v1
+ with:
+ cache: true
+ components: clippy, rustfmt
+ toolchain: stable
+ rustflags: ""
+
+ - name: install cargo-aoc
+ run: cargo install --locked cargo-aoc
+
+ - name: get date
+ id: date
+ run: |
+ echo date=$(date +%Y%m%d) > $GITHUB_OUTPUT
+
+ - name: Get cached inputs
+ id: inputs
+ uses: actions/cache@v4
+ with:
+ path: input
+ key: ${{ steps.date.outputs.date }}
+
+ - name: Get inputs from source
+ if: steps.inputs.outputs.cache-hit != 'true'
+ run: |
+ cargo aoc credentials ${{ secrets.AOC_SESSION }}
+ for i in $(seq 1 25); do
+ dayfmt=$(printf %02d $i)
+ if [ ${{ steps.date.outputs.date }} -ge 202412${dayfmt} ]; then
+ cargo aoc input --year 2024 --day $i
+ fi
+ done
+
+ - name: cargo test
+ run: cargo test --lib
+
+ - name: rustfmt
+ run: cargo fmt --all -- --check
+
+ - name: clippy
+ run: cargo clippy --lib --tests -- -D warnings
+ if: always()
+
+ - name: full run
+ run: cargo run --release
+ if: always()
diff --git a/2024/.gitignore b/2024/.gitignore
new file mode 100644
index 0000000..2ad0769
--- /dev/null
+++ b/2024/.gitignore
@@ -0,0 +1,7 @@
+**/target
+input
+flamegraph.svg
+perf.data*
+guesses
+.aoc_tiles/*
+!.aoc_tiles/tiles/
diff --git a/2024/.pre-commit-config.yaml b/2024/.pre-commit-config.yaml
new file mode 100644
index 0000000..8dd37bf
--- /dev/null
+++ b/2024/.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.2
+ 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=2024
+ # - --language-sorting=jl,kt,py,rs
+ # - --exclude-patterns=2021/*/*.apl,2021/*/*.py,2021/*/*.cpp
diff --git a/2024/.rustfmt.toml b/2024/.rustfmt.toml
new file mode 100644
index 0000000..7530651
--- /dev/null
+++ b/2024/.rustfmt.toml
@@ -0,0 +1 @@
+max_width = 120
diff --git a/2024/Cargo.lock b/2024/Cargo.lock
new file mode 100644
index 0000000..3e179d9
--- /dev/null
+++ b/2024/Cargo.lock
@@ -0,0 +1,666 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "ahash"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "version_check",
+ "zerocopy",
+]
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
+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 = "aoc2024"
+version = "0.1.0"
+dependencies = [
+ "aoc-runner",
+ "aoc-runner-derive",
+ "atoi",
+ "bitflags",
+ "cached",
+ "colored",
+ "grid",
+ "itertools",
+ "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.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
+
+[[package]]
+name = "bitflags"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
+
+[[package]]
+name = "bumpalo"
+version = "3.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
+
+[[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.90",
+]
+
+[[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.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+
+[[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 = "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.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
+
+[[package]]
+name = "darling_core"
+version = "0.20.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5"
+dependencies = [
+ "fnv",
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim",
+ "syn 2.0.90",
+]
+
+[[package]]
+name = "darling_macro"
+version = "0.20.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806"
+dependencies = [
+ "darling_core",
+ "quote",
+ "syn 2.0.90",
+]
+
+[[package]]
+name = "either"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
+
+[[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 = "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.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674"
+
+[[package]]
+name = "js-sys"
+version = "0.3.76"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7"
+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 = "log"
+version = "0.4.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
+
+[[package]]
+name = "memchr"
+version = "2.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
+
+[[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 = "once_cell"
+version = "1.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.92"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "rayon"
+version = "1.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "regex"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497"
+
+[[package]]
+name = "ryu"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
+
+[[package]]
+name = "serde"
+version = "1.0.216"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b9781016e935a97e8beecf0c933758c97a5520d32930e460142b4cd80c6338e"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.216"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.90",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.133"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377"
+dependencies = [
+ "itoa",
+ "memchr",
+ "ryu",
+ "serde",
+]
+
+[[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.90"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31"
+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.90",
+]
+
+[[package]]
+name = "thread_local"
+version = "1.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"
+
+[[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.99"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "wasm-bindgen-macro",
+]
+
+[[package]]
+name = "wasm-bindgen-backend"
+version = "0.2.99"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79"
+dependencies = [
+ "bumpalo",
+ "log",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.90",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.99"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.99"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.90",
+ "wasm-bindgen-backend",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.99"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6"
+
+[[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.7.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.7.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.90",
+]
diff --git a/2024/Cargo.toml b/2024/Cargo.toml
new file mode 100644
index 0000000..5f9a301
--- /dev/null
+++ b/2024/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+edition = "2021"
+name = "aoc2024"
+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"}
+itertools = "0.13.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
\ No newline at end of file
diff --git a/2024/README.md b/2024/README.md
new file mode 100644
index 0000000..dfc7c92
--- /dev/null
+++ b/2024/README.md
@@ -0,0 +1,80 @@
+
+
+ 2024 - 48 ⭐ - Rust
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/2024/boilerplate/src/main.rs b/2024/boilerplate/src/main.rs
new file mode 100644
index 0000000..657202a
--- /dev/null
+++ b/2024/boilerplate/src/main.rs
@@ -0,0 +1,66 @@
+use std::fs::File;
+use std::io::{BufRead, BufReader, Lines};
+use std::time::{Duration, Instant};
+
+// BOILERPLATE
+type InputIter = Lines>;
+
+pub fn get_input() -> InputIter {
+ let f = File::open("input").unwrap();
+ let br = BufReader::new(f);
+ br.lines()
+}
+
+fn duration_format(duration: Duration) -> String {
+ match duration.as_secs_f64() {
+ x if x > 1.0 => format!("{:.3}s", x),
+ x if x > 0.010 => format!("{:.3}ms", x * 1e3),
+ x => format!("{:.3}us", x * 1e6),
+ }
+}
+
+fn main() {
+ let input = get_input();
+ let start = Instant::now();
+ let ans1 = problem1(input);
+ let duration1 = start.elapsed();
+ println!("Problem 1 solution: {} [{}]", ans1, duration_format(duration1));
+
+ let input = get_input();
+ let start = Instant::now();
+ let ans2 = problem2(input);
+ let duration2 = start.elapsed();
+ println!("Problem 2 solution: {} [{}]", ans2, duration_format(duration2));
+ println!("Total duration: {}", duration_format(duration1 + duration2));
+}
+
+// PROBLEM 1 solution
+
+fn problem1(input: Lines) -> u64 {
+ 0
+}
+
+// PROBLEM 2 solution
+fn problem2(input: Lines) -> u64 {
+ 0
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::*;
+ use std::io::Cursor;
+
+ const EXAMPLE: &str = &"";
+
+ #[test]
+ fn problem1_example() {
+ let c = Cursor::new(EXAMPLE);
+ assert_eq!(problem1(c.lines()), 0);
+ }
+
+ #[test]
+ fn problem2_example() {
+ let c = Cursor::new(EXAMPLE);
+ assert_eq!(problem2(c.lines()), 0);
+ }
+}
diff --git a/2024/src/day1.rs b/2024/src/day1.rs
new file mode 100644
index 0000000..a0f909b
--- /dev/null
+++ b/2024/src/day1.rs
@@ -0,0 +1,92 @@
+use aoc_runner_derive::{aoc, aoc_generator};
+use rustc_hash::FxHashMap;
+use std::io::{BufRead, Lines};
+
+type HashMap = FxHashMap;
+
+#[aoc_generator(day1)]
+pub fn get_input(input: &[u8]) -> Locations {
+ Locations::from(input.lines())
+}
+
+#[derive(Clone)]
+pub struct Locations {
+ left: Vec,
+ right: Vec,
+}
+
+impl From> for Locations {
+ fn from(input: Lines) -> Self {
+ let mut left = Vec::new();
+ let mut right = Vec::new();
+ for line in input.map(|i| i.unwrap()) {
+ let parts: Vec<&str> = line.split_ascii_whitespace().collect();
+ left.push(parts[0].parse::().unwrap());
+ right.push(parts[1].parse::().unwrap());
+ }
+ Self { left, right }
+ }
+}
+
+impl Locations {
+ fn sort(&mut self) {
+ self.left.sort();
+ self.right.sort();
+ }
+ fn right_count(&self) -> HashMap {
+ let mut right_count: HashMap = HashMap::default();
+ for rval in &self.right {
+ right_count.insert(*rval, *right_count.get(rval).unwrap_or(&0) + 1);
+ }
+ right_count
+ }
+}
+
+// PROBLEM 1 solution
+#[aoc(day1, part1)]
+pub fn part1(locations: &Locations) -> u64 {
+ let mut locations = locations.clone();
+ locations.sort();
+
+ locations
+ .left
+ .iter()
+ .zip(locations.right)
+ .map(|(l, r)| u64::abs_diff(*l, r))
+ .sum()
+}
+
+// PROBLEM 2 solution
+#[aoc(day1, part2)]
+pub fn part2(locations: &Locations) -> u64 {
+ let right_count = locations.right_count();
+ locations
+ .left
+ .iter()
+ .map(|l| l * right_count.get(l).unwrap_or(&0))
+ .sum::()
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::day1::*;
+
+ const EXAMPLE: &[u8] = b"3 4
+4 3
+2 5
+1 3
+3 9
+3 3";
+
+ #[test]
+ fn part1_example() {
+ let input = get_input(EXAMPLE);
+ assert_eq!(part1(&input), 11);
+ }
+
+ #[test]
+ fn part2_example() {
+ let input = get_input(EXAMPLE);
+ assert_eq!(part2(&input), 31);
+ }
+}
diff --git a/2024/src/day10.rs b/2024/src/day10.rs
new file mode 100644
index 0000000..8f94402
--- /dev/null
+++ b/2024/src/day10.rs
@@ -0,0 +1,111 @@
+use aoc_runner_derive::{aoc, aoc_generator};
+use grid::Grid;
+use itertools::Itertools;
+use std::io::BufRead;
+
+#[aoc_generator(day10)]
+pub fn get_input(input: &[u8]) -> TrailMap {
+ TrailMap::from(input)
+}
+
+pub struct TrailMap {
+ map: Grid,
+}
+
+impl From for TrailMap {
+ fn from(input: T) -> Self {
+ Self { map: input.into() }
+ }
+}
+
+impl TrailMap {
+ fn trailheads(&self) -> Vec<(i64, i64)> {
+ self.map
+ .data
+ .iter()
+ .enumerate()
+ .filter(|(_, v)| **v == b'0')
+ .map(|(i, _v)| self.map.coord(i as i64).unwrap().into())
+ .collect_vec()
+ }
+ fn count_reachable_from(&self, pos: &(i64, i64), needle: u8, visited: &mut Grid) -> u64 {
+ if visited.get(pos) == Some(&true) {
+ return 0;
+ } else {
+ visited.set(pos, true);
+ }
+ let our_val = self.map.get(pos).unwrap();
+ if *our_val == needle {
+ return 1;
+ }
+ // adjacents that are +1
+ [(-1, 0), (1, 0), (0, -1), (0, 1)] // left, right, up, down
+ .iter()
+ .map(|(x_ofs, y_ofs)| (pos.0 + x_ofs, pos.1 + y_ofs)) // get target position
+ .map(|target_pos| (target_pos, self.map.get(&target_pos))) // get value at that position
+ .filter(|(_, val)| *val == Some(&(our_val + 1))) // only interested if it's our value + 1
+ .map(|(pos, _)| pos) // discard the value
+ .map(|pos| self.count_reachable_from(&pos, needle, visited))
+ .sum()
+ }
+
+ fn count_paths_to(&self, pos: &(i64, i64), needle: u8) -> u64 {
+ let our_val = self.map.get(pos).unwrap();
+ if *our_val == needle {
+ return 1;
+ }
+ [(-1, 0), (1, 0), (0, -1), (0, 1)] // left, right, up, down
+ .iter()
+ .map(|(x_ofs, y_ofs)| (pos.0 + x_ofs, pos.1 + y_ofs)) // get target position
+ .map(|target_pos| (target_pos, self.map.get(&target_pos))) // get value at that position
+ .filter(|(_, val)| *val == Some(&(our_val + 1))) // only interested if it's our value + 1
+ .map(|(pos, _)| pos) // discard the value
+ .map(|mov| self.count_paths_to(&mov, needle))
+ .sum::()
+ }
+}
+
+// PROBLEM 1 solution
+#[aoc(day10, part1)]
+pub fn part1(map: &TrailMap) -> u64 {
+ map.trailheads()
+ .iter()
+ .map(|pos| {
+ let mut visited = Grid::with_shape(map.map.width(), map.map.height(), false);
+ map.count_reachable_from(pos, b'9', &mut visited)
+ })
+ .sum()
+}
+
+// PROBLEM 2 solution
+#[aoc(day10, part2)]
+pub fn part2(map: &TrailMap) -> u64 {
+ map.trailheads()
+ .iter()
+ .map(|pos| map.count_paths_to(pos, b'9'))
+ .sum::()
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::day10::*;
+
+ const EXAMPLE: &[u8] = b"89010123
+78121874
+87430965
+96549874
+45678903
+32019012
+01329801
+10456732";
+
+ #[test]
+ fn part1_example() {
+ assert_eq!(part1(&get_input(EXAMPLE)), 36);
+ }
+
+ #[test]
+ fn part2_example() {
+ assert_eq!(part2(&get_input(EXAMPLE)), 81);
+ }
+}
diff --git a/2024/src/day11.rs b/2024/src/day11.rs
new file mode 100644
index 0000000..7029abf
--- /dev/null
+++ b/2024/src/day11.rs
@@ -0,0 +1,103 @@
+use aoc_runner_derive::aoc;
+use itertools::Itertools;
+use rustc_hash::FxHashMap;
+use std::iter::repeat;
+
+type IntType = u64;
+type CacheType = FxHashMap;
+
+#[derive(Clone, Debug, Hash, PartialEq, Eq)]
+struct Stone(IntType);
+struct Stones(Vec);
+
+enum BlinkResult {
+ One(Stone),
+ Two(Stone, Stone),
+}
+
+impl From<&str> for Stones {
+ fn from(input: &str) -> Self {
+ Stones(
+ input
+ .split_ascii_whitespace()
+ .map(|v| Stone(v.parse().unwrap()))
+ .collect_vec(),
+ )
+ }
+}
+
+fn parse(input: &str) -> Stones {
+ Stones::from(input)
+}
+
+impl Stone {
+ fn blink_once(&self) -> BlinkResult {
+ let n_digits = if self.0 == 0 { 1 } else { self.0.ilog10() + 1 };
+ if self.0 == 0 {
+ BlinkResult::One(Stone(1))
+ } else if n_digits % 2 == 0 {
+ let split_factor = (10 as IntType).pow(n_digits / 2);
+ let parts = (self.0 / split_factor, self.0 % split_factor);
+ BlinkResult::Two(Stone(parts.0), Stone(parts.1))
+ } else {
+ BlinkResult::One(Stone(&self.0 * 2024))
+ }
+ }
+}
+
+fn count_blinks(stone: &Stone, blink: usize, cache: &mut Vec) -> IntType {
+ if cache[blink].contains_key(stone) {
+ return cache[blink][stone];
+ }
+ let stones = stone.blink_once();
+ let result = if blink == 0 {
+ match stones {
+ BlinkResult::One(_) => 1,
+ BlinkResult::Two(_, _) => 2,
+ }
+ } else {
+ match stones {
+ BlinkResult::One(s) => count_blinks(&s, blink - 1, cache),
+ BlinkResult::Two(s1, s2) => count_blinks(&s1, blink - 1, cache) + count_blinks(&s2, blink - 1, cache),
+ }
+ };
+ cache[blink].insert(stone.clone(), result);
+ cache[blink][stone]
+}
+
+fn blink_stones(stones: Stones, blinks: usize) -> IntType {
+ let mut cache = Vec::from_iter(repeat(CacheType::default()).take(blinks));
+ stones
+ .0
+ .iter()
+ .map(|stone| count_blinks(stone, blinks - 1, &mut cache))
+ .sum()
+}
+
+#[aoc(day11, part1)]
+pub fn part1(input: &str) -> IntType {
+ let stones = parse(input);
+ blink_stones(stones, 25)
+}
+
+#[aoc(day11, part2)]
+pub fn part2(input: &str) -> IntType {
+ let stones = parse(input);
+ blink_stones(stones, 75)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ pub const EXAMPLE: &str = "125 17";
+
+ #[test]
+ fn part1_example() {
+ assert_eq!(part1(EXAMPLE), 55312);
+ }
+
+ #[test]
+ fn part2_example() {
+ assert_eq!(part2(EXAMPLE), 65601038650482);
+ }
+}
diff --git a/2024/src/day12.rs b/2024/src/day12.rs
new file mode 100644
index 0000000..bbaedc2
--- /dev/null
+++ b/2024/src/day12.rs
@@ -0,0 +1,176 @@
+use std::str::FromStr;
+
+use aoc_runner_derive::aoc;
+use grid::{Coord2d, Grid};
+
+pub struct Farm {
+ map: Grid,
+}
+
+impl FromStr for Farm {
+ type Err = as FromStr>::Err;
+ fn from_str(input: &str) -> Result {
+ Ok(Self { map: input.parse()? })
+ }
+}
+
+impl Farm {
+ fn compute_region(&self, pos: &Coord2d, visited: &mut Grid) -> (u64, u64) {
+ let our_plant = self.map.get(pos).unwrap();
+
+ visited.set(pos, true);
+
+ [(-1i64, 0i64), (1, 0), (0, -1), (0, 1)]
+ .map(|ofs| pos + ofs)
+ .iter()
+ .fold((1, 0), |(area, perimeter), adj| {
+ match self.map.get(adj) {
+ Some(plant) if plant == our_plant => {
+ if visited.get(adj) == Some(&false) {
+ // add the perimeter of the growth from there if not visited yet
+ let (add_area, add_perimeter) = self.compute_region(adj, visited);
+ (area + add_area, perimeter + add_perimeter)
+ } else {
+ (area, perimeter)
+ }
+ }
+ Some(_) | None => (area, perimeter + 1),
+ }
+ })
+ }
+
+ fn regions_cost(&self) -> u64 {
+ let mut visited = Grid::with_shape(self.map.width(), self.map.height(), false);
+ let mut cost = 0;
+ for y in 0..self.map.height() {
+ for x in 0..self.map.width() {
+ cost += match visited.get(&(x, y)) {
+ Some(false) => {
+ let (area, perim) = self.compute_region(
+ &Coord2d {
+ x: x as i64,
+ y: y as i64,
+ },
+ &mut visited,
+ );
+ area * perim
+ }
+ Some(_) | None => 0,
+ }
+ }
+ }
+ cost
+ }
+ fn count_corners(&self, pos: &Coord2d) -> u64 {
+ // NOTE: Iterating twice is faster than combining conditions in one pass
+ // BAB
+ // AAA has 4 inside corners (pos at centre). check that for AA A's exist and B doesn't for each rotation
+ // BAB AB
+ let our_plant = self.map.get(pos);
+ let inside_corners = [(1i64, 1i64), (-1, 1), (1, -1), (-1, -1)]
+ .iter()
+ .filter(|inside_corner| {
+ self.map.get(&(pos + **inside_corner)) != our_plant
+ && self.map.get(&(pos + (inside_corner.0, 0))) == our_plant
+ && self.map.get(&(pos + (0, inside_corner.1))) == our_plant
+ })
+ .count();
+ // BBB
+ // BAB has 4 outside corners (pos at centre). check that for AB the B are both not equal to A for each rot
+ // BBB BB B
+ let outside_corners = [(1i64, 1i64), (-1, 1), (1, -1), (-1, -1)]
+ .iter()
+ .filter(|outside_corner| {
+ self.map.get(&(pos + (outside_corner.0, 0))) != our_plant
+ && self.map.get(&(pos + (0, outside_corner.1))) != our_plant
+ })
+ .count();
+ (inside_corners + outside_corners) as u64
+ }
+ fn region_corners(&self, pos: &Coord2d, visited: &mut Grid) -> (u64, u64) {
+ let our_plant = self.map.get(pos).unwrap();
+
+ visited.set(pos, true);
+
+ [(-1i64, 0i64), (1, 0), (0, -1), (0, 1)]
+ .map(|ofs| pos + ofs)
+ .iter()
+ .fold((1, self.count_corners(pos)), |(area, corners), adj| {
+ match self.map.get(adj) {
+ Some(plant) if plant == our_plant => {
+ if visited.get(adj) == Some(&false) {
+ // add the perimeter of the growth from there if not visited yet
+ let (n_area, n_corners) = self.region_corners(adj, visited);
+ (area + n_area, corners + n_corners)
+ } else {
+ (area, corners)
+ }
+ }
+ Some(_) | None => (area, corners),
+ }
+ })
+ }
+ fn regions_discount_cost(&self) -> u64 {
+ let mut visited = self.map.same_shape(false);
+ let mut cost = 0;
+ for y in 0..self.map.height() {
+ for x in 0..self.map.width() {
+ cost += match visited.get(&(x, y)) {
+ Some(false) => {
+ let (area, corners) = self.region_corners(
+ &Coord2d {
+ x: x as i64,
+ y: y as i64,
+ },
+ &mut visited,
+ );
+ area * corners
+ }
+ Some(_) | None => 0,
+ }
+ }
+ }
+ cost
+ }
+}
+
+fn parse(input: &str) -> Farm {
+ input.parse().unwrap()
+}
+
+#[aoc(day12, part1)]
+pub fn part1(input: &str) -> u64 {
+ let farm = parse(input);
+ farm.regions_cost()
+}
+
+#[aoc(day12, part2)]
+pub fn part2(input: &str) -> u64 {
+ let farm = parse(input);
+ farm.regions_discount_cost()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ const EXAMPLE: &str = "RRRRIICCFF
+RRRRIICCCF
+VVRRRCCFFF
+VVRCCCJFFF
+VVVVCJJCFE
+VVIVCCJJEE
+VVIIICJJEE
+MIIIIIJJEE
+MIIISIJEEE
+MMMISSJEEE";
+
+ #[test]
+ fn part1_example() {
+ assert_eq!(part1(EXAMPLE), 1930);
+ }
+
+ #[test]
+ fn part2_example() {
+ assert_eq!(part2(EXAMPLE), 1206);
+ }
+}
diff --git a/2024/src/day13.rs b/2024/src/day13.rs
new file mode 100644
index 0000000..b4fc3b0
--- /dev/null
+++ b/2024/src/day13.rs
@@ -0,0 +1,135 @@
+use aoc_runner_derive::aoc;
+use itertools::Itertools;
+use regex::Regex;
+use std::str::Lines;
+
+#[derive(Debug, Clone)]
+pub struct MachineAction(i64, i64);
+
+#[derive(Debug, Clone)]
+struct ClawMachine {
+ button_a: MachineAction,
+ button_b: MachineAction,
+ prize: (i64, i64),
+}
+
+impl ClawMachine {
+ fn consume_from_input(input: &mut Lines) -> Option {
+ // consume any empty lines at the front
+ let ofs_re = Regex::new(r"X([+-]\d+), Y([+-]\d+)").unwrap();
+ let prize_re = Regex::new(r"X=(\d+), Y=(\d+)").unwrap();
+ // consume 3 lines - a, b, prize
+ if let Some((a_line, b_line, prize_line)) = input.filter(|l| !l.is_empty()).take(3).collect_tuple() {
+ let a_caps = ofs_re.captures(a_line).unwrap();
+ let b_caps = ofs_re.captures(b_line).unwrap();
+ let prize_caps = prize_re.captures(prize_line).unwrap();
+ let button_a = MachineAction(
+ a_caps.get(1).unwrap().as_str().parse().unwrap(),
+ a_caps.get(2).unwrap().as_str().parse().unwrap(),
+ );
+ let button_b = MachineAction(
+ b_caps.get(1).unwrap().as_str().parse().unwrap(),
+ b_caps.get(2).unwrap().as_str().parse().unwrap(),
+ );
+ let prize = (
+ prize_caps.get(1).unwrap().as_str().parse().unwrap(),
+ prize_caps.get(2).unwrap().as_str().parse().unwrap(),
+ );
+ Some(Self {
+ button_a,
+ button_b,
+ prize,
+ })
+ } else {
+ None
+ }
+ }
+ fn cost(moves: (i64, i64)) -> i64 {
+ moves.0 * 3 + moves.1
+ }
+ fn cheapest_prize(&self) -> Option {
+ let remainder_a = (self.button_b.0 * self.prize.1 - self.button_b.1 * self.prize.0)
+ % (self.button_b.0 * self.button_a.1 - self.button_a.0 * self.button_b.1);
+ let a = (self.button_b.0 * self.prize.1 - self.button_b.1 * self.prize.0)
+ / (self.button_b.0 * self.button_a.1 - self.button_a.0 * self.button_b.1);
+ let remainder_b = (self.prize.0 - (self.button_a.0 * a)) % self.button_b.0;
+ let b = (self.prize.0 - (self.button_a.0 * a)) / self.button_b.0;
+ if remainder_a == 0 && remainder_b == 0 {
+ Some(Self::cost((a, b)))
+ } else {
+ None
+ }
+ }
+ fn offset(&mut self, offset: i64) {
+ self.prize = (self.prize.0 + offset, self.prize.1 + offset)
+ }
+}
+
+#[derive(Debug, Clone)]
+struct ClawMachines {
+ machines: Vec,
+}
+
+impl From<&str> for ClawMachines {
+ fn from(input: &str) -> Self {
+ let mut machines = Vec::new();
+ let mut lines = input.lines();
+ while let Some(machine) = ClawMachine::consume_from_input(&mut lines) {
+ machines.push(machine);
+ }
+ Self { machines }
+ }
+}
+
+fn parse(input: &str) -> ClawMachines {
+ ClawMachines::from(input)
+}
+
+#[aoc(day13, part1)]
+fn part1(input: &str) -> i64 {
+ let machines = parse(input);
+ machines.machines.iter().filter_map(|m| m.cheapest_prize()).sum()
+}
+
+#[aoc(day13, part2)]
+fn part2(input: &str) -> i64 {
+ let mut machines = parse(input);
+ machines
+ .machines
+ .iter_mut()
+ .filter_map(|m| {
+ m.offset(10000000000000);
+ m.cheapest_prize()
+ })
+ .sum()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ const EXAMPLE: &str = "Button A: X+94, Y+34
+Button B: X+22, Y+67
+Prize: X=8400, Y=5400
+
+Button A: X+26, Y+66
+Button B: X+67, Y+21
+Prize: X=12748, Y=12176
+
+Button A: X+17, Y+86
+Button B: X+84, Y+37
+Prize: X=7870, Y=6450
+
+Button A: X+69, Y+23
+Button B: X+27, Y+71
+Prize: X=18641, Y=10279";
+
+ #[test]
+ fn part1_example() {
+ assert_eq!(part1(EXAMPLE), 480);
+ }
+
+ #[test]
+ fn part2_example() {
+ assert_eq!(part2(EXAMPLE), 875318608908);
+ }
+}
diff --git a/2024/src/day14.rs b/2024/src/day14.rs
new file mode 100644
index 0000000..ce53376
--- /dev/null
+++ b/2024/src/day14.rs
@@ -0,0 +1,178 @@
+use aoc_runner_derive::aoc;
+use colored::Colorize;
+use grid::{AsCoord2d, Grid};
+use misc::CustomWrapped;
+use nom::{
+ bytes::complete::tag,
+ character::complete::digit1,
+ combinator::{map_res, opt, recognize},
+ sequence::{preceded, separated_pair},
+ IResult,
+};
+use std::{fmt::Display, str::FromStr};
+
+type Coord = (CustomWrapped, CustomWrapped);
+struct Robot {
+ pos: Coord,
+ vel: (i64, i64),
+}
+
+struct Robots {
+ robots: Vec,
+ width: i64,
+ height: i64,
+}
+
+#[derive(Debug, Eq, PartialEq)]
+enum Quadrant {
+ NW = 0,
+ NE = 1,
+ SW = 2,
+ SE = 3,
+}
+
+fn nom_i64(input: &str) -> IResult<&str, i64> {
+ let (i, number) = map_res(recognize(preceded(opt(tag("-")), digit1)), i64::from_str)(input)?;
+ Ok((i, number))
+}
+fn nom_i64_pair(input: &str) -> IResult<&str, (i64, i64)> {
+ let (i, pair) = separated_pair(nom_i64, tag(","), nom_i64)(input)?;
+ Ok((i, pair))
+}
+
+impl Robot {
+ fn from_str(s: &str, bounds: (i64, i64)) -> Self {
+ let (s, pos) = preceded(tag("p="), nom_i64_pair)(s).unwrap();
+ let (_, vel) = preceded(tag(" v="), nom_i64_pair)(s).unwrap();
+ Self {
+ pos: (CustomWrapped::new(pos.0, bounds.0), CustomWrapped::new(pos.1, bounds.1)),
+ vel,
+ }
+ }
+ fn step(&mut self, count: i64) {
+ self.pos.0 += self.vel.x() * count;
+ self.pos.1 += self.vel.y() * count;
+ }
+ fn quad(&self, bounds: (i64, i64)) -> Option {
+ let splits = (bounds.0 / 2, bounds.1 / 2);
+ if self.pos.0 < splits.0 && self.pos.1 < splits.1 {
+ Some(Quadrant::NW)
+ } else if self.pos.0 > splits.0 && self.pos.1 < splits.1 {
+ Some(Quadrant::NE)
+ } else if self.pos.0 < splits.0 && self.pos.1 > splits.1 {
+ Some(Quadrant::SW)
+ } else if self.pos.0 > splits.0 && self.pos.1 > splits.1 {
+ Some(Quadrant::SE)
+ } else {
+ None
+ }
+ }
+}
+
+impl Robots {
+ fn from_vec(robots: Vec, width: i64, height: i64) -> Self {
+ Self { robots, width, height }
+ }
+ fn as_grid(&self) -> Grid {
+ let mut grid = Grid::with_shape(self.width as usize, self.height as usize, 0usize);
+ for r in &self.robots {
+ grid.increment(&(r.pos.0.val, r.pos.1.val), 1usize);
+ }
+ grid
+ }
+ fn count_quads(&self) -> [u64; 4] {
+ let mut counts = [0; 4];
+ for r in &self.robots {
+ if let Some(q) = r.quad((self.width, self.height)) {
+ counts[q as usize] += 1
+ }
+ }
+ counts
+ }
+ fn step(&mut self, count: i64) {
+ for robot in &mut self.robots {
+ robot.step(count)
+ }
+ }
+}
+
+impl Display for Robots {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let grid = self.as_grid();
+ for row in 0..grid.height() {
+ for col in 0..grid.width() {
+ if *grid.get(&(col, row)).unwrap() != 0 {
+ "█".green().fmt(f)?;
+ } else {
+ " ".color(colored::Color::Black).fmt(f)?;
+ }
+ }
+ writeln!(f)?
+ }
+ Ok(())
+ }
+}
+
+fn parse(input: &str, width: i64, height: i64) -> Vec {
+ input.lines().map(|l| Robot::from_str(l, (width, height))).collect()
+}
+
+fn part1_impl(input: &str, width: i64, height: i64) -> u64 {
+ let mut robots = Robots::from_vec(parse(input, width, height), width, height);
+ robots.step(100);
+ let counts = robots.count_quads();
+ counts.iter().product()
+}
+
+#[aoc(day14, part1)]
+pub fn part1(input: &str) -> u64 {
+ part1_impl(input, 101, 103)
+}
+
+#[aoc(day14, part2)]
+pub fn part2(input: &str) -> u64 {
+ let width = 101;
+ let height = 103;
+ let mut robots = Robots::from_vec(parse(input, width, height), width, height);
+ for i in 1.. {
+ robots.step(1);
+ // collect into lines
+ let g = robots.as_grid();
+ if g.data
+ .chunk_by(|a, b| *a != 0 && *b != 0)
+ .filter(|c| !c.is_empty() && c[0] != 0)
+ .any(|c| c.len() > width as usize / 10)
+ {
+ return i;
+ }
+ }
+ unreachable!()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ const EXAMPLE: &str = "p=0,4 v=3,-3
+p=6,3 v=-1,-3
+p=10,3 v=-1,2
+p=2,0 v=2,-1
+p=0,0 v=1,3
+p=3,0 v=-2,-2
+p=7,6 v=-1,-3
+p=3,0 v=-1,-2
+p=9,3 v=2,3
+p=7,3 v=-1,2
+p=2,4 v=2,-3
+p=9,5 v=-3,-3";
+
+ #[test]
+ fn part1_example() {
+ assert_eq!(part1_impl(EXAMPLE, 11, 7), 12);
+ }
+
+ // part 2 does not converge using the test vector
+ // #[test]
+ // fn part2_example() {
+ // // assert_eq!(part2(EXAMPLE), 0);
+ // }
+}
diff --git a/2024/src/day15.rs b/2024/src/day15.rs
new file mode 100644
index 0000000..08149fe
--- /dev/null
+++ b/2024/src/day15.rs
@@ -0,0 +1,241 @@
+use aoc_runner_derive::aoc;
+use grid::{AsCoord2d, Coord2d, Grid};
+use itertools::Itertools;
+use std::{fmt::Display, io::Cursor, str::FromStr};
+
+struct Warehouse {
+ map: Grid,
+ robot_pos: Coord2d,
+}
+
+impl Display for Warehouse {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.map.fmt(f)
+ }
+}
+
+impl Warehouse {
+ fn step_robot(&mut self, dir: Move) {
+ let start = self.robot_pos;
+ if self.push(&start, &dir) {
+ self.robot_pos = &self.robot_pos + dir.ofs();
+ }
+ }
+
+ fn push(&mut self, pos: &Coord2d, dir: &Move) -> bool {
+ if self.can_push(pos, dir) {
+ let target = pos + dir.ofs();
+ match self.map.get(&target).unwrap() {
+ b'#' => {}
+ b'.' => self.map.swap(target, pos),
+ b'O' => {
+ self.push(&target, dir);
+ self.map.swap(target, pos);
+ }
+ b'[' | b']' if *dir == Move::Left || *dir == Move::Right => {
+ self.push(&target, dir);
+ self.map.swap(target, pos)
+ }
+ b']' => {
+ // move both parts
+ self.push(&target, dir);
+ self.push(&(&target + (-1, 0)), dir);
+ self.map.swap(target, pos);
+ }
+ b'[' => {
+ self.push(&target, dir);
+ self.push(&(&target + (1, 0)), dir);
+ self.map.swap(target, pos);
+ }
+ c => panic!("unexpected char {}", c),
+ }
+ return true;
+ }
+ false
+ }
+
+ fn can_push(&mut self, pos: &Coord2d, dir: &Move) -> bool {
+ let target = pos + dir.ofs();
+ match self.map.get(&target).unwrap() {
+ b'#' => false,
+ b'.' => true,
+ b'O' => self.can_push(&target, dir),
+ b'[' | b']' if *dir == Move::Left || *dir == Move::Right => self.can_push(&target, dir),
+ b']' => self.can_push(&target, dir) && self.can_push(&(&target + (-1, 0)), dir),
+ b'[' => self.can_push(&target, dir) && self.can_push(&(&target + (1, 0)), dir),
+ c => panic!("unexpected char {}", c),
+ }
+ }
+
+ fn embiggen(&mut self) {
+ let new_lines = (0..self.map.height())
+ .map(|r| self.map.row(r as i64).unwrap())
+ .map(|row| {
+ row.iter()
+ .flat_map(|c| match c {
+ b'#' => ['#', '#'],
+ b'O' => ['[', ']'],
+ b'.' => ['.', '.'],
+ b'@' => ['@', '.'],
+ c => panic!("unexpected character {}", c),
+ })
+ .collect::()
+ })
+ .join("\n");
+ self.map = Grid::from(Cursor::new(new_lines.as_str()));
+ self.robot_pos = self.map.find(&b'@').unwrap().to_coord();
+ }
+
+ fn score(&self) -> i64 {
+ self.map
+ .data
+ .iter()
+ .enumerate()
+ .filter(|(_, v)| **v == b'O' || **v == b'[')
+ .map(|(i, _)| self.map.coord(i as i64).unwrap().y() * 100 + self.map.coord(i as i64).unwrap().x())
+ .sum()
+ }
+}
+
+#[derive(Debug, Eq, PartialEq)]
+enum Move {
+ Left,
+ Right,
+ Up,
+ Down,
+}
+
+impl Display for Move {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Left => f.write_str("Left"),
+ Self::Right => f.write_str("Right"),
+ Self::Up => f.write_str("Up"),
+ Self::Down => f.write_str("Down"),
+ }
+ }
+}
+
+impl From for Move {
+ fn from(c: char) -> Self {
+ match c {
+ '<' => Self::Left,
+ '>' => Self::Right,
+ '^' => Self::Up,
+ 'v' => Self::Down,
+ c => panic!("invalid move {}", c),
+ }
+ }
+}
+
+impl Move {
+ fn ofs(&self) -> (i64, i64) {
+ match self {
+ Move::Left => (-1, 0),
+ Move::Right => (1, 0),
+ Move::Up => (0, -1),
+ Move::Down => (0, 1),
+ }
+ }
+}
+
+#[derive(Debug)]
+struct MovePlan(Vec);
+
+impl FromStr for MovePlan {
+ type Err = Box;
+ fn from_str(s: &str) -> Result {
+ Ok(MovePlan(s.chars().filter(|c| *c != '\n').map(Move::from).collect()))
+ }
+}
+
+fn parse(input: &str) -> (Warehouse, MovePlan) {
+ let lines = input.lines().collect_vec();
+ let parts = lines.split(|l| l.is_empty()).map(|ls| ls.join("\n")).collect_vec();
+ let map: Grid = parts[0].parse().unwrap();
+ let wh = Warehouse {
+ robot_pos: map.find(&b'@').unwrap().to_coord(),
+ map,
+ };
+ let moves = parts[1].parse().unwrap();
+
+ (wh, moves)
+}
+
+#[aoc(day15, part1)]
+pub fn part1(input: &str) -> i64 {
+ let (mut wh, moves) = parse(input);
+ for m in moves.0 {
+ wh.step_robot(m);
+ }
+ wh.score()
+}
+
+#[aoc(day15, part2)]
+pub fn part2(input: &str) -> i64 {
+ let (mut wh, moves) = parse(input);
+ wh.embiggen();
+
+ for m in moves.0 {
+ wh.step_robot(m);
+ }
+ wh.score()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ const EXAMPLE1: &str = "########
+#..O.O.#
+##@.O..#
+#...O..#
+#.#.O..#
+#...O..#
+#......#
+########
+
+<^^>>>vv>v<<";
+ const EXAMPLE2: &str = "##########
+#..O..O.O#
+#......O.#
+#.OO..O.O#
+#..O@..O.#
+#O#..O...#
+#O..O..O.#
+#.OO.O.OO#
+#....O...#
+##########
+
+^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^
+vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv<
+<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^
+^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^><
+^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^
+<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<>
+^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><
+v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^";
+
+ const EXAMPLE3: &str = "#######
+#...#.#
+#.....#
+#..OO@#
+#..O..#
+#.....#
+#######
+
+ (CoordType, CoordType) {
+ match self {
+ FacingDirection::East => (1, 0),
+ FacingDirection::South => (0, 1),
+ FacingDirection::West => (-1, 0),
+ FacingDirection::North => (0, -1),
+ }
+ }
+ fn reachable(&self) -> &[FacingDirection; 3] {
+ // Can move perpendicularly or the same direction, backwards would always increase path cost
+ match self {
+ FacingDirection::East => &[FacingDirection::East, FacingDirection::North, FacingDirection::South],
+ FacingDirection::West => &[FacingDirection::West, FacingDirection::North, FacingDirection::South],
+ FacingDirection::South => &[FacingDirection::South, FacingDirection::East, FacingDirection::West],
+ FacingDirection::North => &[FacingDirection::North, FacingDirection::East, FacingDirection::West],
+ }
+ }
+}
+
+#[derive(Clone, Eq, PartialEq, Debug)]
+struct State {
+ cost: usize,
+ position: Coord,
+ facing: FacingDirection,
+}
+
+impl Ord for State {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ other
+ .cost
+ .cmp(&self.cost)
+ .then_with(|| self.position.cmp(&other.position))
+ .then_with(|| self.facing.cmp(&other.facing))
+ }
+}
+
+impl PartialOrd for State {
+ fn partial_cmp(&self, other: &Self) -> Option {
+ Some(self.cmp(other))
+ }
+}
+
+#[derive(Clone, Eq, PartialEq, Debug)]
+struct PathState {
+ state: State,
+ path: Vec,
+}
+
+impl Ord for PathState {
+ fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+ self.state.cmp(&other.state)
+ }
+}
+impl PartialOrd for PathState {
+ fn partial_cmp(&self, other: &Self) -> Option {
+ Some(self.cmp(other))
+ }
+}
+
+struct Maze {
+ map: Grid,
+}
+
+impl FromStr for Maze {
+ type Err = Box;
+ fn from_str(s: &str) -> Result {
+ let map: Grid = s.parse()?;
+
+ Ok(Self { map })
+ }
+}
+
+impl Maze {
+ fn valid_moves<'a>(&'a self, state: &'a State) -> impl Iterator- + use<'a> {
+ let reachable = state.facing.reachable();
+ reachable
+ .iter()
+ .map(|dir| (dir, (state.position.0 + dir.ofs().0, state.position.1 + dir.ofs().1)))
+ .filter(|(_, pos)| self.map.get(pos).is_some_and(|c| *c != b'#'))
+ .map(|(dir, pos)| State {
+ facing: *dir,
+ position: pos,
+ cost: if *dir == state.facing {
+ state.cost + 1
+ } else {
+ state.cost + 1001
+ },
+ })
+ }
+ fn dijkstra(&self) -> usize {
+ let Coord2d {x: start_x, y: start_y} = self.map.find(&b'S').expect("can't find start");
+ let start = (start_x as CoordType, start_y as CoordType);
+
+ let Coord2d {x: finish_x, y: finish_y} = self.map.find(&b'E').expect("can't find finish");
+ let finish = (finish_x as CoordType, finish_y as CoordType);
+
+ let mut distances = HashMap::new();
+ let mut queue = BinaryHeap::new();
+
+ distances.insert((start, FacingDirection::East), 0);
+ queue.push(State {
+ cost: 0,
+ position: start,
+ facing: FacingDirection::East,
+ });
+
+ while let Some(state) = queue.pop() {
+ if state.position == finish {
+ return state.cost;
+ }
+
+ if distances
+ .get(&(state.position, state.facing))
+ .is_some_and(|v| state.cost > *v)
+ {
+ continue;
+ }
+
+ for new_state in self.valid_moves(&state) {
+ if distances
+ .get(&(new_state.position, new_state.facing))
+ .is_none_or(|best_cost| new_state.cost < *best_cost)
+ {
+ distances.insert((new_state.position, new_state.facing), new_state.cost);
+ queue.push(new_state);
+ }
+ }
+ }
+ usize::MAX
+ }
+ fn path_dijkstra(&mut self) -> (usize, Vec>) {
+ let Coord2d {x: start_x, y: start_y} = self.map.find(&b'S').expect("can't find start");
+ let start = (start_x as CoordType, start_y as CoordType);
+
+ let Coord2d {x: finish_x, y: finish_y} = self.map.find(&b'E').expect("can't find finish");
+ let finish = (finish_x as CoordType, finish_y as CoordType);
+
+ let mut distances = HashMap::new();
+ let mut queue = BinaryHeap::with_capacity(self.map.data.len());
+ let mut best_paths = Vec::new();
+ let mut best_cost = usize::MAX;
+
+ distances.insert((start, FacingDirection::East), 0);
+ queue.push(PathState {
+ state: State {
+ cost: 0,
+ position: start,
+ facing: FacingDirection::East,
+ },
+ path: Vec::new(),
+ });
+
+ while let Some(PathState { state, mut path }) = queue.pop() {
+ if distances
+ .get(&(state.position, state.facing))
+ .is_some_and(|v| state.cost > *v)
+ {
+ continue;
+ }
+ if state.position == finish {
+ match state.cost.cmp(&best_cost) {
+ Ordering::Less => {
+ path.push(state.position);
+ best_paths.clear();
+ best_paths.push(path);
+ best_cost = state.cost
+ }
+ Ordering::Equal => {
+ path.push(state.position);
+ best_paths.push(path);
+ }
+ _ => {}
+ }
+ continue;
+ }
+
+ for new_state in self.valid_moves(&state) {
+ if distances
+ .get(&(new_state.position, new_state.facing))
+ .is_none_or(|best_cost| new_state.cost <= *best_cost)
+ {
+ let mut new_path = path.clone();
+ new_path.push(state.position);
+ distances.insert((new_state.position, new_state.facing), new_state.cost);
+ queue.push(PathState {
+ state: new_state,
+ path: new_path,
+ });
+ }
+ }
+ }
+ (best_cost, best_paths)
+ }
+}
+
+fn parse(input: &str) -> Maze {
+ input.parse().unwrap()
+}
+
+#[aoc(day16, part1)]
+pub fn part1(input: &str) -> usize {
+ let maze = parse(input);
+ maze.dijkstra()
+}
+
+#[aoc(day16, part2)]
+pub fn part2(input: &str) -> usize {
+ let mut maze = parse(input);
+ let best_paths = maze.path_dijkstra();
+
+ let mut path_map = maze.map.same_shape(false);
+ for tile in best_paths.1.iter().flatten() {
+ path_map.set(tile, true);
+ }
+ path_map.count(&true)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ const EXAMPLE1: &str = "###############
+#.......#....E#
+#.#.###.#.###.#
+#.....#.#...#.#
+#.###.#####.#.#
+#.#.#.......#.#
+#.#.#####.###.#
+#...........#.#
+###.#.#####.#.#
+#...#.....#.#.#
+#.#.#.###.#.#.#
+#.....#...#.#.#
+#.###.#.#.#.#.#
+#S..#.....#...#
+###############";
+
+ const EXAMPLE2: &str = "#################
+#...#...#...#..E#
+#.#.#.#.#.#.#.#.#
+#.#.#.#...#...#.#
+#.#.#.#.###.#.#.#
+#...#.#.#.....#.#
+#.#.#.#.#.#####.#
+#.#...#.#.#.....#
+#.#.#####.#.###.#
+#.#.#.......#...#
+#.#.###.#####.###
+#.#.#...#.....#.#
+#.#.#.#####.###.#
+#.#.#.........#.#
+#.#.#.#########.#
+#S#.............#
+#################";
+
+ #[test]
+ fn part1_example1() {
+ assert_eq!(part1(EXAMPLE1), 7036);
+ }
+
+ #[test]
+ fn part1_example2() {
+ assert_eq!(part1(EXAMPLE2), 11048);
+ }
+
+ #[test]
+ fn part2_example1() {
+ assert_eq!(part2(EXAMPLE1), 45);
+ }
+
+ #[test]
+ fn part2_example2() {
+ assert_eq!(part2(EXAMPLE2), 64);
+ }
+}
diff --git a/2024/src/day17.rs b/2024/src/day17.rs
new file mode 100644
index 0000000..ae37743
--- /dev/null
+++ b/2024/src/day17.rs
@@ -0,0 +1,298 @@
+use aoc_runner_derive::aoc;
+use itertools::Itertools;
+use regex::Regex;
+
+#[derive(Debug, Clone, Copy)]
+enum Register {
+ A = 0,
+ B = 1,
+ C = 2,
+}
+impl From for Register {
+ fn from(value: usize) -> Self {
+ match value {
+ 0 => Register::A,
+ 1 => Register::B,
+ 2 => Register::C,
+ v => panic!("invalid register address {}", v),
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+enum Opcode {
+ Adv = 0,
+ Bxl = 1,
+ Bst = 2,
+ Jnz = 3,
+ Bxc = 4,
+ Out = 5,
+ Bdv = 6,
+ Cdv = 7,
+}
+
+impl From for Opcode {
+ fn from(value: i64) -> Self {
+ match value {
+ 0 => Opcode::Adv,
+ 1 => Opcode::Bxl,
+ 2 => Opcode::Bst,
+ 3 => Opcode::Jnz,
+ 4 => Opcode::Bxc,
+ 5 => Opcode::Out,
+ 6 => Opcode::Bdv,
+ 7 => Opcode::Cdv,
+ v => panic!("invalid opcode {}", v),
+ }
+ }
+}
+
+impl Opcode {
+ fn interp_operand(&self, value: i64) -> Operand {
+ match self {
+ Self::Adv | Self::Bst | Self::Out | Self::Bdv | Self::Cdv => Operand::new_combo(value),
+ Self::Bxl | Self::Jnz => Operand::Literal(value),
+ Self::Bxc => Operand::Ignore,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+enum Operand {
+ Literal(i64),
+ Load(Register),
+ Ignore,
+}
+
+impl Operand {
+ fn new_combo(value: i64) -> Self {
+ match value {
+ 0..=3 => Operand::Literal(value),
+ 4 => Operand::Load(Register::A),
+ 5 => Operand::Load(Register::B),
+ 6 => Operand::Load(Register::C),
+ 7 => panic!("reserved combo operand 7"),
+ i => panic!("invalid combo operand {}", i),
+ }
+ }
+ fn value(self, m: &Machine) -> i64 {
+ match self {
+ Self::Literal(i) => i,
+ Self::Load(reg) => *m.registers.load(reg),
+ Self::Ignore => panic!("can't read ignored operand"),
+ }
+ }
+}
+
+#[derive(Debug)]
+struct RegisterFile {
+ file: [T; SIZE],
+}
+
+impl, const SIZE: usize> RegisterFile {
+ fn load(&self, reg: Register) -> &T {
+ &self.file[reg as usize]
+ }
+ fn store(&mut self, reg: Register, val: T) {
+ self.file[reg as usize] = val;
+ }
+ fn reset(&mut self) {
+ self.file.fill(0.into());
+ }
+}
+
+#[derive(Debug, Copy, Clone)]
+struct Instruction {
+ opcode: Opcode,
+ operand: Operand,
+}
+
+impl Instruction {
+ fn exec(&self, m: &mut Machine) {
+ match self.opcode {
+ Opcode::Adv => self.adv(m),
+ Opcode::Bxl => self.bxl(m),
+ Opcode::Bst => self.bst(m),
+ Opcode::Jnz => self.jnz(m),
+ Opcode::Bxc => self.bxc(m),
+ Opcode::Out => self.out(m),
+ Opcode::Bdv => self.bdv(m),
+ Opcode::Cdv => self.cdv(m),
+ }
+ }
+ fn adv(&self, m: &mut Machine) {
+ let num = m.registers.load(Register::A);
+ let denom = 1 << self.operand.value(m);
+ m.registers.store(Register::A, num / denom);
+ m.advance();
+ }
+ fn bxl(&self, m: &mut Machine) {
+ let lhs = self.operand.value(m);
+ let rhs = m.registers.load(Register::B);
+ m.registers.store(Register::B, lhs ^ rhs);
+ m.advance();
+ }
+ fn bst(&self, m: &mut Machine) {
+ m.registers.store(Register::B, self.operand.value(m) % 8);
+ m.advance();
+ }
+ fn jnz(&self, m: &mut Machine) {
+ if *m.registers.load(Register::A) == 0 {
+ m.advance();
+ } else {
+ m.jump(self.operand.value(m) as usize);
+ }
+ }
+ fn bxc(&self, m: &mut Machine) {
+ let lhs = m.registers.load(Register::B);
+ let rhs = m.registers.load(Register::C);
+ m.registers.store(Register::B, lhs ^ rhs);
+ m.advance();
+ }
+ fn out(&self, m: &mut Machine) {
+ m.out_file.push(self.operand.value(m) % 8);
+ m.advance();
+ }
+ fn bdv(&self, m: &mut Machine) {
+ let num = m.registers.load(Register::A);
+ let denom = 1 << self.operand.value(m);
+ m.registers.store(Register::B, num / denom);
+ m.advance();
+ }
+ fn cdv(&self, m: &mut Machine) {
+ let num = m.registers.load(Register::A);
+ let denom = 1 << self.operand.value(m);
+ m.registers.store(Register::C, num / denom);
+ m.advance();
+ }
+}
+
+#[derive(Debug)]
+pub struct Machine {
+ registers: RegisterFile<3, i64>,
+ program: Vec,
+ program_raw: Vec,
+ ip: usize,
+ out_file: Vec,
+}
+
+impl Machine {
+ fn run(&mut self) {
+ let program = self.program.clone();
+ while let Some(inst) = program.get(self.ip) {
+ inst.exec(self);
+ }
+ }
+ fn advance(&mut self) {
+ self.ip += 1;
+ }
+ fn jump(&mut self, addr: usize) {
+ self.ip = addr;
+ }
+ fn reset(&mut self) {
+ self.registers.reset();
+ self.ip = 0;
+ self.out_file.clear();
+ }
+}
+
+fn parse(input: &str) -> Machine {
+ let reg_re = Regex::new(r"Register ([ABC]): (\d+)").unwrap();
+ let prog_re = Regex::new(r"Program: ((\d+,)*\d+)").unwrap();
+
+ let mut registers: RegisterFile<3, i64> = RegisterFile { file: [0; 3] };
+ let mut program = Vec::new();
+ let mut program_raw = Vec::new();
+ for line in input.lines() {
+ if let Some(caps) = reg_re.captures(line) {
+ let address = (caps[1].as_bytes()[0] - b'A') as usize;
+ let value = caps[2].parse().unwrap();
+ registers.store(address.into(), value);
+ continue;
+ }
+ if let Some(caps) = prog_re.captures(line) {
+ let instructions = caps[1].split(',');
+ for (inst, operand) in instructions.tuples() {
+ let opcode = inst.parse::().unwrap();
+ let operand = operand.parse::().unwrap();
+ program_raw.push(opcode);
+ program_raw.push(operand);
+ let opcode: Opcode = opcode.into();
+ program.push(Instruction {
+ operand: opcode.interp_operand(operand),
+ opcode,
+ });
+ }
+ }
+ }
+
+ Machine {
+ registers,
+ program,
+ program_raw,
+ out_file: Vec::new(),
+ ip: 0,
+ }
+}
+
+#[aoc(day17, part1)]
+pub fn part1(input: &str) -> String {
+ let mut machine = parse(input);
+ machine.run();
+ machine.out_file.iter().map(|n| n.to_string()).join(",")
+}
+
+// The program must be of the correct form to be solvable
+pub fn solve(m: &mut Machine, guess: i64, i: usize) -> Option {
+ if i == m.program_raw.len() {
+ return Some(guess);
+ }
+ let program_pos = m.program_raw.len() - 1 - i;
+ let goal_digit = m.program_raw[program_pos];
+
+ for digit in 0..8 {
+ let local_guess = (digit << (program_pos * 3)) + guess;
+ m.reset();
+ m.registers.store(Register::A, local_guess);
+ m.run();
+ if m.out_file.len() == m.program_raw.len() && m.out_file[program_pos] == goal_digit {
+ if let Some(sol) = solve(m, local_guess, i + 1) {
+ return Some(sol);
+ }
+ }
+ }
+ None
+}
+
+#[aoc(day17, part2)]
+pub fn part2(input: &str) -> i64 {
+ let mut machine = parse(input);
+
+ solve(&mut machine, 0, 0).expect("expected a solution")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ const EXAMPLE1: &str = "Register A: 729
+Register B: 0
+Register C: 0
+
+Program: 0,1,5,4,3,0";
+
+ const EXAMPLE2: &str = "Register A: 2024
+Register B: 0
+Register C: 0
+
+Program: 0,3,5,4,3,0";
+
+ #[test]
+ fn part1_example() {
+ assert_eq!(part1(EXAMPLE1), "4,6,3,5,6,3,5,2,1,0");
+ }
+
+ #[test]
+ fn part2_example() {
+ assert_eq!(part2(EXAMPLE2), 117440);
+ }
+}
diff --git a/2024/src/day18.rs b/2024/src/day18.rs
new file mode 100644
index 0000000..8270d7e
--- /dev/null
+++ b/2024/src/day18.rs
@@ -0,0 +1,286 @@
+use aoc_runner_derive::aoc;
+use grid::Grid;
+use itertools::Itertools;
+use std::{
+ cmp::Reverse,
+ collections::{BinaryHeap, VecDeque},
+};
+
+#[derive(Clone)]
+struct MemoryMap {
+ map: Grid,
+ byte_stream: Vec<(i64, i64)>,
+}
+
+trait PathTrack {
+ const DOES_WORK: bool = true;
+ fn new() -> Self;
+ fn push(&mut self, pos: (i64, i64));
+ fn finalize(&mut self) {}
+}
+
+struct LengthPath(usize);
+impl PathTrack for LengthPath {
+ fn new() -> Self {
+ LengthPath(0)
+ }
+ fn push(&mut self, _: (i64, i64)) {
+ self.0 += 1
+ }
+}
+
+impl PathTrack for Vec<(i64, i64)> {
+ fn new() -> Self {
+ Vec::new()
+ }
+ fn push(&mut self, pos: (i64, i64)) {
+ self.push(pos);
+ }
+ fn finalize(&mut self) {
+ self.reverse();
+ }
+}
+
+struct NoopTrack {}
+impl PathTrack for NoopTrack {
+ const DOES_WORK: bool = false;
+ fn new() -> Self {
+ Self {}
+ }
+ fn push(&mut self, _: (i64, i64)) {}
+}
+
+impl MemoryMap {
+ fn from_str(input: &str, width: usize, height: usize) -> Self {
+ let map = Grid::with_shape(width, height, true);
+ let mut byte_stream = Vec::new();
+
+ for line in input.lines() {
+ if let Some((x, y)) = line.split_once(',') {
+ let pos: (i64, i64) = (x.parse().unwrap(), y.parse().unwrap());
+ byte_stream.push(pos);
+ }
+ }
+
+ Self { map, byte_stream }
+ }
+
+ fn place_byte(&mut self, i: usize) {
+ let pos = self.byte_stream[i];
+ self.map.set(&pos, false);
+ }
+
+ fn place_bytes(&mut self, start: usize, end: usize) {
+ for i in start..=end {
+ self.place_byte(i);
+ }
+ }
+
+ fn valid_moves<'a>(&'a self, pos: &'a (i64, i64)) -> impl Iterator
- + 'a {
+ ([(0, 1), (1, 0), (0, -1), (-1, 0)])
+ .iter()
+ .filter(|ofs| self.map.get(&(pos.0 + ofs.0, pos.1 + ofs.1)).is_some_and(|v| *v))
+ .map(|ofs| (pos.0 + ofs.0, pos.1 + ofs.1))
+ }
+
+ fn bfs(&self, start: (i64, i64)) -> Option {
+ let goal = (self.map.width() as i64 - 1, self.map.height() as i64 - 1);
+
+ let mut visited = self.map.same_shape(false);
+ let mut prev = self.map.same_shape((i64::MAX, i64::MAX));
+ let mut queue = VecDeque::new();
+
+ visited.set(&start, true);
+ queue.push_back((0, start));
+
+ while let Some((depth, pos)) = queue.pop_front() {
+ if pos == goal {
+ if T::DOES_WORK {
+ let mut visited_pos = goal;
+ let mut path = T::new();
+ path.push(pos);
+ while let Some(next) = prev.get(&visited_pos) {
+ visited_pos = *next;
+ path.push(*next);
+ if *next == start {
+ path.finalize();
+ return Some(path);
+ }
+ }
+ } else {
+ return Some(T::new());
+ }
+ }
+
+ // if visited.get(&pos).is_some_and(|v| *v) {
+ // continue;
+ // }
+
+ let moves = self.valid_moves(&pos);
+ for new_pos in moves {
+ if visited.get(&new_pos).is_none_or(|v| !v) {
+ visited.set(&new_pos, true);
+ if T::DOES_WORK {
+ prev.set(&new_pos, pos);
+ }
+ queue.push_back((depth + 1, new_pos));
+ }
+ }
+ }
+ None
+ }
+
+ #[allow(dead_code)] // will be moved to Grid at some point
+ fn dijkstra(&self, start: (i64, i64)) -> Option {
+ let goal = (self.map.width() as i64 - 1, self.map.height() as i64 - 1);
+
+ let mut costs = self.map.same_shape(i64::MAX);
+ let mut prev = self.map.same_shape((i64::MAX, i64::MAX));
+ let mut queue = BinaryHeap::new();
+
+ costs.set(&start, 0);
+ queue.push((Reverse(0), start));
+
+ while let Some((cost, pos)) = queue.pop() {
+ if pos == goal {
+ if T::DOES_WORK {
+ let mut visited_pos = goal;
+ let mut path = T::new();
+ path.push(pos);
+ while let Some(next) = prev.get(&visited_pos) {
+ visited_pos = *next;
+ path.push(*next);
+ if *next == start {
+ path.finalize();
+ return Some(path);
+ }
+ }
+ } else {
+ return Some(T::new());
+ }
+ }
+
+ if costs.get(&pos).is_some_and(|v| cost.0 > *v) {
+ continue;
+ }
+
+ let moves = self.valid_moves(&pos);
+ for new_pos in moves {
+ if costs.get(&new_pos).is_none_or(|best_cost| cost.0 + 1 < *best_cost) {
+ costs.set(&new_pos, cost.0 + 1);
+ if T::DOES_WORK {
+ prev.set(&new_pos, pos);
+ }
+ queue.push((Reverse(cost.0 + 1), new_pos));
+ }
+ }
+ }
+ None
+ }
+}
+
+pub fn part1_impl(input: &str, width: usize, height: usize, initial_safe_byte_count: usize) -> usize {
+ let mut map = MemoryMap::from_str(input, width, height);
+ map.place_bytes(0, initial_safe_byte_count - 1);
+ let path = map.bfs::((0, 0)).expect("no path found");
+
+ path.0 - 1 // count edges, not visited nodes (start doesn't count)
+}
+
+// My original devised solution
+pub fn part2_impl_brute(input: &str, width: usize, height: usize, initial_safe_byte_count: usize) -> (i64, i64) {
+ let mut input_map = MemoryMap::from_str(input, width, height);
+ input_map.place_bytes(0, initial_safe_byte_count - 1);
+
+ let mut path = input_map.bfs::>((0, 0)).expect("no path found");
+
+ for byte in initial_safe_byte_count..input_map.byte_stream.len() {
+ input_map.place_byte(byte);
+ // If it obstructs our best path, we need to do a new path search
+ if let Some((obs_at, _)) = path.iter().find_position(|v| *v == &input_map.byte_stream[byte]) {
+ let (before, _) = path.split_at(obs_at);
+
+ if let Some(new_path) = input_map.bfs::>(path[obs_at - 1]) {
+ path = [before, &new_path].concat();
+ } else {
+ return input_map.byte_stream[byte];
+ }
+ }
+ }
+ panic!("no bytes block route");
+}
+
+// Optimized based on others' ideas
+pub fn part2_impl(input: &str, width: usize, height: usize, initial_safe_byte_count: usize) -> (i64, i64) {
+ let mut input_map = MemoryMap::from_str(input, width, height);
+
+ input_map.place_bytes(0, initial_safe_byte_count - 1);
+
+ // for the unplaced bytes, binary search for the partition point, given the predicate that a path is reachable
+ // when all bytes up to that n have been placed
+ let possible_problems = (initial_safe_byte_count..input_map.byte_stream.len()).collect_vec();
+ let solution = possible_problems.partition_point(|byte| {
+ // avoiding this clone by rolling back the byte placements instead is slower
+ let mut local_map = input_map.clone();
+ local_map.place_bytes(initial_safe_byte_count, *byte);
+ local_map.bfs::((0, 0)).is_some()
+ }) + initial_safe_byte_count;
+
+ input_map.byte_stream[solution]
+}
+
+#[aoc(day18, part1)]
+pub fn part1(input: &str) -> usize {
+ part1_impl(input, 71, 71, 1024)
+}
+
+#[aoc(day18, part2)]
+pub fn part2(input: &str) -> String {
+ let sol = part2_impl(input, 71, 71, 1024);
+ format!("{},{}", sol.0, sol.1)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ const EXAMPLE: &str = "5,4
+4,2
+4,5
+3,0
+2,1
+6,3
+2,4
+1,5
+0,6
+3,3
+2,6
+5,1
+1,2
+5,5
+2,5
+6,5
+1,4
+0,4
+6,4
+1,1
+6,1
+1,0
+0,5
+1,6
+2,0";
+
+ #[test]
+ fn part1_example() {
+ assert_eq!(part1_impl(EXAMPLE, 7, 7, 12), 22);
+ }
+
+ #[test]
+ fn part2_example() {
+ assert_eq!(part2_impl(EXAMPLE, 7, 7, 12), (6, 1));
+ }
+
+ #[test]
+ fn part2_example_brute() {
+ assert_eq!(part2_impl_brute(EXAMPLE, 7, 7, 12,), (6, 1));
+ }
+}
diff --git a/2024/src/day19.rs b/2024/src/day19.rs
new file mode 100644
index 0000000..781e3a4
--- /dev/null
+++ b/2024/src/day19.rs
@@ -0,0 +1,192 @@
+use aoc_runner_derive::aoc;
+use itertools::Itertools;
+use rayon::iter::{IntoParallelIterator, ParallelIterator};
+use rustc_hash::FxHashMap;
+use std::fmt::{Display, Write};
+
+#[repr(u8)]
+#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
+enum Stripe {
+ White = b'w',
+ Blue = b'u',
+ Black = b'b',
+ Red = b'r',
+ Green = b'g',
+}
+
+impl From<&u8> for Stripe {
+ fn from(value: &u8) -> Self {
+ match value {
+ b'w' => Self::White,
+ b'u' => Self::Blue,
+ b'b' => Self::Black,
+ b'r' => Self::Red,
+ b'g' => Self::Green,
+ _ => unimplemented!(),
+ }
+ }
+}
+
+impl From<&Stripe> for char {
+ fn from(val: &Stripe) -> Self {
+ let v = *val as u8;
+ v.into()
+ }
+}
+
+impl Display for Stripe {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_char(self.into())
+ }
+}
+
+#[derive(Debug, Clone)]
+struct Design {
+ stripes: Vec,
+}
+
+impl From<&[u8]> for Design {
+ fn from(input: &[u8]) -> Self {
+ let stripes = input.iter().map(|c| c.into()).collect();
+ Self { stripes }
+ }
+}
+
+impl Display for Design {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ for stripe in &self.stripes {
+ f.write_char(stripe.into())?;
+ }
+ Ok(())
+ }
+}
+
+#[derive(Debug)]
+struct Onsen {
+ towels: Vec,
+ designs: Vec,
+}
+
+impl Display for Onsen {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.towels.iter().join(", "))?;
+ writeln!(f)?;
+ writeln!(f)?;
+ for d in &self.designs {
+ d.fmt(f)?;
+ writeln!(f)?;
+ }
+ Ok(())
+ }
+}
+
+impl Onsen {
+ fn possible(&self, d: &[Stripe]) -> bool {
+ if d.is_empty() {
+ return true;
+ }
+ for t in &self.towels {
+ if d.starts_with(&t.stripes) && self.possible(d.split_at(t.stripes.len()).1) {
+ return true;
+ }
+ }
+ false
+ }
+ // Count the ways to construct a given substring
+ fn ways<'a>(
+ &'a self,
+ d: &'a [Stripe],
+ mut cache: FxHashMap<&'a [Stripe], i64>,
+ ) -> (FxHashMap<&'a [Stripe], i64>, i64) {
+ if d.is_empty() {
+ return (cache, 1);
+ }
+ if cache.contains_key(d) {
+ let val = cache[d];
+ return (cache, val);
+ }
+
+ let mut count = 0;
+ for t in &self.towels {
+ if d.starts_with(&t.stripes) {
+ let res_count;
+ (cache, res_count) = self.ways(&d[t.stripes.len()..d.len()], cache);
+ count += res_count;
+ }
+ }
+ cache.insert(d, count);
+ (cache, count)
+ }
+ fn count_possible(&self) -> i64 {
+ self.designs
+ .clone()
+ .into_par_iter()
+ .map(|d| self.possible(&d.stripes))
+ .filter(|p| *p)
+ .count() as i64
+ }
+ fn count_ways(&self) -> i64 {
+ self.designs
+ .clone()
+ .into_par_iter()
+ .map(|d| self.ways(&d.stripes, FxHashMap::default()).1)
+ .sum::()
+ }
+}
+
+fn parse(input: &str) -> Onsen {
+ let mut lines = input.lines();
+
+ let towels = lines
+ .next()
+ .unwrap()
+ .split(&[',', ' '])
+ .filter(|s| !s.is_empty())
+ .map(|s| s.as_bytes().into())
+ .collect();
+
+ lines.next().unwrap(); // discard empty line
+
+ let designs = lines.map(|l| l.as_bytes().into()).collect();
+
+ Onsen { towels, designs }
+}
+
+#[aoc(day19, part1)]
+fn part1(input: &str) -> i64 {
+ let onsen = parse(input);
+
+ onsen.count_possible()
+}
+
+#[aoc(day19, part2)]
+fn part2(input: &str) -> i64 {
+ let onsen = parse(input);
+
+ onsen.count_ways()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ const EXAMPLE: &str = "r, wr, b, g, bwu, rb, gb, br
+
+brwrr
+bggr
+gbbr
+rrbgbr
+ubwu
+bwurrg
+brgr
+bbrgwb";
+
+ #[test]
+ fn part1_example() {
+ assert_eq!(part1(EXAMPLE), 6);
+ }
+
+ #[test]
+ fn part2_example() {
+ assert_eq!(part2(EXAMPLE), 16);
+ }
+}
diff --git a/2024/src/day2.rs b/2024/src/day2.rs
new file mode 100644
index 0000000..a5a8fea
--- /dev/null
+++ b/2024/src/day2.rs
@@ -0,0 +1,105 @@
+use aoc_runner_derive::{aoc, aoc_generator};
+use std::io::{BufRead, Lines};
+
+#[aoc_generator(day2)]
+pub fn get_input(input: &[u8]) -> Reports {
+ Reports::from(input.lines())
+}
+
+#[derive(Debug)]
+pub struct Reports {
+ reports: Vec>,
+}
+
+impl From> for Reports {
+ fn from(lines: Lines) -> Self {
+ let mut reports = Vec::new();
+ for line in lines.map(|i| i.unwrap()) {
+ reports.push(
+ line.split_ascii_whitespace()
+ .map(|record| record.parse::().unwrap())
+ .collect(),
+ )
+ }
+ Reports { reports }
+ }
+}
+
+impl Reports {
+ fn is_safe(report: &[u64]) -> bool {
+ let mut ascending: bool = true;
+ let mut descending: bool = true;
+ for (a, b) in report.iter().zip(report.iter().skip(1)) {
+ if a > b {
+ ascending = false
+ }
+ if a < b {
+ descending = false;
+ }
+ let ad = a.abs_diff(*b);
+ if !(1..=3).contains(&ad) || (!ascending && !descending) {
+ return false;
+ };
+ }
+ true
+ }
+ fn count_safe(&self) -> u64 {
+ self.reports.iter().filter(|report| Self::is_safe(report)).count() as u64
+ }
+ fn is_dumb_dampened_safe(report: &[u64]) -> bool {
+ if Self::is_safe(report) {
+ return true;
+ }
+ for i in 0..report.len() {
+ let mut new_vec = report.to_owned();
+ new_vec.remove(i);
+ if Self::is_safe(&new_vec) {
+ return true;
+ }
+ }
+ false
+ }
+ fn dampened_count_safe(&self) -> u64 {
+ self.reports
+ .iter()
+ .filter(|report| Self::is_dumb_dampened_safe(report))
+ .count() as u64
+ }
+}
+
+// PROBLEM 1 solution
+#[aoc(day2, part1)]
+pub fn part1(input: &Reports) -> u64 {
+ input.count_safe()
+}
+
+// PROBLEM 2 solution
+#[aoc(day2, part2)]
+pub fn part2(input: &Reports) -> u64 {
+ input.dampened_count_safe()
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::day2::*;
+
+ const EXAMPLE: &[u8] = b"7 6 4 2 1
+1 2 7 8 9
+9 7 6 2 1
+1 3 2 4 5
+8 6 4 4 1
+1 3 6 7 9";
+
+ #[test]
+ fn part1_example() {
+ let input = get_input(EXAMPLE);
+ println!("{:?}", input);
+ assert_eq!(part1(&input), 2);
+ }
+
+ #[test]
+ fn part2_example() {
+ let input = get_input(EXAMPLE);
+ assert_eq!(part2(&input), 4);
+ }
+}
diff --git a/2024/src/day20.rs b/2024/src/day20.rs
new file mode 100644
index 0000000..8f69c5a
--- /dev/null
+++ b/2024/src/day20.rs
@@ -0,0 +1,186 @@
+use aoc_runner_derive::aoc;
+use grid::{AsCoord2d, Coord2d, Grid};
+use itertools::Itertools;
+use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
+use std::collections::VecDeque;
+
+struct RaceTrack {
+ map: Grid,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
+struct State {
+ pos: Coord2d,
+ cost: u64,
+}
+
+#[derive(Clone, Debug, Eq, PartialEq, Hash)]
+struct CheatState {
+ s: State,
+}
+
+const DIRECTIONS: [(i64, i64); 4] = [(-1, 0), (1, 0), (0, -1), (0, 1)];
+
+impl RaceTrack {
+ fn valid_moves<'a>(&'a self, CheatState { s: state }: &'a CheatState) -> impl Iterator
- + 'a {
+ DIRECTIONS
+ .iter()
+ .map(|dir| state.pos + dir)
+ .filter_map(move |pos| match &self.map.get(&pos) {
+ Some(b'.') | Some(b'S') | Some(b'E') => Some(CheatState {
+ s: State {
+ pos,
+ cost: state.cost + 1,
+ },
+ }),
+ _ => None,
+ })
+ }
+ fn path_costs(&self, start: Coord2d, goal: Coord2d) -> Grid