From 7f8d03a5a0cbbb9e8d073e04f0671f6055ed2720 Mon Sep 17 00:00:00 2001 From: kageru Date: Thu, 30 Nov 2023 23:56:01 +0100 Subject: [PATCH] add 2023 setup and grid code --- 2023/Cargo.toml | 11 ++ 2023/rustfmt.toml | 7 + 2023/setup_day.sh | 34 +++++ 2023/src/common.rs | 25 ++++ 2023/src/grid.rs | 159 +++++++++++++++++++++++ 2023/src/grid/direction.rs | 49 +++++++ 2023/src/grid/position.rs | 257 +++++++++++++++++++++++++++++++++++++ 2023/src/lib.rs | 5 + 2023/src/teststuff.rs | 65 ++++++++++ 9 files changed, 612 insertions(+) create mode 100644 2023/Cargo.toml create mode 100644 2023/rustfmt.toml create mode 100755 2023/setup_day.sh create mode 100644 2023/src/common.rs create mode 100644 2023/src/grid.rs create mode 100644 2023/src/grid/direction.rs create mode 100644 2023/src/grid/position.rs create mode 100644 2023/src/lib.rs create mode 100644 2023/src/teststuff.rs diff --git a/2023/Cargo.toml b/2023/Cargo.toml new file mode 100644 index 0000000..fc1117b --- /dev/null +++ b/2023/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "aoc2023" +version = "0.1.0" +edition = "2021" + +[dependencies] +itertools = "0.12" +paste = "1.0" + +[profile.bench] +lto = true diff --git a/2023/rustfmt.toml b/2023/rustfmt.toml new file mode 100644 index 0000000..36e1962 --- /dev/null +++ b/2023/rustfmt.toml @@ -0,0 +1,7 @@ +newline_style = "Unix" +max_width = 140 +imports_granularity = "Crate" +struct_field_align_threshold = 25 +where_single_line = true +edition = "2021" +use_small_heuristics = "Max" diff --git a/2023/setup_day.sh b/2023/setup_day.sh new file mode 100755 index 0000000..62dcd5d --- /dev/null +++ b/2023/setup_day.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +today=$(date +%d) +aocd > inputs/day$today + +echo '#![feature(test)] +extern crate test; +use aoc2023::{boilerplate, common::*}; + +const DAY: usize = '$today'; +type Parsed = Vec; + +fn parse_input(raw: &str) -> Parsed { + parse_nums(raw) +} + +fn part1(parsed: &Parsed) -> usize { + unimplemented!() +} + +fn part2(parsed: &Parsed) -> usize { + unimplemented!() +} + +boilerplate! { + TEST_INPUT == "", + tests: { + part1: { TEST_INPUT => 0 }, + part2: { TEST_INPUT => 0 }, + }, + bench1 == 0, + bench2 == 0, + bench_parse: Vec::len => 0, +}' > src/bin/day$today.rs diff --git a/2023/src/common.rs b/2023/src/common.rs new file mode 100644 index 0000000..1206d9a --- /dev/null +++ b/2023/src/common.rs @@ -0,0 +1,25 @@ +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() +} + +pub fn parse_nums(l: &str) -> Vec { + l.lines().map(parse_num).collect() +} + +pub fn parse_nums_comma(l: &str) -> Vec { + l.trim().split(',').map(parse_num).collect() +} + +#[cfg(debug_assertions)] +pub fn parse_num(s: &str) -> T { + s.parse().unwrap_or_else(|_| panic!("Invalid number {s}")) +} + +// For benchmarks. +// This function assumes that the input will always be valid numbers and is UB otherwise +#[cfg(not(debug_assertions))] +pub fn parse_num + std::ops::Add + std::ops::Mul>(s: &str) -> T { + let mut digits = s.bytes().map(|b| T::from(b - b'0')); + let start = unsafe { digits.next().unwrap_unchecked() }; + digits.fold(start, |acc, n| acc * T::from(10) + n) +} diff --git a/2023/src/grid.rs b/2023/src/grid.rs new file mode 100644 index 0000000..39eff06 --- /dev/null +++ b/2023/src/grid.rs @@ -0,0 +1,159 @@ +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: Index, Output = T> + IndexMut> { + fn get(&self, pos: &PositionND) -> Option<&T>; + + fn insert>>(&mut self, pos: Pos, element: T); + + fn len(&self) -> usize; +} + +#[derive(Debug, Clone, PartialEq)] +pub struct HashGrid { + pub fields: HashMap, T>, +} + +impl Index> for HashGrid { + type Output = T; + fn index(&self, index: PositionND) -> &Self::Output { + &self.fields[&index] + } +} + +impl IndexMut> for HashGrid { + fn index_mut(&mut self, index: PositionND) -> &mut Self::Output { + self.fields.get_mut(&index).expect("Key not in map") + } +} + +impl Grid for HashGrid { + fn get(&self, pos: &PositionND) -> Option<&T> { + self.fields.get(pos) + } + + fn insert>>(&mut self, pos: Pos, t: T) { + self.fields.insert(pos.into(), t); + } + + fn len(&self) -> usize { + self.fields.len() + } +} + +impl HashGrid { + pub fn from_bytes_2d T + Copy>(raw: &str, mut f: F) -> HashGrid { + 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 std::iter::FromIterator<(PositionND, T)> for HashGrid { + fn from_iter, T)>>(iter: I) -> Self { + HashGrid { fields: iter.into_iter().collect() } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct VecGrid { + pub fields: Vec>, +} + +impl Grid for VecGrid { + fn get(&self, pos: &PositionND<2>) -> Option<&T> { + self.fields.get(pos.0[0] as usize)?.get(pos.0[1] as usize) + } + + fn insert>>(&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 Index for VecGrid { + type Output = T; + fn index(&self, index: Position2D) -> &Self::Output { + &self.fields[index.0[0] as usize][index.0[1] as usize] + } +} + +impl IndexMut for VecGrid { + fn index_mut(&mut self, index: Position2D) -> &mut Self::Output { + &mut self.fields[index.0[0] as usize][index.0[1] as usize] + } +} + +impl VecGrid { + pub fn from_bytes_2d T + Copy>(raw: &str, f: F) -> VecGrid { + 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(coordinates: &HashMap, T>) -> String { + let b = get_boundaries(&coordinates.keys().collect::>()); + 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::() + }), + "\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()); + } +} diff --git a/2023/src/grid/direction.rs b/2023/src/grid/direction.rs new file mode 100644 index 0000000..9c4360b --- /dev/null +++ b/2023/src/grid/direction.rs @@ -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 { + Right = 0, + Down = 1, + Left = 2, + Up = 3, +} + +impl AddAssign 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!("Illegal turn value: {n}"), + } +}); + +impl Direction { + pub fn turn(&mut self, turn_value: i64) { + *self += turn_value as i8; + } +} diff --git a/2023/src/grid/position.rs b/2023/src/grid/position.rs new file mode 100644 index 0000000..a740298 --- /dev/null +++ b/2023/src/grid/position.rs @@ -0,0 +1,257 @@ +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(pub [i64; DIMS]); + +pub type Position2D = PositionND<2>; + +impl From<[I; D]> for PositionND +where I: TryInto + 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 PositionND { + pub const fn zero() -> Self { + PositionND([0; DIMS]) + } + + pub fn from_padded(slice: &[i64]) -> PositionND { + 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; num_neighbors(DIMS)] + where [PositionND; num_neighbors(DIMS) + 1]: Sized { + let ns = neighbor_vectors::(); + 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>([x, y]) = *self; + [[x + 1, y].into(), [x, y + 1].into()] + } + + 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()] + } +} + +#[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() -> [[i64; D]; num_neighbors(D) + 1] +where +{ + // I would love to just call neighbor_vectors::(), 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 Mul for PositionND { + type Output = PositionND; + + fn mul(mut self, rhs: i64) -> Self::Output { + for p in self.0.iter_mut() { + *p *= rhs; + } + self + } +} + +impl Add> for PositionND { + type Output = PositionND; + + fn add(mut self, rhs: PositionND) -> Self::Output { + for (x, y) in self.0.iter_mut().zip(rhs.0) { + *x += y; + } + self + } +} + +impl Sub> for PositionND { + type Output = PositionND; + + fn sub(mut self, rhs: PositionND) -> Self::Output { + for (x, y) in self.0.iter_mut().zip(rhs.0) { + *x -= y; + } + self + } +} + +impl From 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([0, 0]); + let n = p.neighbors(); + assert_eq!( + n, + [ + PositionND([-1, -1]), + PositionND([-1, 0]), + PositionND([-1, 1]), + PositionND([0, -1]), + PositionND([0, 1]), + PositionND([1, -1]), + PositionND([1, 0]), + PositionND([1, 1]), + ] + ); + + let p = PositionND([1, 1]); + let n = p.neighbors(); + assert_eq!( + n, + [ + PositionND([0, 0]), + PositionND([0, 1]), + PositionND([0, 2]), + PositionND([1, 0]), + PositionND([1, 2]), + PositionND([2, 0]), + PositionND([2, 1]), + PositionND([2, 2]), + ] + ) + } + + #[test] + fn test_neighbors_3d() { + let p = PositionND([0, 0, 0]); + let n = p.neighbors(); + assert_eq!( + n, + [ + PositionND([-1, -1, -1]), + PositionND([-1, -1, 0]), + PositionND([-1, -1, 1]), + PositionND([-1, 0, -1]), + PositionND([-1, 0, 0]), + PositionND([-1, 0, 1]), + PositionND([-1, 1, -1]), + PositionND([-1, 1, 0]), + PositionND([-1, 1, 1]), + PositionND([0, -1, -1]), + PositionND([0, -1, 0]), + PositionND([0, -1, 1]), + PositionND([0, 0, -1]), + PositionND([0, 0, 1]), + PositionND([0, 1, -1]), + PositionND([0, 1, 0]), + PositionND([0, 1, 1]), + PositionND([1, -1, -1]), + PositionND([1, -1, 0]), + PositionND([1, -1, 1]), + PositionND([1, 0, -1]), + PositionND([1, 0, 0]), + PositionND([1, 0, 1]), + PositionND([1, 1, -1]), + PositionND([1, 1, 0]), + PositionND([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>())) + } +} diff --git a/2023/src/lib.rs b/2023/src/lib.rs new file mode 100644 index 0000000..63928ce --- /dev/null +++ b/2023/src/lib.rs @@ -0,0 +1,5 @@ +#![allow(incomplete_features)] +#![feature(test, generic_const_exprs)] +pub mod common; +pub mod grid; +pub mod teststuff; diff --git a/2023/src/teststuff.rs b/2023/src/teststuff.rs new file mode 100644 index 0000000..2040fa9 --- /dev/null +++ b/2023/src/teststuff.rs @@ -0,0 +1,65 @@ +#[macro_export] +macro_rules! boilerplate { + ( + TEST_INPUT == $ti: literal, + tests: { + $($part: ident: { $($tpi: expr $(,$ati: expr)* => $to: expr),+$(,)? }),*$(,)? + }, + $(unittests: { + $($unittest: ident: { $($($utpi: expr),+ => $uto: expr),+$(,)? }),*$(,)? + },)? + bench1$(($bi1: literal))? == $b1: literal, + bench2$(($bi2: literal))? == $b2: literal, + bench_parse: $input_fn: expr => $it: expr$(,)? + ) => { + fn main() { + let raw_input = read_file(DAY); + let input = parse_input(&raw_input); + println!("Part 1: {}", part1(&input$(,$bi1)?)); + println!("Part 2: {}", part2(&input$(,$bi2)?)); + } + + #[cfg(test)] + mod tests { + use super::*; + use aoc2023::*; + + const TEST_INPUT: &str = $ti; + + $($($(paste::paste! { + #[test] + fn [<$unittest _test_ $uto:lower>]() { + assert_eq!($unittest($($utpi),+), $uto); + } + })+)*)? + $($(paste::paste! { + #[test] + fn [<$part _test_ $to:lower>]() { + let input = parse_input($tpi); + assert_eq!($part(&input, $($ati),*), $to); + } + })+)* + bench!(part1($($bi1)?) == $b1); + bench!(part2($($bi2)?) == $b2); + #[bench] + fn bench_input_parsing(b: &mut test::Bencher) { + let raw = &read_file(DAY); + b.iter(|| assert_eq!($input_fn(&parse_input(test::black_box(&raw))), $it)); + } + } + } +} + +#[macro_export] +macro_rules! bench { + ($part: ident($($bi: literal)?) == $expected:expr) => { + paste::paste! { + #[bench] + fn [<$part _bench>](b: &mut test::Bencher) { + let raw = &read_file(DAY); + let input = parse_input(&raw); + b.iter(|| assert_eq!($part(test::black_box(&input)$(, $bi)?), $expected)); + } + } + }; +}