that *should* be day 9, and the example passes,

but the real input is off!!!
This commit is contained in:
Gabe Venberg 2023-11-20 14:40:03 -06:00
parent 8fcc676be0
commit dfc41a1167
12 changed files with 2422 additions and 49 deletions

7
Cargo.lock generated
View file

@ -11,6 +11,10 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "aoc_libs"
version = "0.1.0"
[[package]] [[package]]
name = "day01" name = "day01"
version = "0.1.0" version = "0.1.0"
@ -59,6 +63,9 @@ version = "0.1.0"
[[package]] [[package]]
name = "day09" name = "day09"
version = "0.1.0" version = "0.1.0"
dependencies = [
"aoc_libs",
]
[[package]] [[package]]
name = "memchr" name = "memchr"

View file

@ -1,9 +1,10 @@
[workspace] [workspace]
members = [ members = [
"template", "template",
"aoc_libs",
"days/*", "days/*",
] ]
default-members = [ "days/*" ] default-members = [ "days/*", "aoc_libs" ]
resolver = "2" resolver = "2"
[workspace.package] [workspace.package]
@ -13,6 +14,7 @@ edition = "2021"
description = "advent of code 2022 in rust" description = "advent of code 2022 in rust"
[workspace.dependencies] [workspace.dependencies]
aoc_libs = {path = "./aoc_libs"}
regex = "1" regex = "1"
once_cell = "1.16" once_cell = "1.16"
thiserror = "1.0" thiserror = "1.0"

6
aoc_libs/Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "aoc_libs"
version.workspace = true
authors.workspace = true
edition.workspace = true
description.workspace = true

1
aoc_libs/src/lib.rs Normal file
View file

@ -0,0 +1 @@
pub mod points;

211
aoc_libs/src/points.rs Normal file
View file

@ -0,0 +1,211 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct Point {
pub x: isize,
pub y: isize,
}
impl Point {
/// converts a point (representing a point on a 4 quadrant grid with positive xy in the
/// top-right) into a upoint (representing a point on a 1 quadrant grid with the origin in the
/// top-left corner). Returns none if the resulting point would have either number negative.
pub fn to_upoint(self, zero_coord: &UPoint) -> Option<UPoint> {
Some(UPoint {
x: zero_coord.x.checked_add_signed(self.x)?,
y: zero_coord.y.checked_add_signed(-self.y)?,
})
}
}
impl std::ops::Add for Point {
type Output = Point;
fn add(self, rhs: Self) -> Self::Output {
Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
}
}
}
impl std::ops::AddAssign for Point {
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs
}
}
impl std::ops::Sub for Point {
type Output = Point;
fn sub(self, rhs: Self) -> Self::Output {
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
}
}
}
impl std::ops::SubAssign for Point {
fn sub_assign(&mut self, rhs: Self) {
*self = *self - rhs
}
}
impl std::ops::Neg for Point {
type Output = Point;
fn neg(self) -> Self::Output {
Point {
x: -self.x,
y: -self.y,
}
}
}
/// an unsigned point in 2d space
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UPoint {
pub x: usize,
pub y: usize,
}
impl UPoint {
/// converts a upoint (representing a point on a 1 quadrant grid with the origin in the
/// top-left corner) into a point( representing a point on a 4 quadrant grid with positive xy
/// in the top-right)
pub fn to_point(self, zero_coord: &UPoint) -> Point {
Point {
x: -(zero_coord.x as isize - self.x as isize),
y: zero_coord.y as isize - self.y as isize,
}
}
}
impl std::ops::Add for UPoint {
type Output = UPoint;
fn add(self, rhs: Self) -> Self::Output {
Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
}
}
}
impl std::ops::AddAssign for UPoint {
fn add_assign(&mut self, rhs: Self) {
*self = *self + rhs
}
}
impl std::ops::Sub for UPoint {
type Output = UPoint;
fn sub(self, rhs: Self) -> Self::Output {
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
}
}
}
impl std::ops::SubAssign for UPoint {
fn sub_assign(&mut self, rhs: Self) {
*self = *self - rhs
}
}
/// A matrix that allows negative co-oordinates. Will panic if referencing out of bounds, just like
/// a normal 2d array.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FourQuadrantMatrix<const X: usize, const Y: usize, T> {
matrix: [[T; X]; Y],
max_point: Point,
min_point: Point,
zero_coord: UPoint,
}
impl<const X: usize, const Y: usize, T> FourQuadrantMatrix<{ X }, { Y }, T>
where
T: Copy,
T: Default,
{
/// generates a new FourQuadrantMatrix with a given zero point (the point in the underlying 2d
/// array considered to be (0,0))
pub fn new(zero_coord: UPoint) -> FourQuadrantMatrix<{ X }, { Y }, T> {
FourQuadrantMatrix {
matrix: [[T::default(); X]; Y],
max_point: UPoint { x: X - 1, y: 0 }.to_point(&zero_coord),
min_point: UPoint { x: 0, y: Y - 1 }.to_point(&zero_coord),
zero_coord,
}
}
pub fn zero_coord(&self) -> UPoint {
self.zero_coord
}
pub fn min_point(&self) -> Point {
self.min_point
}
pub fn max_point(&self) -> Point {
self.max_point
}
/// makes sure a point is in bounds and if not, brings it in bounds.
pub fn bound_point(&self, point: &mut Point) {
if point.x > self.max_point.x {
point.x = self.max_point.x
}
if point.y > self.max_point.y {
point.y = self.max_point.y
}
if point.x < self.min_point.x {
point.x = self.min_point.x
}
if point.y < self.min_point.y {
point.y = self.min_point.y
}
}
/// checks if the point is in bounds.
pub fn is_in_bounds(&self, point: &Point) -> bool {
point.x <= self.max_point.x
&& point.y <= self.max_point.y
&& point.x >= self.min_point.x
&& point.y >= self.min_point.y
}
/// fills the matrix with the Ts default value.
pub fn reset_matrix(&mut self) {
self.matrix = [[T::default(); X]; Y];
}
}
impl<T, const X: usize, const Y: usize> std::ops::IndexMut<Point> for FourQuadrantMatrix<{ X }, { Y }, T> {
fn index_mut(&mut self, index: Point) -> &mut Self::Output {
let upoint = index
.to_upoint(&self.zero_coord)
.expect("would result in negative unsigned coordinate!");
&mut self.matrix[upoint.y][upoint.x]
}
}
impl<T, const X: usize, const Y: usize> std::ops::Index<Point> for FourQuadrantMatrix<{ X }, { Y }, T> {
type Output = T;
fn index(&self, index: Point) -> &Self::Output {
let upoint = index
.to_upoint(&self.zero_coord)
.expect("would result in negative unsigned coordinate!");
&self.matrix[upoint.y][upoint.x]
}
}
impl<T, const X: usize, const Y: usize> From<FourQuadrantMatrix<{ X }, { Y }, T>> for [[T; X]; Y] {
fn from(value: FourQuadrantMatrix<{ X }, { Y }, T>) -> Self {
value.matrix
}
}

