Import aoc2025 history into 2025/

git-subtree-dir: 2025
git-subtree-mainline: cceb6f232e
git-subtree-split: 0446debff4
This commit is contained in:
ktims committed 2026-12-02 13:13:49 -07:00
commit 70a284ca0f
39 files changed
+5184

No files matched your search

+7
View File
@@ -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"
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "grid"
version = "0.1.0"
edition = "2024"
[dependencies]
[lib]
path = "lib.rs"
+798
View File
@@ -0,0 +1,798 @@
use std::{
fmt::{Debug, Display, Formatter, Write},
io::{BufRead, Cursor},
iter::repeat_n,
mem::swap,
ops::{Add, AddAssign, Sub},
str::FromStr,
};
/// NW, N, NE, W, E, SW, S, SE
pub const ADJACENT_OFFSETS: [&(i64, i64); 8] = [
&(-1, -1),
&(0, -1),
&(1, -1),
&(-1, 0),
&(1, 0),
&(-1, 1),
&(0, 1),
&(1, 1),
];
/// NESW
pub const CARDINAL_OFFSETS: [&(i64, i64); 4] = [&(0, -1), &(-1, 0), &(1, 0), &(0, 1)];
pub enum MirrorAxis {
X,
Y,
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Coord2d {
pub x: i64,
pub y: i64,
}
impl Display for Coord2d {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("({}, {})", self.x, self.y))
}
}
impl FromStr for Coord2d {
type Err = Box<dyn std::error::Error>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
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<T: AsCoord2d>(&self, other: &T) -> u64 {
self.x().abs_diff(other.x()) + self.y().abs_diff(other.y())
}
}
impl<T: AsCoord2d> Sub<T> for &Coord2d {
type Output = Coord2d;
fn sub(self, rhs: T) -> Self::Output {
Coord2d {
x: self.x() - rhs.x(),
y: self.y() - rhs.y(),
}
}
}
impl<T: AsCoord2d> Add<T> for &Coord2d
where
T: Copy,
{
type Output = Coord2d;
fn add(self, rhs: T) -> Self::Output {
Coord2d {
x: self.x() + rhs.x(),
y: self.y() + rhs.y(),
}
}
}
impl<T: AsCoord2d + ?Sized> Add<&T> for Coord2d {
type Output = Coord2d;
fn add(self, rhs: &T) -> Self::Output {
Coord2d {
x: self.x() + rhs.x(),
y: self.y() + rhs.y(),
}
}
}
impl AsCoord2d for Coord2d {
fn to_coord(self) -> Coord2d {
self
}
fn x(&self) -> i64 {
self.x
}
fn y(&self) -> i64 {
self.y
}
}
impl AsCoord2d for &Coord2d {
fn to_coord(self) -> Coord2d {
self.to_owned()
}
fn x(&self) -> i64 {
self.x
}
fn y(&self) -> i64 {
self.y
}
}
impl<T> AsCoord2d for (T, T)
where
T: Copy + TryInto<i64>,
<T as TryInto<i64>>::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<T> AsCoord2d for &(T, T)
where
T: Copy + TryInto<i64>,
<T as TryInto<i64>>::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<Coord2d> 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<T>, 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::Item> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
#[derive(Debug)]
pub struct CoordIter<'a, T> {
pos: usize,
grid: &'a Grid<T>,
}
impl<'a, T: Clone + Eq + PartialEq + Debug> Iterator for CoordIter<'a, T> {
type Item = Coord2d;
fn next(&mut self) -> Option<Self::Item> {
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<T>,
}
#[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<Self::Item> {
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<T>,
stride: usize,
cur: usize,
}
impl<'a, T: Clone + Eq + PartialEq + Debug> GridColIter<'a, T> {
fn new(grid: &'a Grid<T>, 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<Self::Item> {
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<usize>) {
(self.grid.height() - 1, Some(self.grid.height() - 1))
}
}
#[derive(Debug)]
pub struct OffsetsIter<'a, T> {
grid: &'a Grid<T>,
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<Self::Item> {
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<usize>) {
(0, Some(self.offsets.len() - self.cur))
}
}
#[derive(Clone, Eq, PartialEq, Debug, Hash)]
pub struct Grid<T> {
pub data: Vec<T>,
width: i64,
}
impl<T: Clone + Eq + PartialEq + Debug> Grid<T> {
/// Returns a new [Grid] with the same shape (width x height) as `self`, filled with `fill`
pub fn same_shape<NT: Clone + Eq + PartialEq + Debug>(&self, fill: NT) -> Grid<NT> {
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<C: AsCoord2d>(&self, c: &C) -> i64 {
c.y() * self.width + c.x()
}
pub fn coord(&self, pos: i64) -> Option<Coord2d> {
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<C: AsCoord2d>(&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<C: AsCoord2d>(&self, c: &C) -> Option<usize> {
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<C: AsCoord2d>(&self, c: &C) -> Option<&T> {
match self.valid_pos(c) {
Some(pos) => Some(&self.data[pos]),
None => None,
}
}
pub fn get_mut<C: AsCoord2d>(&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<C: AsCoord2d>(&mut self, c: &C, mut val: T) -> Option<T> {
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<A>,
{
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<GridRowIter<'a, T>> {
if (y as usize) < self.height() {
Some(GridRowIter::new(self, y))
} else {
None
}
}
pub fn col(&self, x: i64) -> Option<Vec<&T>> {
self.col_iter(x).map(|iter| iter.collect())
}
pub fn col_iter<'a>(&'a self, x: i64) -> Option<GridColIter<'a, T>> {
if (x as usize) < self.width() {
Some(GridColIter::new(self, x))
} else {
None
}
}
// Find the first instance of `needle` in self in storage order (row then col)
pub fn find(&self, needle: &T) -> Option<Coord2d> {
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<Item = Coord2d> + '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<C: AsCoord2d>(&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<A: AsCoord2d, B: AsCoord2d>(&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<C: AsCoord2d + Copy, P>(&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<C: AsCoord2d + Copy, P>(&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<const REV: bool>(&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<T: BufRead> From<T> for Grid<u8> {
fn from(input: T) -> Grid<u8> {
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<char>?
impl FromStr for Grid<u8> {
type Err = Box<dyn std::error::Error>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Cursor::new(s).into())
}
}
// impl<T: Copy + Eq + PartialEq + Display + Debug + Into<char>> Display for Grid<T> {
// 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<u8> {
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<bool> {
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<u8> {
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::<Grid<u8>>().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::<Vec<_>>(),
[&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::<Vec<_>>(),
[&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::<Vec<_>>(),
[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::<Vec<_>>(),
[
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::<Vec<_>>(),
[
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);
// }
}
+44
View File
@@ -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",
]
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "misc"
version = "0.1.0"
edition = "2024"
[dependencies]
intrusive-collections = "0.9.7"
num-traits = "0.2.19"
+115
View File
@@ -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<const N: usize>() -> [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<T: Signed + Copy> {
pub val: T,
pub bound: T,
}
impl<T: Signed + Copy> Add<T> for CustomWrapped<T> {
type Output = CustomWrapped<T>;
fn add(self, rhs: T) -> Self::Output {
Self {
val: ((self.val + rhs % self.bound) + self.bound) % self.bound,
bound: self.bound,
}
}
}
impl<T: Signed + Copy> Add<T> for &CustomWrapped<T> {
type Output = CustomWrapped<T>;
fn add(self, rhs: T) -> Self::Output {
CustomWrapped {
val: ((self.val + rhs % self.bound) + self.bound) % self.bound,
bound: self.bound,
}
}
}
impl<T: Signed + Copy> AddAssign<T> for CustomWrapped<T> {
fn add_assign(&mut self, rhs: T) {
self.val = ((self.val + rhs % self.bound) + self.bound) % self.bound
}
}
impl<T: Signed + Copy> CustomWrapped<T> {
pub fn new(val: T, bound: T) -> Self {
Self { val, bound }
}
}
impl<T: Signed + Copy + PartialEq> PartialEq for CustomWrapped<T> {
fn eq(&self, other: &Self) -> bool {
self.val.eq(&other.val)
}
}
impl<T: Signed + PartialOrd + Copy> PartialOrd for CustomWrapped<T> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.val.partial_cmp(&other.val)
}
}
impl<T: Signed + Ord + Copy> Ord for CustomWrapped<T> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.val.cmp(&other.val)
}
}
impl<T: Signed + PartialEq + Copy> PartialEq<T> for CustomWrapped<T> {
fn eq(&self, other: &T) -> bool {
self.val == *other
}
}
impl<T: Signed + PartialOrd + Copy> PartialOrd<T> for CustomWrapped<T> {
fn partial_cmp(&self, other: &T) -> Option<std::cmp::Ordering> {
self.val.partial_cmp(other)
}
}
impl<T: Display + Signed + Copy> Display for CustomWrapped<T>
where
T: Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.val.fmt(f)
}
}
// impl<T> Into<T> for CustomWrapped<T> {
// 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))
}
}
}
+124
View File
@@ -0,0 +1,124 @@
use intrusive_collections::Bound as IBound;
use intrusive_collections::{KeyAdapter, intrusive_adapter};
use intrusive_collections::{RBTreeLink, rbtree::RBTree};
use std::cmp::{max, min};
use std::ops::{Add, Bound, RangeBounds, Sub};
#[derive(Debug)]
pub struct NaiveRange<T> {
link: RBTreeLink,
pub start: T,
pub end: T,
}
intrusive_adapter!(
pub NaiveRangeAdapter<T> = Box<NaiveRange<T>>: NaiveRange<T> { link: RBTreeLink }
);
impl<'a, T: Ord + Clone> KeyAdapter<'a> for NaiveRangeAdapter<T> {
type Key = T;
fn get_key(&self, node: &'a NaiveRange<T>) -> T {
node.start.clone()
}
}
impl<T: Ord> NaiveRange<T> {
fn new(start: T, end: T) -> Self {
Self {
link: RBTreeLink::new(),
start,
end,
}
}
}
pub struct RangeSet<T: Ord> {
pub store: RBTree<NaiveRangeAdapter<T>>,
}
fn normalize_range<R: RangeBounds<T>, T: Copy + Ord + Add<Output = T> + From<u8>>(
r: &R,
) -> NaiveRange<T> {
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<T: Copy + Ord + Add<Output = T> + Sub<Output = T> + From<u8>> Default for RangeSet<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Copy + Ord + Add<Output = T> + Sub<Output = T> + From<u8>> RangeSet<T> {
pub fn new() -> Self {
Self {
store: RBTree::new(NaiveRangeAdapter::<T>::new()),
}
}
pub fn add<R: RangeBounds<T>>(&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::<Vec<_>>();
assert_eq!(end, [(-10, 10), (50, 2001)])
}
}