make position generic over number types

This commit is contained in:
kageru 2023-12-03 16:25:25 +01:00
parent 072c178cb8
commit db09b873ed
Signed by: kageru
GPG Key ID: 8282A2BEA4ADA3D2
5 changed files with 77 additions and 265 deletions

@ -5,11 +5,12 @@ use std::ops::RangeInclusive;
use aoc2023::{
boilerplate,
common::*,
grid::{Position2D, PositionND},
position::{Position2D, PositionND},
};
use itertools::Itertools;
const DAY: usize = 3;
type I = i32;
type Grid<'a> = Vec<&'a [u8]>;
type Parsed<'a> = (Grid<'a>, Vec<Vec<(usize, RangeInclusive<usize>)>>);
@ -47,8 +48,8 @@ fn part1((grid, number_positions): &Parsed) -> usize {
.flatten()
.cloned()
.filter_map(|(x, ys)| {
let start = Position2D::from([x, *ys.start()]);
let end = Position2D::from([x, *ys.end()]);
let start = PositionND([x as I, *ys.start() as I]);
let end = PositionND([x as I, *ys.end() as I]);
start
.neighbors()
.into_iter()
@ -61,17 +62,17 @@ fn part1((grid, number_positions): &Parsed) -> usize {
.sum()
}
fn part_of(PositionND([x1, y]): Position2D, (x2, ys): &(usize, RangeInclusive<usize>)) -> bool {
x1 == *x2 as i64 && ys.contains(&(y as usize))
fn part_of(PositionND([_, y]): Position2D<I>, (_, ys): &(usize, RangeInclusive<usize>)) -> bool {
ys.contains(&(y as usize))
}
fn part2((grid, number_positions): &Parsed) -> usize {
grid.iter()
.enumerate()
.flat_map(|(x, ys)| ys.iter().enumerate().filter_map(move |(y, &b)| (b == b'*').then_some(Position2D::from([x, y]))))
.flat_map(|(x, ys)| ys.iter().enumerate().filter_map(move |(y, &b)| (b == b'*').then_some(PositionND([x as I, y as I]))))
.filter_map(|p| {
let neighbors = p.neighbors();
number_positions[((p.0[0] - 1) as usize)..=((p.0[0] + 1) as usize)]
number_positions[(p.0[0].dec() as usize)..=(p.0[0].inc() as usize)]
.iter()
.flatten()
.filter_map(|np| neighbors.iter().find_map(|&n| part_of(n, np).then(|| parse_at(grid, np.clone()))))

@ -1,3 +1,5 @@
use std::iter::Step;
pub fn read_file(day: usize) -> String {
std::fs::read_to_string(std::env::var("AOC_INPUT").unwrap_or_else(|_| format!("inputs/day{day:0>2}"))).unwrap()
}
@ -25,6 +27,21 @@ impl Splitting for &str {
}
}
pub trait Inc: Default + Copy + Step {
fn inc(self) -> Self;
fn dec(self) -> Self;
}
impl<T: Step + Default + Copy> Inc for T {
fn inc(self) -> Self {
T::forward(self, 1)
}
fn dec(self) -> Self {
T::backward(self, 1)
}
}
#[cfg(debug_assertions)]
pub fn parse_num<T: std::str::FromStr + std::fmt::Display>(s: &str) -> T {
s.parse().unwrap_or_else(|_| panic!("Invalid number {s}"))

@ -1,159 +0,0 @@
pub mod direction;
pub mod position;
pub use direction::*;
use fnv::FnvHashMap as HashMap;
use itertools::{join, Itertools, MinMaxResult};
pub use position::*;
use std::{
fmt::Display,
ops::{Index, IndexMut},
};
#[allow(clippy::len_without_is_empty)] // I mainly have this for assertions in benchmarks
pub trait Grid<T, const D: usize>: Index<PositionND<D>, Output = T> + IndexMut<PositionND<D>> {
fn get(&self, pos: &PositionND<D>) -> Option<&T>;
fn insert<Pos: Into<PositionND<D>>>(&mut self, pos: Pos, element: T);
fn len(&self) -> usize;
}
#[derive(Debug, Clone, PartialEq)]
pub struct HashGrid<T: Default, const D: usize> {
pub fields: HashMap<PositionND<D>, T>,
}
impl<T: Default, const D: usize> Index<PositionND<D>> for HashGrid<T, D> {
type Output = T;
fn index(&self, index: PositionND<D>) -> &Self::Output {
&self.fields[&index]
}
}
impl<T: Default, const D: usize> IndexMut<PositionND<D>> for HashGrid<T, D> {
fn index_mut(&mut self, index: PositionND<D>) -> &mut Self::Output {
self.fields.get_mut(&index).expect("Key not in map")
}
}
impl<T: Default, const D: usize> Grid<T, D> for HashGrid<T, D> {
fn get(&self, pos: &PositionND<D>) -> Option<&T> {
self.fields.get(pos)
}
fn insert<Pos: Into<PositionND<D>>>(&mut self, pos: Pos, t: T) {
self.fields.insert(pos.into(), t);
}
fn len(&self) -> usize {
self.fields.len()
}
}
impl<T: Default + Copy> HashGrid<T, 2> {
pub fn from_bytes_2d<F: FnMut(u8) -> T + Copy>(raw: &str, mut f: F) -> HashGrid<T, 2> {
raw.lines()
.enumerate()
.flat_map(move |(y, l)| l.bytes().enumerate().map(move |(x, c)| (PositionND([x as i64, y as i64]), f(c))))
.collect()
}
}
impl<T: Default, const D: usize> std::iter::FromIterator<(PositionND<D>, T)> for HashGrid<T, D> {
fn from_iter<I: IntoIterator<Item = (PositionND<D>, T)>>(iter: I) -> Self {
HashGrid { fields: iter.into_iter().collect() }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct VecGrid<T> {
pub fields: Vec<Vec<T>>,
}
impl<T> Grid<T, 2> for VecGrid<T> {
fn get(&self, pos: &PositionND<2>) -> Option<&T> {
self.fields.get(pos.0[0] as usize)?.get(pos.0[1] as usize)
}
fn insert<Pos: Into<PositionND<2>>>(&mut self, pos: Pos, element: T) {
let PositionND([x, y]) = pos.into();
self.fields[x as usize][y as usize] = element;
}
fn len(&self) -> usize {
self.fields.len()
}
}
impl<T> Index<Position2D> for VecGrid<T> {
type Output = T;
fn index(&self, index: Position2D) -> &Self::Output {
&self.fields[index.0[0] as usize][index.0[1] as usize]
}
}
impl<T> IndexMut<Position2D> for VecGrid<T> {
fn index_mut(&mut self, index: Position2D) -> &mut Self::Output {
&mut self.fields[index.0[0] as usize][index.0[1] as usize]
}
}
impl<T: Copy> VecGrid<T> {
pub fn from_bytes_2d<F: FnMut(u8) -> T + Copy>(raw: &str, f: F) -> VecGrid<T> {
VecGrid { fields: raw.lines().map(|l| l.bytes().map(f).collect()).collect() }
}
}
pub struct Boundaries {
pub x_min: i64,
pub x_max: i64,
pub y_min: i64,
pub y_max: i64,
}
pub fn get_boundaries(input: &[&PositionND<2>]) -> Boundaries {
let (x_min, x_max) = match input.iter().map(|p| p.0[0]).minmax() {
MinMaxResult::NoElements => (0, 0),
MinMaxResult::MinMax(min, max) => (min, max),
MinMaxResult::OneElement(x) => (x, x),
};
let (y_min, y_max) = match input.iter().map(|p| p.0[1]).minmax() {
MinMaxResult::NoElements => (0, 0),
MinMaxResult::MinMax(min, max) => (min, max),
MinMaxResult::OneElement(x) => (x, x),
};
Boundaries { x_min, x_max, y_min, y_max }
}
pub fn draw_ascii<T: Display + Default>(coordinates: &HashMap<PositionND<2>, T>) -> String {
let b = get_boundaries(&coordinates.keys().collect::<Vec<_>>());
join(
(b.x_min..=b.x_max).map(|x| {
(b.y_min..=b.y_max).map(|y| coordinates.get(&PositionND([x, y])).unwrap_or(&T::default()).to_string()).collect::<String>()
}),
"\n",
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(PositionND([0, 2]) + PositionND([-1, 0]), [-1, 2].into());
assert_eq!(PositionND([0, -1]) + PositionND::from(Direction::Up), [0, 0].into());
}
#[test]
fn test_sub() {
assert_eq!(PositionND([0, 2]) - PositionND([-1, 0]), [1, 2].into());
assert_eq!(PositionND([0, -1]) - PositionND([0, -1]), [0, 0].into());
}
#[test]
fn test_mul() {
assert_eq!(PositionND([0, 2]) * 5, [0, 10].into());
assert_eq!(PositionND([0, -1]) * -2, [0, 2].into());
}
}

@ -1,5 +1,5 @@
#![allow(incomplete_features)]
#![feature(test, generic_const_exprs)]
#![feature(test, generic_const_exprs, step_trait)]
pub mod common;
pub mod grid;
pub mod position;
pub mod teststuff;

@ -1,39 +1,29 @@
extern crate test;
use super::direction::*;
use std::{
convert::TryInto,
fmt::Debug,
hash::Hash,
ops::{Add, Mul, Sub},
iter::Step,
ops::{Add, AddAssign},
};
use crate::common::Inc;
#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
pub struct PositionND<const DIMS: usize>(pub [i64; DIMS]);
pub struct PositionND<I, const DIMS: usize>(pub [I; DIMS]);
pub type Position2D = PositionND<2>;
impl<I, const D: usize> From<[I; D]> for PositionND<D>
where I: TryInto<i64> + Copy
{
fn from(s: [I; D]) -> Self {
let mut points = [0; D];
for i in 0..D {
points[i] = s[i].try_into().unwrap_or_else(|_| panic!("number did not fit in target type"))
}
Self(points)
}
}
pub type Position2D<I> = PositionND<I, 2>;
pub const fn num_neighbors(d: usize) -> usize {
3usize.pow(d as u32) - 1
}
impl<const DIMS: usize> PositionND<DIMS> {
pub const fn zero() -> Self {
PositionND([0; DIMS])
impl<I: Inc + Add<I, Output = I> + AddAssign + Debug, const DIMS: usize> PositionND<I, DIMS> {
pub fn zero() -> Self {
PositionND([I::default(); DIMS])
}
pub fn from_padded(slice: &[i64]) -> PositionND<DIMS> {
let mut points = [0; DIMS];
pub fn from_padded(slice: &[I]) -> PositionND<I, DIMS> {
let mut points = [I::default(); DIMS];
#[allow(clippy::manual_memcpy)]
for i in 0..(DIMS.min(slice.len())) {
points[i] = slice[i];
@ -41,36 +31,44 @@ impl<const DIMS: usize> PositionND<DIMS> {
PositionND(points)
}
pub fn neighbors(&self) -> [PositionND<DIMS>; num_neighbors(DIMS)]
where [PositionND<DIMS>; num_neighbors(DIMS) + 1]: Sized {
let ns = neighbor_vectors::<DIMS>();
pub fn neighbors(&self) -> [PositionND<I, DIMS>; num_neighbors(DIMS)]
where [PositionND<I, DIMS>; num_neighbors(DIMS) + 1]: Sized {
let ns = neighbor_vectors::<I, DIMS>();
let mut out = [*self; num_neighbors(DIMS)];
for (out, dir) in out.iter_mut().zip(IntoIterator::into_iter(ns).filter(|n| n != &[0; DIMS])) {
*out = *out + PositionND::from(dir);
for (out, dir) in out.iter_mut().zip(IntoIterator::into_iter(ns).filter(|n| n != &[I::default(); DIMS])) {
*out = *out + PositionND(dir);
}
out
}
}
impl PositionND<2> {
pub fn neighbors_no_diagonals_only_positive(&self) -> [PositionND<2>; 2] {
let PositionND::<2>([x, y]) = *self;
[[x + 1, y].into(), [x, y + 1].into()]
}
impl<I, const D: usize> Add<PositionND<I, D>> for PositionND<I, D>
where I: AddAssign<I> + Copy
{
type Output = PositionND<I, D>;
pub fn neighbors_no_diagonals(&self) -> [PositionND<2>; 4] {
let PositionND::<2>([x, y]) = *self;
[[x + 1, y].into(), [x, y + 1].into(), [x - 1, y].into(), [x, y - 1].into()]
fn add(mut self, rhs: PositionND<I, D>) -> Self::Output {
for (x, y) in self.0.iter_mut().zip(rhs.0) {
*x += y;
}
self
}
}
impl<I: Copy + Default + Step> PositionND<I, 2> {
pub fn neighbors_no_diagonals(&self) -> [PositionND<I, 2>; 4] {
let PositionND([x, y]) = *self;
[PositionND([x.inc(), y]), PositionND([x, y.inc()]), PositionND([x.dec(), y]), PositionND([x, y.dec()])]
}
}
#[macro_export]
macro_rules! dim {
($d: expr) => {{
let mut out = [[0; D]; num_neighbors(D) + 1];
($d: expr, $i:ty) => {{
let zero: $i = Default::default();
let mut out = [[zero; D]; num_neighbors(D) + 1];
let mut i = 0;
for offset in -1..=1 {
for inner in neighbor_vectors::<$d>() {
for offset in zero.dec()..=zero.inc() {
for inner in neighbor_vectors::<$i, $d>() {
out[i][0] = offset;
let mut j = 1;
for e in inner {
@ -84,75 +82,30 @@ macro_rules! dim {
}};
}
fn neighbor_vectors<const D: usize>() -> [[i64; D]; num_neighbors(D) + 1]
where
{
fn neighbor_vectors<I: Inc, const D: usize>() -> [[I; D]; num_neighbors(D) + 1] {
// I would love to just call neighbor_vectors::<D-1>(), but it seems to be impossible to get the
// correct constraints for that.
match D {
0 => unreachable!(),
1 => {
let mut out = [[0; D]; num_neighbors(D) + 1];
out[0] = [-1; D];
out[1] = [0; D];
out[2] = [1; D];
let zero = I::default();
let mut out = [[zero; D]; num_neighbors(D) + 1];
out[0] = [zero.dec(); D];
out[1] = [zero; D];
out[2] = [zero.inc(); D];
out
}
2 => dim!(1),
3 => dim!(2),
4 => dim!(3),
5 => dim!(4),
6 => dim!(5),
7 => dim!(6),
2 => dim!(1, I),
3 => dim!(2, I),
4 => dim!(3, I),
5 => dim!(4, I),
6 => dim!(5, I),
7 => dim!(6, I),
// Adding more causes a stackoverflow. How curious.
_ => unimplemented!(),
}
}
impl<const D: usize> Mul<i64> for PositionND<D> {
type Output = PositionND<D>;
fn mul(mut self, rhs: i64) -> Self::Output {
for p in self.0.iter_mut() {
*p *= rhs;
}
self
}
}
impl<const D: usize> Add<PositionND<D>> for PositionND<D> {
type Output = PositionND<D>;
fn add(mut self, rhs: PositionND<D>) -> Self::Output {
for (x, y) in self.0.iter_mut().zip(rhs.0) {
*x += y;
}
self
}
}
impl<const D: usize> Sub<PositionND<D>> for PositionND<D> {
type Output = PositionND<D>;
fn sub(mut self, rhs: PositionND<D>) -> Self::Output {
for (x, y) in self.0.iter_mut().zip(rhs.0) {
*x -= y;
}
self
}
}
impl From<Direction> for PositionND<2> {
fn from(d: Direction) -> Self {
match d {
Direction::Up => PositionND::from([0, 1]),
Direction::Right => PositionND::from([1, 0]),
Direction::Left => PositionND::from([-1, 0]),
Direction::Down => PositionND::from([0, -1]),
}
}
}
#[cfg(test)]
mod tests {
use super::*;