From 96ac7d1c012ef4ea6d8dde09af712f06c76be42e Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Thu, 3 Dec 2026 17:18:26 -0700 Subject: [PATCH] 2022/day8: part 1 + add utils --- .aoc_tiles/tiles/2022/08.png | Bin 0 -> 8523 bytes 2022/Cargo.lock | 207 ++++++++- 2022/Cargo.toml | 5 + 2022/src/day8.rs | 77 ++++ 2022/src/lib.rs | 1 + 2022/utils/grid/Cargo.lock | 7 + 2022/utils/grid/Cargo.toml | 9 + 2022/utils/grid/lib.rs | 797 +++++++++++++++++++++++++++++++++++ 2022/utils/misc/Cargo.lock | 44 ++ 2022/utils/misc/Cargo.toml | 8 + 2022/utils/misc/src/lib.rs | 115 +++++ 2022/utils/misc/src/range.rs | 118 ++++++ README.md | 7 +- 13 files changed, 1392 insertions(+), 3 deletions(-) create mode 100644 .aoc_tiles/tiles/2022/08.png create mode 100644 2022/src/day8.rs create mode 100644 2022/utils/grid/Cargo.lock create mode 100644 2022/utils/grid/Cargo.toml create mode 100644 2022/utils/grid/lib.rs create mode 100644 2022/utils/misc/Cargo.lock create mode 100644 2022/utils/misc/Cargo.toml create mode 100644 2022/utils/misc/src/lib.rs create mode 100644 2022/utils/misc/src/range.rs diff --git a/.aoc_tiles/tiles/2022/08.png b/.aoc_tiles/tiles/2022/08.png new file mode 100644 index 0000000000000000000000000000000000000000..167cf172510ed502cada86d233cdff796fd4dc42 GIT binary patch literal 8523 zcmW+*1y~f{7ab6g7LbxI0bwPiB?Kfzx)u=-5TvA$SQZwLE&*X_knZm8mF|{Bx}+r} z|MUC5Z{wStnf>0pckj99oExg4rbvWOgAV`zk+PDU7Wn-We1F8n1V7)dZ@&isW-?_t z86A(*eIsj+$Fq%60t@c*2^(vN!9rO=p`gx|kjYR_yW>t>yE#LXlZ|oKfI|NNGO9T8 zP!Z{9>`q7>bcAv+kUx$NNA)`C0TVRf(7#w>W2fHdYCZZ=(R1K$;=f|$V2}4|(cLy8 zR%uQ4E`vn*jic8!bk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`PAH(ZyUNd6RGpKcX2cu;m6 zX<+LR=l-XMI0A0G9N_L-;+hbNs`{_LA2EAK>#UslB$ThOv~^V6tmUJrXZ6G*`zO~k z=q-AFG;q{qVN_#W*UnBBbQ)>!ZH#|KE;OH6vmva-lPTWw`fv%!}GO k`gN@hE?l>;_Fdnju`cDBQeLfqZ8<<$UQMn{_JjZb09yJE4*&oF literal 0 HcmV?d00001 diff --git a/2022/Cargo.lock b/2022/Cargo.lock index 03982db..0dd7345 100644 --- a/2022/Cargo.lock +++ b/2022/Cargo.lock @@ -68,12 +68,15 @@ dependencies = [ "bitflags", "cached", "colored", + "grid", "indicatif", "itertools", "lazy_static", + "misc", "nom", "rayon", "regex", + "rstest", "rustc-hash", "thread_local", ] @@ -114,7 +117,7 @@ dependencies = [ "ahash", "cached_proc_macro", "cached_proc_macro_types", - "hashbrown", + "hashbrown 0.14.5", "once_cell", "thiserror", "web-time", @@ -239,12 +242,57 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-timer" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "grid" +version = "0.1.0" + [[package]] name = "hashbrown" version = "0.14.5" @@ -255,12 +303,28 @@ dependencies = [ "allocator-api2", ] +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + [[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.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", +] + [[package]] name = "indicatif" version = "0.17.11" @@ -275,6 +339,15 @@ dependencies = [ "web-time", ] +[[package]] +name = "intrusive-collections" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" +dependencies = [ + "memoffset", +] + [[package]] name = "itertools" version = "0.13.0" @@ -318,12 +391,29 @@ 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 = "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 = [ + "intrusive-collections", + "num-traits", +] + [[package]] name = "nom" version = "7.1.3" @@ -355,12 +445,27 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +[[package]] +name = "pin-project-lite" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" + [[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.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.103" @@ -428,12 +533,56 @@ 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.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddccc32d6bd1be19116efd2c550447d9bfc8f1751afa298ca10b97cf843dbcc7" +dependencies = [ + "futures-timer", + "futures-util", + "rstest_macros", +] + +[[package]] +name = "rstest_macros" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25018259fbc1cbcb0d01b5b3bc2296c1bbe2e20d0e72efe81dde11e860b7e3b4" +dependencies = [ + "cfg-if", + "glob", + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 3.0.10", + "unicode-ident", +] + [[package]] name = "rustc-hash" version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" +[[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" @@ -446,6 +595,12 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.228" @@ -516,6 +671,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -545,6 +711,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.21+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" +dependencies = [ + "winnow", +] + [[package]] name = "unicode-ident" version = "1.0.22" @@ -691,6 +887,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + [[package]] name = "zerocopy" version = "0.8.31" diff --git a/2022/Cargo.toml b/2022/Cargo.toml index 2436a85..72954f2 100644 --- a/2022/Cargo.toml +++ b/2022/Cargo.toml @@ -18,8 +18,13 @@ rayon = "1.10.0" regex = "1.11.1" rustc-hash = "2.1.0" thread_local = "1.1.8" +grid = {version = "0.1.0", path = "utils/grid"} +misc = {path = "utils/misc"} [profile.release] lto = true opt-level = 3 overflow-checks = false + +[dev-dependencies] +rstest = "0.29.1" diff --git a/2022/src/day8.rs b/2022/src/day8.rs new file mode 100644 index 0000000..081e90d --- /dev/null +++ b/2022/src/day8.rs @@ -0,0 +1,77 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use std::str::FromStr; + +use grid::{Coord2d, Grid}; + +#[aoc_generator(day8)] +fn parse(input: &str) -> Grid { + Grid::from_str(input).unwrap() +} + +#[aoc(day8, part1)] +fn part1(input: &Grid) -> u64 { + let mut visible_map = input.same_shape(false); + for y in 0..input.height() { + let mut left_max = 0u8; + let mut right_max = 0u8; + for x in 0..input.width() { + let height_left = *input.get(&(x as i64, y as i64)).unwrap(); + if height_left > left_max { + left_max = height_left; + visible_map.set(&(x as i64, y as i64), true); + } + let height_right = *input.get(&(input.width() as i64 - 1 - x as i64, y as i64)).unwrap(); + if height_right > right_max { + right_max = height_right; + visible_map.set(&(input.width() as i64 - 1 - x as i64, y as i64), true); + } + } + } + for x in 0..input.width() { + let mut top_max = 0u8; + let mut bottom_max = 0u8; + for y in 0..input.height() { + let height_top = *input.get(&(x as i64, y as i64)).unwrap(); + if height_top > top_max { + top_max = height_top; + visible_map.set(&(x as i64, y as i64), true); + } + let height_bottom = *input.get(&(x as i64, input.height() as i64 - 1 - y as i64)).unwrap(); + if height_bottom > bottom_max { + bottom_max = height_bottom; + visible_map.set(&(x as i64, input.height() as i64 - 1 - y as i64), true); + } + } + } + + visible_map.count(&true) as u64 +} + +#[aoc(day8, part2)] +fn part2(input: &Grid) -> u64 { + todo!() +} + +#[cfg(test)] +mod tests { + use super::*; + use rstest::rstest; + + const EXAMPLE: &str = "30373 +25512 +65332 +33549 +35390"; + + #[rstest] + #[case(EXAMPLE, 21)] + 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/2022/src/lib.rs b/2022/src/lib.rs index 3dc247d..1c24e34 100644 --- a/2022/src/lib.rs +++ b/2022/src/lib.rs @@ -4,6 +4,7 @@ mod day3; mod day4; mod day5; mod day7; +mod day8; use aoc_runner_derive::aoc_lib; mod day6; diff --git a/2022/utils/grid/Cargo.lock b/2022/utils/grid/Cargo.lock new file mode 100644 index 0000000..1c1a197 --- /dev/null +++ b/2022/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/2022/utils/grid/Cargo.toml b/2022/utils/grid/Cargo.toml new file mode 100644 index 0000000..a95c55e --- /dev/null +++ b/2022/utils/grid/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "grid" +version = "0.1.0" +edition = "2024" + +[dependencies] + +[lib] +path = "lib.rs" diff --git a/2022/utils/grid/lib.rs b/2022/utils/grid/lib.rs new file mode 100644 index 0000000..aa4262a --- /dev/null +++ b/2022/utils/grid/lib.rs @@ -0,0 +1,797 @@ +use std::{ + fmt::{Debug, Display, Formatter, Write}, + io::{BufRead, Cursor}, + iter::repeat_n, + mem::swap, + ops::{Add, AddAssign, Sub}, + str::FromStr, +}; + +/// NW, N, NE, W, E, SW, S, SE +pub const ADJACENT_OFFSETS: [&(i64, i64); 8] = [ + &(-1, -1), + &(0, -1), + &(1, -1), + &(-1, 0), + &(1, 0), + &(-1, 1), + &(0, 1), + &(1, 1), +]; + +/// NESW +pub const CARDINAL_OFFSETS: [&(i64, i64); 4] = [&(0, -1), &(-1, 0), &(1, 0), &(0, 1)]; + +pub enum MirrorAxis { + X, + Y, +} + +#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] +pub struct Coord2d { + pub x: i64, + pub y: i64, +} + +impl Display for Coord2d { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_fmt(format_args!("({}, {})", self.x, self.y)) + } +} + +impl FromStr for Coord2d { + type Err = Box; + fn from_str(s: &str) -> Result { + let (l, r) = s.split_once(',').ok_or("Can't split on ,")?; + Ok(Coord2d { + x: l.parse()?, + y: r.parse()?, + }) + } +} + +pub trait AsCoord2d { + fn to_coord(self) -> Coord2d; + fn x(&self) -> i64; + fn y(&self) -> i64; + + fn manhattan(&self, other: &T) -> u64 { + self.x().abs_diff(other.x()) + self.y().abs_diff(other.y()) + } +} + +// Implements `lhs rhs` for each listed lhs type, with any `AsCoord2d` on the right. +macro_rules! impl_coord_op { + ($trait:ident, $method:ident, $op:tt; $($lhs:ty),+) => {$( + impl $trait for $lhs { + type Output = Coord2d; + fn $method(self, rhs: T) -> Coord2d { + Coord2d { + x: self.x() $op rhs.x(), + y: self.y() $op rhs.y(), + } + } + } + )+}; +} + +impl_coord_op!(Add, add, +; Coord2d, &Coord2d); +impl_coord_op!(Sub, sub, -; Coord2d, &Coord2d); + +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() + } +} +impl<'a, T> DoubleEndedIterator for GridRowIter<'a, T> { + fn next_back(&mut self) -> Option { + self.iter.next_back() + } +} +impl<'a, T> ExactSizeIterator for GridRowIter<'a, T> { + fn len(&self) -> usize { + self.iter.len() + } +} + +#[derive(Debug)] +pub struct CoordIter<'a, T> { + pos: usize, + grid: &'a Grid, +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for CoordIter<'a, T> { + type Item = Coord2d; + fn next(&mut self) -> Option { + if self.pos < self.grid.data.len() { + self.pos += 1; + self.grid.coord(self.pos as i64 - 1) + } else { + None + } + } +} + +#[derive(Debug)] +pub struct ItemIter<'a, T> { + pos: usize, + grid: &'a Grid, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct Item<'a, T> { + pub pos: Coord2d, + pub value: &'a T, +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for ItemIter<'a, T> { + type Item = Item<'a, T>; + fn next(&mut self) -> Option { + if self.pos < self.grid.data.len() { + self.pos += 1; + Some(Item { + pos: self.grid.coord(self.pos as i64 - 1).unwrap(), + value: &self.grid.data[self.pos - 1], + }) + } else { + None + } + } +} + +#[derive(Debug)] +pub struct GridColIter<'a, T> { + grid: &'a Grid, + stride: usize, + cur: usize, +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> GridColIter<'a, T> { + fn new(grid: &'a Grid, x: i64) -> Self { + Self { + grid, + stride: grid.width(), + cur: x as usize, + } + } +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for GridColIter<'a, T> { + type Item = &'a T; + fn next(&mut self) -> Option { + let cur = self.cur; + self.cur += self.stride; + if cur < self.grid.data.len() { + Some(&self.grid.data[cur]) + } else { + None + } + } + fn size_hint(&self) -> (usize, Option) { + (self.grid.height() - 1, Some(self.grid.height() - 1)) + } +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> DoubleEndedIterator for GridColIter<'a, T> { + fn next_back(&mut self) -> Option { + if self.cur < self.stride { + None + } else { + self.cur -= self.stride; + Some(&self.grid.data[self.cur]) + } + } +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> ExactSizeIterator for GridColIter<'a, T> { + fn len(&self) -> usize { + self.grid.height() - 1 + } +} + +#[derive(Debug)] +pub struct OffsetsIter<'a, T> { + grid: &'a Grid, + origin: Coord2d, + cur: usize, + offsets: &'a [&'a (i64, i64)], +} + +impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for OffsetsIter<'a, T> { + type Item = Item<'a, T>; + fn next(&mut self) -> Option { + while self.cur < self.offsets.len() { + let pos = self.origin + self.offsets[self.cur]; + self.cur += 1; + if let Some(value) = self.grid.get(&pos) { + return Some(Item { pos, value }); + } + } + None + } + fn size_hint(&self) -> (usize, Option) { + (0, Some(self.offsets.len() - self.cur)) + } +} + +#[derive(Clone, Eq, PartialEq, Debug, Hash)] +pub struct Grid { + pub data: Vec, + width: i64, +} + +impl Grid { + /// Returns a new [Grid] with the same shape (width x height) as `self`, filled with `fill` + pub fn same_shape(&self, fill: NT) -> Grid { + Grid::with_shape(self.width(), self.height(), fill) + } + /// Returns a new [Grid] with the given shape (width x height), filled with `fill` + pub fn with_shape(width: usize, height: usize, fill: T) -> Self { + Self { + data: Vec::from_iter(repeat_n(fill, width * height)), + width: width as i64, + } + } + pub fn width(&self) -> usize { + self.width as usize + } + pub fn height(&self) -> usize { + self.data.len() / self.width() + } + pub fn pos(&self, c: &C) -> i64 { + c.y() * self.width + c.x() + } + pub fn coord(&self, pos: i64) -> Option { + if pos < 0 || pos >= self.data.len() as i64 { + None + } else { + Some(Coord2d { + x: pos % self.width, + y: pos / self.width, + }) + } + } + pub fn coord_iter<'a>(&'a self) -> CoordIter<'a, T> { + CoordIter { pos: 0, grid: self } + } + pub fn item_iter<'a>(&'a self) -> ItemIter<'a, T> { + ItemIter { pos: 0, grid: self } + } + pub fn is_valid(&self, c: &C) -> bool { + if c.x() < 0 || c.x() >= self.width { + return false; + } + if c.y() < 0 || c.y() as usize >= self.height() { + return false; + } + true + } + fn valid_pos(&self, c: &C) -> Option { + if c.x() < 0 || c.x() >= self.width { + return None; + } + if c.y() < 0 || c.y() as usize >= self.height() { + return None; + } + let pos = self.pos(c); + if pos < 0 || pos as usize >= self.data.len() { + return None; + } + self.pos(c).try_into().ok() + } + pub fn get(&self, c: &C) -> Option<&T> { + match self.valid_pos(c) { + Some(pos) => Some(&self.data[pos]), + None => None, + } + } + pub fn get_mut(&mut self, c: &C) -> Option<&mut T> { + match self.valid_pos(c) { + Some(pos) => Some(self.data.get_mut(pos).unwrap()), + None => None, + } + } + pub fn set(&mut self, c: &C, mut val: T) -> Option { + match self.valid_pos(c) { + Some(pos) => { + swap(&mut self.data[pos], &mut val); + Some(val) + } + None => None, + } + } + pub fn increment<'a, A, C: AsCoord2d>(&'a mut self, c: &C, i: A) -> Option<&'a T> + where + T: AddAssign, + { + match self.valid_pos(c) { + Some(pos) => { + self.data[pos] += i; + Some(&self.data[pos]) + } + None => None, + } + } + pub fn row(&self, y: i64) -> Option<&[T]> { + if y < self.height() as i64 && y >= 0 { + Some(&self.data[self.pos(&(0, y)) as usize..self.pos(&(self.width, y)) as usize]) + } else { + None + } + } + + pub fn row_iter<'a>(&'a self, y: i64) -> Option> { + if (y as usize) < self.height() { + Some(GridRowIter::new(self, y)) + } else { + None + } + } + + pub fn col(&self, x: i64) -> Option> { + self.col_iter(x).map(|iter| iter.collect()) + } + + pub fn col_iter<'a>(&'a self, x: i64) -> Option> { + if (x as usize) < self.width() { + Some(GridColIter::new(self, x)) + } else { + None + } + } + + pub fn find(&self, needle: &T) -> Option { + self.coord( + self.data + .iter() + .enumerate() + .find_map(|(pos, val)| if val == needle { Some(pos as i64) } else { None }) + .unwrap_or(-1), + ) + } + /// Get all of the coordinates having value `needle` + pub fn find_all<'a>(&'a self, needle: &'a T) -> impl DoubleEndedIterator + Clone + 'a { + self.data + .iter() + .enumerate() + .filter_map(|(pos, val)| (*val == *needle).then_some(self.coord(pos as i64).unwrap())) + } + pub fn count(&self, haystack: &T) -> usize { + self.data.iter().filter(|item| *item == haystack).count() + } + + pub fn forward_slice(&self, start: &C, len: i64) -> Option<&[T]> { + let pos = (self.valid_pos(start), self.valid_pos(&(start.x() + len - 1, start.y()))); + match pos { + (Some(pos1), Some(pos2)) => Some(&self.data[pos1..pos2 + 1]), + _ => None, + } + } + + pub fn swap(&mut self, a: A, b: B) { + if let (Some(a), Some(b)) = (self.valid_pos(&a), self.valid_pos(&b)) { + self.data.swap(a, b) + } + } + + /// Return the count of neighbours (8 directions) matching predicate p + pub fn adjacent_count(&self, c: &C, mut p: P) -> usize + where + P: FnMut(&T) -> bool, + { + self.adjacent_iter(c).filter(|i| p(i.value)).count() + } + + /// Return the count of cardinal neighbours (4 directions) matching predicate p + pub fn cardinal_count(&self, c: &C, mut p: P) -> usize + where + P: FnMut(&T) -> bool, + { + self.cardinal_iter(c).filter(|i| p(i.value)).count() + } + + /// Return an iterator over the 8 neighbours of c. The iterator skips neighbouring positions outside of the grid. + pub fn adjacent_iter<'a, C: AsCoord2d + Copy>(&'a self, c: &'a C) -> OffsetsIter<'a, T> { + OffsetsIter { + grid: self, + origin: c.to_coord(), + cur: 0, + offsets: &ADJACENT_OFFSETS, + } + } + + /// Return an iterator over the 4 cardinal neighbours of c. The iterator skips neighbouring positions outside of the grid. + pub fn cardinal_iter<'a, C: AsCoord2d + Copy>(&'a self, c: &'a C) -> OffsetsIter<'a, T> { + OffsetsIter { + grid: self, + origin: c.to_coord(), + cur: 0, + offsets: &CARDINAL_OFFSETS, + } + } + + pub fn rotated(&self, mut rot: u8) -> Self { + rot %= 4; + match rot { + 0 => self.clone(), + 1 => { + let mut n = Grid::with_shape(self.height(), self.width(), self.data[0].clone()); // fill will be overwritten anyway + for y in 0..self.height() { + for x in 0..self.width() { + n.set( + &(self.height() - y - 1, x), + self.get(&(x as u64, y as u64)).unwrap().clone(), + ); + } + } + n + } + 2 => { + let mut n = Grid::with_shape(self.height(), self.width(), self.data[0].clone()); // fill will be overwritten anyway + for y in 0..self.height() { + for x in 0..self.width() { + n.set( + &(self.width() - x - 1, self.height() - y - 1), + self.get(&(x as u64, y as u64)).unwrap().clone(), + ); + } + } + n + } + 3 => { + let mut n = Grid::with_shape(self.height(), self.width(), self.data[0].clone()); // fill will be overwritten anyway + for y in 0..self.height() { + for x in 0..self.width() { + n.set( + &(self.height() - y - 1, self.width() - x - 1), + self.get(&(x as u64, y as u64)).unwrap().clone(), + ); + } + } + n + } + _ => unreachable!("invalid rotation"), + } + } + + pub fn mirrored(&self, axis: MirrorAxis) -> Self { + match axis { + MirrorAxis::X => { + let mut n = Grid::with_shape(self.height(), self.width(), self.data[0].clone()); // fill will be overwritten anyway + for y in 0..self.height() { + for x in 0..self.width() { + n.set( + &(self.width() - x - 1, y), + self.get(&(x as u64, y as u64)).unwrap().clone(), + ); + } + } + n + } + MirrorAxis::Y => { + let mut n = Grid::with_shape(self.height(), self.width(), self.data[0].clone()); // fill will be overwritten anyway + for y in 0..self.height() { + for x in 0..self.width() { + n.set( + &(x, &self.height() - y - 1), + self.get(&(x as u64, y as u64)).unwrap().clone(), + ); + } + } + n + } + } + } + + // fn window_compare_impl(&self, needle: &[T]) -> Vec<(i64, i64)> { + // if (self.width as usize) < needle.len() { + // return Vec::new(); + // } + // let mut res = Vec::new(); + // for y in 0..self.height() as i64 { + // let mut windows_tmp = self.row(y).unwrap().windows(needle.len()); + // let windows = if REV { + // windows_tmp.rev() + // } else { + // windows_tmp + // }; + + // res.extend( + // windows + // .enumerate() + // .filter_map(|(x, w)| if w == needle { Some((x as i64, y)) } else { None }), + // ); + // } + // res + // } +} + +impl From for Grid { + fn from(input: T) -> Grid { + let mut data = Vec::new(); + let mut width = 0; + for line in input.split(b'\n').map(|i| i.unwrap()) { + if width == 0 { + width = line.len() as i64 + } else if line.len() as i64 != width { + panic!("Grids must have fixed length rows") + } + data.extend_from_slice(&line); + } + Grid { data, width } + } +} + +// Should be Grid? +impl FromStr for Grid { + type Err = Box; + fn from_str(s: &str) -> Result { + Ok(Cursor::new(s).into()) + } +} + +// impl> Display for Grid { +// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { +// for y in 0..self.height() { +// for x in 0..self.width() { +// f.write_fmt(format_args!("{}",self.get(x as i64, y as i64).unwrap() as char))?; +// } +// f.write_char('\n')?; +// } +// f.write_char('\n') +// } +// } + +impl Display for Grid { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + for y in 0..self.height() { + for x in 0..self.width() { + f.write_fmt(format_args!("{}", *self.get(&(x as i64, y as i64)).unwrap() as char))?; + } + f.write_char('\n')?; + } + f.write_char('\n') + } +} + +impl Display for Grid { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + for y in 0..self.height() { + for x in 0..self.width() { + f.write_fmt(format_args!( + "{}", + match *self.get(&(x as i64, y as i64)).unwrap() { + true => '.', + false => '#', + } + ))?; + } + f.write_char('\n')?; + } + f.write_char('\n') + } +} + +#[cfg(test)] +mod tests { + use super::*; + + static TEST_VECTOR: &[u8] = b"ABCD +EFGH +IJKL +FBCG"; + + static TEST_VECTOR_S: &str = "ABCD +EFGH +IJKL +FBCG"; + + fn unchecked_load() -> Grid { + Grid::from(TEST_VECTOR) + } + + #[test] + fn from_string() { + let grid = unchecked_load(); + assert_eq!(grid.data, "ABCDEFGHIJKLFBCG".as_bytes()); + assert_eq!( + TEST_VECTOR_S.parse::>().unwrap().data, + "ABCDEFGHIJKLFBCG".as_bytes() + ); + } + + #[test] + fn indexing() { + let grid = unchecked_load(); + assert_eq!(grid.get(&(0, 0)), Some(b'A').as_ref()); + assert_eq!(grid.get(&(3, 3)), Some(b'G').as_ref()); + assert_eq!(grid.get(&(-1, 0)), None); + assert_eq!(grid.get(&(0, -1)), None); + assert_eq!(grid.get(&(5, 0)), None); + assert_eq!(grid.get(&(0, 5)), None); + } + + #[test] + fn forward_slice() { + let grid = unchecked_load(); + assert_eq!(grid.forward_slice(&(0, 0), 2), Some(b"AB".as_slice())); + assert_eq!(grid.forward_slice(&(2, 0), 2), Some(b"CD".as_slice())); + assert_eq!(grid.forward_slice(&(2, 0), 3), None); + assert_eq!(grid.forward_slice(&(0, 2), 4), Some(b"IJKL".as_slice())); + } + + #[test] + fn row_iter() { + let grid = unchecked_load(); + assert_eq!( + grid.row_iter(2).unwrap().collect::>(), + [&b'I', &b'J', &b'K', &b'L'] + ); + assert!(grid.row_iter(-1).is_none()); + assert!(grid.row_iter(4).is_none()); + } + + #[test] + fn col_iter() { + let grid = unchecked_load(); + assert_eq!( + grid.col_iter(2).unwrap().collect::>(), + [&b'C', &b'G', &b'K', &b'C'] + ); + assert!(grid.col_iter(-1).is_none()); + assert!(grid.col_iter(4).is_none()); + } + + #[test] + fn find_all() { + let grid = unchecked_load(); + assert_eq!( + grid.find_all(&b'G').collect::>(), + [Coord2d { x: 2, y: 1 }, Coord2d { x: 3, y: 3 }] + ) + } + + #[test] + fn neighbours_iter() { + let grid = unchecked_load(); + assert_eq!( + grid.adjacent_iter(&(0, 1)).collect::>(), + [ + Item { + pos: Coord2d { x: 0, y: 0 }, + value: &b'A' + }, + Item { + pos: Coord2d { x: 1, y: 0 }, + value: &b'B' + }, + Item { + pos: Coord2d { x: 1, y: 1 }, + value: &b'F' + }, + Item { + pos: Coord2d { x: 0, y: 2 }, + value: &b'I' + }, + Item { + pos: Coord2d { x: 1, y: 2 }, + value: &b'J' + }, + ] + ) + } + + #[test] + fn cardinal_iter() { + let grid = unchecked_load(); + assert_eq!( + grid.cardinal_iter(&(0, 1)).collect::>(), + [ + Item { + pos: Coord2d { x: 0, y: 0 }, + value: &b'A' + }, + Item { + pos: Coord2d { x: 1, y: 1 }, + value: &b'F' + }, + Item { + pos: Coord2d { x: 0, y: 2 }, + value: &b'I' + } + ] + ) + } + + // #[test] + // fn window_compare() { + // let grid = unchecked_load(); + // assert_eq!(grid.window_compare(b"IJKL"), &[(0, 2)]); + // assert_eq!(grid.window_compare(b"BC"), &[(1, 0), (1, 3)]); + // assert_eq!(grid.window_compare(b"LF").len(), 0); + // } +} diff --git a/2022/utils/misc/Cargo.lock b/2022/utils/misc/Cargo.lock new file mode 100644 index 0000000..6dfd16a --- /dev/null +++ b/2022/utils/misc/Cargo.lock @@ -0,0 +1,44 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "autocfg" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" + +[[package]] +name = "intrusive-collections" +version = "0.9.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" +dependencies = [ + "memoffset", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "misc" +version = "0.1.0" +dependencies = [ + "intrusive-collections", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] diff --git a/2022/utils/misc/Cargo.toml b/2022/utils/misc/Cargo.toml new file mode 100644 index 0000000..cf51035 --- /dev/null +++ b/2022/utils/misc/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "misc" +version = "0.1.0" +edition = "2024" + +[dependencies] +intrusive-collections = "0.9.7" +num-traits = "0.2.19" diff --git a/2022/utils/misc/src/lib.rs b/2022/utils/misc/src/lib.rs new file mode 100644 index 0000000..97836e2 --- /dev/null +++ b/2022/utils/misc/src/lib.rs @@ -0,0 +1,115 @@ +use num_traits::Signed; +use std::fmt::Display; +use std::ops::{Add, AddAssign}; + +pub mod range; + +const POW10MAX: usize = u64::MAX.ilog10() as usize; +pub const POW10: [u64; POW10MAX] = pow10_lut(); + +const fn pow10_lut() -> [u64; N] { + let mut res = [0; N]; + let mut i = 0; + while i < N { + res[i] = 10u64.pow(i as u32); + i += 1; + } + res +} + +/// Wrapped signed integer with custom upper bound with wrapping of 0s to the upper bound +#[derive(Eq, Clone, Copy)] +pub struct CustomWrapped { + pub val: T, + pub bound: T, +} + +impl Add for CustomWrapped { + type Output = CustomWrapped; + fn add(self, rhs: T) -> Self::Output { + Self { + val: ((self.val + rhs % self.bound) + self.bound) % self.bound, + bound: self.bound, + } + } +} + +impl Add for &CustomWrapped { + type Output = CustomWrapped; + fn add(self, rhs: T) -> Self::Output { + CustomWrapped { + val: ((self.val + rhs % self.bound) + self.bound) % self.bound, + bound: self.bound, + } + } +} + +impl AddAssign for CustomWrapped { + fn add_assign(&mut self, rhs: T) { + self.val = ((self.val + rhs % self.bound) + self.bound) % self.bound + } +} + +impl CustomWrapped { + pub fn new(val: T, bound: T) -> Self { + Self { val, bound } + } +} + +impl PartialEq for CustomWrapped { + fn eq(&self, other: &Self) -> bool { + self.val.eq(&other.val) + } +} + +impl PartialOrd for CustomWrapped { + fn partial_cmp(&self, other: &Self) -> Option { + self.val.partial_cmp(&other.val) + } +} + +impl Ord for CustomWrapped { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.val.cmp(&other.val) + } +} + +impl PartialEq for CustomWrapped { + fn eq(&self, other: &T) -> bool { + self.val == *other + } +} + +impl PartialOrd for CustomWrapped { + fn partial_cmp(&self, other: &T) -> Option { + self.val.partial_cmp(other) + } +} + +impl Display for CustomWrapped +where + T: Display, +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.val.fmt(f) + } +} + +// impl Into for CustomWrapped { +// fn into(self) -> T { +// self.val +// } +// } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_pow10() { + #[allow(clippy::needless_range_loop)] + for i in 0..POW10MAX { + assert_eq!(POW10[i], 10u64.pow(i as u32)) + } + } +} diff --git a/2022/utils/misc/src/range.rs b/2022/utils/misc/src/range.rs new file mode 100644 index 0000000..314ebb8 --- /dev/null +++ b/2022/utils/misc/src/range.rs @@ -0,0 +1,118 @@ +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)]) + } +} diff --git a/README.md b/README.md index 54ea7e4..002cafe 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@

- Advent of Code - 144/556 ⭐ + Advent of Code - 145/558 ⭐

2026 - 6 ⭐ - Rust @@ -210,7 +210,7 @@

- 2022 - 14 ⭐ - Rust + 2022 - 15 ⭐ - Rust

@@ -233,6 +233,9 @@ + + +

2015 - 2 ⭐ - Rust