View file

@ -3,3 +3,7 @@ name = "day09"
authors.workspace = true authors.workspace = true
description.workspace = true description.workspace = true
version.workspace = true version.workspace = true
edition.workspace = true
[dependencies]
aoc_libs.workspace = true

File diff suppressed because it is too large Load diff

View file

@ -10,8 +10,8 @@ fn main() {
let structured_input = parse::parse(input); let structured_input = parse::parse(input);
println!("Part One"); println!("Part One");
println!("Result: {}", part1::part1()); println!("Result: {}", part1::part1(&structured_input));
println!("Part Two"); // println!("Part Two");
println!("Result: {}", part2::part2()); // println!("Result: {}", part2::part2(&structured_input));
} }

View file

@ -1,8 +1,19 @@
//TODO: use std::collections::HashSet;
#![allow(unused)]
pub fn part1() -> usize { use aoc_libs::points::Point;
unimplemented!()
use crate::parse::Direction;
use crate::rope::Rope;
pub fn part1(input: &Vec<Direction>) -> usize {
let mut visited: HashSet<Point> = HashSet::new();
let mut rope: Rope<2> = Rope::new();
visited.insert(*rope.get_tail_pos());
for direction in input {
rope.update_rope(direction);
visited.insert(*rope.get_tail_pos());
}
visited.len()
} }
#[cfg(test)] #[cfg(test)]
@ -11,6 +22,32 @@ mod tests {
#[test] #[test]
fn test_part1() { fn test_part1() {
assert_eq!(0, 0); let input = vec![
Direction::Right,
Direction::Right,
Direction::Right,
Direction::Right,
Direction::Up,
Direction::Up,
Direction::Up,
Direction::Up,
Direction::Left,
Direction::Left,
Direction::Left,
Direction::Down,
Direction::Right,
Direction::Right,
Direction::Right,
Direction::Right,
Direction::Down,
Direction::Left,
Direction::Left,
Direction::Left,
Direction::Left,
Direction::Left,
Direction::Right,
Direction::Right,
];
assert_eq!(part1(&input), 13);
} }
} }

View file

@ -1,8 +1,18 @@
//TODO: use std::collections::HashSet;
#![allow(unused)]
pub fn part2() -> usize { use aoc_libs::points::Point;
unimplemented!()
use crate::{rope::Rope, parse::Direction};
pub fn part2(input: &Vec<Direction>) -> usize {
let mut visited: HashSet<Point> = HashSet::new();
let mut rope: Rope<10> = Rope::new();
for direction in input {
visited.insert(*rope.get_tail_pos());
rope.update_rope(direction);
println!("{}", rope)
}
visited.len()
} }
#[cfg(test)] #[cfg(test)]

View file

