add grid from previous years
This commit is contained in:
parent
8c7b1dfb78
commit
93e753d902
|
@ -5,6 +5,7 @@ edition = "2021"
|
|||
|
||||
[dependencies]
|
||||
fnv = "1.0.7"
|
||||
impl_ops = "0.1.1"
|
||||
itertools = "0.10.5"
|
||||
paste = "1.0"
|
||||
rayon = "1.6.0"
|
||||
|
|
|
@ -0,0 +1,132 @@
|
|||
pub mod cell;
|
||||
pub mod direction;
|
||||
pub mod position;
|
||||
pub use direction::*;
|
||||
use itertools::{join, Itertools, MinMaxResult};
|
||||
pub use position::*;
|
||||
use std::{collections::HashMap, fmt::Display, hash::BuildHasher};
|
||||
|
||||
#[allow(clippy::len_without_is_empty)] // I mainly have this for assertions in benchmarks
|
||||
pub trait Grid<T, const D: usize> {
|
||||
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> 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 { points: [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.points[0] as usize)?.get(pos.points[1] as usize)
|
||||
}
|
||||
|
||||
fn insert<Pos: Into<PositionND<2>>>(&mut self, pos: Pos, element: T) {
|
||||
let PositionND { points: [x, y] } = pos.into();
|
||||
self.fields[x as usize][y as usize] = element;
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.fields.len()
|
||||
}
|
||||
}
|
||||
|
||||
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.points[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.points[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, S: BuildHasher>(coordinates: &HashMap<PositionND<2>, T, S>) -> String {
|
||||
let b = get_boundaries(&coordinates.keys().collect::<Vec<_>>());
|
||||
join(
|
||||
(b.y_min..=b.y_max).rev().map(|y| {
|
||||
(b.x_min..=b.x_max)
|
||||
.map(|x| coordinates.get(&PositionND { points: [x, y] }).unwrap_or(&T::default()).to_string())
|
||||
.collect::<String>()
|
||||
}),
|
||||
"\n",
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_add() {
|
||||
assert_eq!(PositionND::from([0, 2]) + PositionND::from([-1, 0]), [-1, 2].into());
|
||||
assert_eq!(PositionND::from([0, -1]) + PositionND::from(Direction::Up), [0, 0].into());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sub() {
|
||||
assert_eq!(PositionND::from([0, 2]) - PositionND::from([-1, 0]), [1, 2].into());
|
||||
assert_eq!(PositionND::from([0, -1]) - PositionND::from([0, -1]), [0, 0].into());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mul() {
|
||||
assert_eq!(PositionND::from([0, 2]) * 5, [0, 10].into());
|
||||
assert_eq!(PositionND::from([0, -1]) * -2, [0, 2].into());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
use impl_ops::*;
|
||||
use std::{ops, ops::AddAssign};
|
||||
|
||||
pub const ALL_DIRECTIONS: [Direction; 4] = [Direction::Up, Direction::Down, Direction::Left, Direction::Right];
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Direction {
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
impl AddAssign<i8> for Direction {
|
||||
fn add_assign(&mut self, rhs: i8) {
|
||||
*self = *self + rhs;
|
||||
}
|
||||
}
|
||||
|
||||
impl_op!(+ |a: Direction, b: i8| -> Direction {
|
||||
match b {
|
||||
-1 | 3 => match a {
|
||||
Direction::Up => Direction::Left,
|
||||
Direction::Right => Direction::Up,
|
||||
Direction::Down => Direction::Right,
|
||||
Direction::Left => Direction::Down,
|
||||
},
|
||||
1 | -3 => match a {
|
||||
Direction::Up => Direction::Right,
|
||||
Direction::Right => Direction::Down,
|
||||
Direction::Down => Direction::Left,
|
||||
Direction::Left => Direction::Up,
|
||||
},
|
||||
0 | 4 | -4 => a,
|
||||
2 | -2 => match a {
|
||||
Direction::Up => Direction::Down,
|
||||
Direction::Right => Direction::Left,
|
||||
Direction::Down => Direction::Up,
|
||||
Direction::Left => Direction::Right,
|
||||
},
|
||||
n => unreachable!(format!("Illegal turn value: {}", n)),
|
||||
}
|
||||
});
|
||||
|
||||
impl Direction {
|
||||
pub fn turn(&mut self, turn_value: i64) {
|
||||
*self += turn_value as i8;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,259 @@
|
|||
extern crate test;
|
||||
use super::direction::*;
|
||||
use std::{
|
||||
convert::TryInto,
|
||||
hash::Hash,
|
||||
ops::{Add, Mul, Sub},
|
||||
};
|
||||
|
||||
#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
|
||||
pub struct PositionND<const DIMS: usize> {
|
||||
pub points: [i64; 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 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 { points: [0; DIMS] }
|
||||
}
|
||||
|
||||
pub fn from_padded(slice: &[i64]) -> PositionND<DIMS> {
|
||||
let mut points = [0; DIMS];
|
||||
#[allow(clippy::manual_memcpy)]
|
||||
for i in 0..(DIMS.min(slice.len())) {
|
||||
points[i] = slice[i];
|
||||
}
|
||||
PositionND { points }
|
||||
}
|
||||
|
||||
pub fn neighbors(&self) -> [PositionND<DIMS>; num_neighbors(DIMS)]
|
||||
where [PositionND<DIMS>; num_neighbors(DIMS) + 1]: Sized {
|
||||
let ns = neighbor_vectors::<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);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl PositionND<2> {
|
||||
pub fn neighbors_no_diagonals_only_positive(&self) -> [PositionND<2>; 2] {
|
||||
let PositionND::<2> { points: [x, y] } = *self;
|
||||
[[x + 1, y].into(), [x, y + 1].into()]
|
||||
}
|
||||
|
||||
pub fn neighbors_no_diagonals(&self) -> [PositionND<2>; 4] {
|
||||
let PositionND::<2> { points: [x, y] } = *self;
|
||||
[[x + 1, y].into(), [x, y + 1].into(), [x - 1, y].into(), [x, y - 1].into()]
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! dim {
|
||||
($d: expr) => {{
|
||||
let mut out = [[0; D]; num_neighbors(D) + 1];
|
||||
let mut i = 0;
|
||||
for offset in -1..=1 {
|
||||
for inner in neighbor_vectors::<$d>() {
|
||||
out[i][0] = offset;
|
||||
let mut j = 1;
|
||||
for e in inner {
|
||||
out[i][j] = e;
|
||||
j += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}};
|
||||
}
|
||||
|
||||
fn neighbor_vectors<const D: usize>() -> [[i64; D]; num_neighbors(D) + 1]
|
||||
where
|
||||
{
|
||||
// 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];
|
||||
out
|
||||
}
|
||||
2 => dim!(1),
|
||||
3 => dim!(2),
|
||||
4 => dim!(3),
|
||||
5 => dim!(4),
|
||||
6 => dim!(5),
|
||||
7 => dim!(6),
|
||||
// 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.points.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.points.iter_mut().zip(rhs.points) {
|
||||
*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.points.iter_mut().zip(rhs.points) {
|
||||
*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::*;
|
||||
|
||||
#[test]
|
||||
fn test_neighbors_2d() {
|
||||
let p = PositionND { points: [0, 0] };
|
||||
let n = p.neighbors();
|
||||
assert_eq!(
|
||||
n,
|
||||
[
|
||||
PositionND { points: [-1, -1] },
|
||||
PositionND { points: [-1, 0] },
|
||||
PositionND { points: [-1, 1] },
|
||||
PositionND { points: [0, -1] },
|
||||
PositionND { points: [0, 1] },
|
||||
PositionND { points: [1, -1] },
|
||||
PositionND { points: [1, 0] },
|
||||
PositionND { points: [1, 1] },
|
||||
]
|
||||
);
|
||||
|
||||
let p = PositionND { points: [1, 1] };
|
||||
let n = p.neighbors();
|
||||
assert_eq!(
|
||||
n,
|
||||
[
|
||||
PositionND { points: [0, 0] },
|
||||
PositionND { points: [0, 1] },
|
||||
PositionND { points: [0, 2] },
|
||||
PositionND { points: [1, 0] },
|
||||
PositionND { points: [1, 2] },
|
||||
PositionND { points: [2, 0] },
|
||||
PositionND { points: [2, 1] },
|
||||
PositionND { points: [2, 2] },
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_neighbors_3d() {
|
||||
let p = PositionND { points: [0, 0, 0] };
|
||||
let n = p.neighbors();
|
||||
assert_eq!(
|
||||
n,
|
||||
[
|
||||
PositionND { points: [-1, -1, -1] },
|
||||
PositionND { points: [-1, -1, 0] },
|
||||
PositionND { points: [-1, -1, 1] },
|
||||
PositionND { points: [-1, 0, -1] },
|
||||
PositionND { points: [-1, 0, 0] },
|
||||
PositionND { points: [-1, 0, 1] },
|
||||
PositionND { points: [-1, 1, -1] },
|
||||
PositionND { points: [-1, 1, 0] },
|
||||
PositionND { points: [-1, 1, 1] },
|
||||
PositionND { points: [0, -1, -1] },
|
||||
PositionND { points: [0, -1, 0] },
|
||||
PositionND { points: [0, -1, 1] },
|
||||
PositionND { points: [0, 0, -1] },
|
||||
PositionND { points: [0, 0, 1] },
|
||||
PositionND { points: [0, 1, -1] },
|
||||
PositionND { points: [0, 1, 0] },
|
||||
PositionND { points: [0, 1, 1] },
|
||||
PositionND { points: [1, -1, -1] },
|
||||
PositionND { points: [1, -1, 0] },
|
||||
PositionND { points: [1, -1, 1] },
|
||||
PositionND { points: [1, 0, -1] },
|
||||
PositionND { points: [1, 0, 0] },
|
||||
PositionND { points: [1, 0, 1] },
|
||||
PositionND { points: [1, 1, -1] },
|
||||
PositionND { points: [1, 1, 0] },
|
||||
PositionND { points: [1, 1, 1] },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_neighbor_vectors() {
|
||||
let n = neighbor_vectors::<2>();
|
||||
assert_eq!(n, [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1],]);
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_neighbor_vectors_2d(b: &mut test::Bencher) {
|
||||
b.iter(|| test::black_box(neighbor_vectors::<2>()))
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_neighbor_vectors_3d(b: &mut test::Bencher) {
|
||||
b.iter(|| test::black_box(neighbor_vectors::<3>()))
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_neighbor_vectors_4d(b: &mut test::Bencher) {
|
||||
b.iter(|| test::black_box(neighbor_vectors::<4>()))
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_neighbor_vectors_5d(b: &mut test::Bencher) {
|
||||
b.iter(|| test::black_box(neighbor_vectors::<5>()))
|
||||
}
|
||||
}
|
|
@ -10,7 +10,7 @@ macro_rules! boilerplate {
|
|||
},)?
|
||||
bench1 == $b1: literal,
|
||||
bench2 == $b2: literal,
|
||||
bench_parse: $input_fn: expr => $it: literal$(,)?
|
||||
bench_parse: $input_fn: expr => $it: expr$(,)?
|
||||
) => {
|
||||
fn main() {
|
||||
let raw_input = read_file(DAY);
|
||||
|
|
Loading…
Reference in New Issue
Block a user