1
0

Add FromStr trait to Point2 and Point3, and change to i64

This commit is contained in:
Stefan Müller
2026-02-04 16:59:55 +01:00
parent a3a9eb0e45
commit b746cad9ae
3 changed files with 38 additions and 27 deletions
+36 -25
View File
@@ -1,45 +1,56 @@
#[derive(Hash, PartialEq, Eq, Debug)]
pub struct Point2(pub u64, pub u64);
use std::str::FromStr;
#[derive(Hash, PartialEq, Eq, Debug, Copy, Clone)]
pub struct Point2(pub i64, pub i64);
impl Point2 {
const POINT_SPLIT_CHAR: char = ',';
pub fn from_line(line: &str) -> Self {
let p: Vec<u64> = line
.split(Self::POINT_SPLIT_CHAR)
.map(|s| {
s.parse()
.expect(&format!("could not create Point2 from line '{line}'"))
})
.collect();
Self(p[0], p[1])
}
pub fn rect_area(&self, other: &Self) -> u64 {
(self.0.abs_diff(other.0) + 1) * (self.1.abs_diff(other.1) + 1)
}
}
impl FromStr for Point2 {
type Err = ParsePointError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (x_str, y_str) = s
.split_once(Self::POINT_SPLIT_CHAR)
.ok_or(ParsePointError)?;
let x = x_str.parse::<i64>().map_err(|_| ParsePointError)?;
let y = y_str.parse::<i64>().map_err(|_| ParsePointError)?;
Ok(Self(x, y))
}
}
#[derive(Hash, PartialEq, Eq, Debug)]
pub struct Point3(pub u64, pub u64, pub u64);
pub struct Point3(pub i64, pub i64, pub i64);
impl Point3 {
const POINT_SPLIT_CHAR: char = ',';
pub fn from_line(line: &str) -> Self {
let p: Vec<u64> = line
.split(Self::POINT_SPLIT_CHAR)
.map(|s| {
s.parse()
.expect(&format!("could not create Point3 from line '{line}'"))
})
.collect();
Self(p[0], p[1], p[2])
}
pub fn distance_sqr(&self, other: &Self) -> u64 {
self.0.abs_diff(other.0).pow(2)
+ self.1.abs_diff(other.1).pow(2)
+ self.2.abs_diff(other.2).pow(2)
}
}
impl FromStr for Point3 {
type Err = ParsePointError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let p = s
.split(Self::POINT_SPLIT_CHAR)
.map(|s| s.parse::<i64>().map_err(|_| ParsePointError))
.collect::<Result<Vec<i64>, Self::Err>>()?;
match p.as_slice() {
[x, y, z] => Ok(Self(*x, *y, *z)),
_ => Err(ParsePointError),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct ParsePointError;
+1 -1
View File
@@ -9,7 +9,7 @@ impl MovieTheater {
fn red_tiles<R: BufRead>(reader: R) -> Vec<Point2> {
let mut red_tiles = Vec::new();
for line in reader.lines().map_while(Result::ok) {
red_tiles.push(Point2::from_line(&line));
red_tiles.push(line.parse::<Point2>().unwrap());
}
red_tiles
}
+1 -1
View File
@@ -20,7 +20,7 @@ impl Playground {
fn junction_boxes<R: BufRead>(reader: R) -> Vec<Point3> {
let mut junction_boxes = Vec::new();
for line in reader.lines().map_while(Result::ok) {
junction_boxes.push(Point3::from_line(&line));
junction_boxes.push(line.parse::<Point3>().unwrap());
}
junction_boxes
}