@ -1,53 +1,48 @@
use std::fmt::Display;
use crate::parse::Direction; use crate::parse::Direction;
#[derive(Debug, Clone, Copy)] use aoc_libs::points::{Point, UPoint};
struct Point {
x: isize,
y: isize,
}
impl std::ops::Add for Point {
type Output = Point;
fn add(self, rhs: Self) -> Self::Output {
Self {
x: self.x + rhs.x,
y: self.y + rhs.y,
}
}
}
impl std::ops::Sub for Point {
type Output = Point;
fn sub(self, rhs: Self) -> Self::Output {
Self {
x: self.x - rhs.x,
y: self.y - rhs.y,
}
}
}
// L is the length of the rope in segments. // L is the length of the rope in segments.
#[derive(Debug)] #[derive(Debug)]
struct Rope<const L: usize> { pub struct Rope<const L: usize> {
segments: [Point; L], segments: [Point; L],
} }
impl<const L: usize> Rope<L> { impl<const L: usize> Rope<L> {
pub fn new()->Rope{ pub fn new() -> Rope<L> {
Rope { segments: () } Rope {
segments: [Point::default(); L],
}
} }
pub fn update_rope(&mut self, direction: Direction) { pub fn update_rope(&mut self, direction: &Direction) {
todo!() self.segments[0] += match direction {
Direction::Up => Point { x: 0, y: 1 },
Direction::Right => Point { x: 1, y: 0 },
Direction::Down => Point { x: 0, y: -1 },
Direction::Left => Point { x: -1, y: 0 },
};
println!("direction is {:?}", direction);
for segment in 1..self.segments.len() {
self.segments[segment] += Rope::<L>::update_single_segment_pair(
&self.segments[segment - 1],
&self.segments[segment],
)
}
println!("{}", self);
} }
pub fn get_tail_pos(&self) -> &Point { pub fn get_tail_pos(&self) -> &Point {
&self.segments[self.segments.len() - 1] &self.segments[self.segments.len() - 1]
} }
fn update_single_segment_pair(head: Point, tail: Point) -> Point { // the rope segment will not move if the segment ahead of it is only at most one away, and will
let delta = head - tail; // move with the following rules if it is 2 away: It moves straight towards the head if the
// head is directly up/down/left/right, and diagonally towards it if its not straight
// up/down/left/right.
fn update_single_segment_pair(head: &Point, tail: &Point) -> Point {
let delta = *head - *tail;
if delta.x.abs() > 2 || delta.y.abs() > 2 { if delta.x.abs() > 2 || delta.y.abs() > 2 {
panic!("invalid delta ({}, {})", delta.y, delta.x) panic!("invalid delta ({}, {})", delta.y, delta.x)
} }
@ -64,3 +59,102 @@ impl<const L: usize> Rope<L> {
} }
} }
} }
impl<const L: usize> Display for Rope<{ L }> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let grid_size = (self.segments.len() * 2) - 1;
let zero_point = UPoint {
x: self.segments.len() - 1,
y: self.segments.len() - 1,
};
let mut grid: Vec<Vec<char>> = Vec::with_capacity(grid_size);
for y in 0..grid_size {
grid.push(Vec::with_capacity(grid_size));
for _ in 0..grid_size {
grid[y].push('.')
}
}
for segment in self.segments.iter().skip(1) {
let delta = *segment-self.segments[0];
let upoint = delta.to_upoint(&zero_point).unwrap();
grid[upoint.y][upoint.x] = 'T'
}
writeln!(
f,
"head is at {}, {}",
self.segments[0].x, self.segments[0].y
)?;
let upoint = Point { x: 0, y: 0 }.to_upoint(&zero_point).unwrap();
grid[upoint.y][upoint.x] = 'H';
for line in grid {
let mut writeline = "".to_string();
for char in line {
writeline.push(char)
}
writeln!(f, "{}", writeline)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use super::*;
#[test]
fn test_single_segment() {
let input = [
Direction::Right,
Direction::Right,
Direction::Right,
Direction::Right,
Direction::Up,
Direction::Up,
Direction::Up,
Direction::Up,
Direction::Left,
Direction::Left,
Direction::Left,
Direction::Down,
Direction::Right,
Direction::Right,
Direction::Right,
Direction::Right,
Direction::Down,
Direction::Left,
Direction::Left,
Direction::Left,
Direction::Left,
Direction::Left,
Direction::Right,
Direction::Right,
];
let mut visited: HashSet<Point> = HashSet::new();
let mut rope: Rope<2> = Rope::new();
visited.insert(*rope.get_tail_pos());
for direction in input {
rope.update_rope(&direction);
visited.insert(*rope.get_tail_pos());
}
// let mut graph = [
// ['.', '.', '.', '.', '.', '.'],
// ['.', '.', '.', '.', '.', '.'],
// ['.', '.', '.', '.', '.', '.'],
// ['.', '.', '.', '.', '.', '.'],
// ['s', '.', '.', '.', '.', '.'],
// ];
// for point in &visited {
// graph[4 - point.y as usize][point.x as usize] = '#';
// }
// for line in graph {
// println!("{:?}", line)
// }
assert_eq!(visited.len(), 13)
}
}

View file

@ -3,3 +3,4 @@ name = "template"
authors.workspace = true authors.workspace = true
description.workspace = true description.workspace = true
version.workspace = true version.workspace = true
edition.workspace = true