Skip to content

Commit

Permalink
chore: update point helper
Browse files Browse the repository at this point in the history
  • Loading branch information
believer committed Dec 11, 2023
1 parent 67f0ce9 commit 17ce039
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
4 changes: 2 additions & 2 deletions rust/2023/src/day_03.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ pub fn solve_part_01(input: &Input) -> u32 {

for (number, points) in numbers {
'points: for point in points {
for check_point in DIAGONALS.iter().map(|diagonal| *point + *diagonal) {
for check_point in ALL_DIRECTIONS.iter().map(|diagonal| *point + *diagonal) {
// If the point is in the list of symbols, it's a "part number"
if symbols.contains(&check_point) {
part_numbers += number;
Expand Down Expand Up @@ -138,7 +138,7 @@ pub fn solve_part_02(input: &Input) -> u32 {
let mut last_found_points = vec![];
let mut adjacents = vec![];

for check_point in DIAGONALS.iter().map(|diagonal| *point + *diagonal) {
for check_point in ALL_DIRECTIONS.iter().map(|diagonal| *point + *diagonal) {
for (number, points) in numbers {
// If the point is in the list of points we've already found, skip it
if last_found_points.contains(&check_point) {
Expand Down
26 changes: 23 additions & 3 deletions rust/2023/src/point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@
//!
//! ```

use std::ops::Add;
use std::{
fmt::Display,
ops::{Add, AddAssign},
};

#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, Ord, PartialOrd)]
pub struct Point {
pub x: i32,
pub y: i32,
Expand All @@ -30,6 +33,7 @@ impl Point {
}
}

/// Make it possible to sum two points
impl Add for Point {
type Output = Point;

Expand All @@ -38,8 +42,24 @@ impl Add for Point {
}
}

/// Make it possible to += two points
impl AddAssign for Point {
fn add_assign(&mut self, rhs: Self) {
self.x += rhs.x;
self.y += rhs.y;
}
}

impl Display for Point {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Point { x, y } = self;
write!(f, "({}, {})", x, y)
}
}

// Common points and directions. Useful for looking
// around a point or moving in a direction
pub const ORIGIN: Point = Point::new(0, 0);
pub const UP: Point = Point::new(0, -1);
pub const DOWN: Point = Point::new(0, 1);
pub const LEFT: Point = Point::new(-1, 0);
Expand All @@ -49,7 +69,7 @@ pub const TOP_RIGHT: Point = Point::new(1, -1);
pub const BOTTOM_LEFT: Point = Point::new(-1, 1);
pub const BOTTOM_RIGHT: Point = Point::new(1, 1);

pub const DIAGONALS: [Point; 8] =
pub const ALL_DIRECTIONS: [Point; 8] =
[
TOP_LEFT,
UP,
Expand Down

0 comments on commit 17ce039

Please sign in to comment.