1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use num_traits::{Float, PrimInt, ToPrimitive};
use std::fmt::Debug;
#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub struct Point<T: PartialOrd + PartialEq + Clone, const DIM: usize>(pub [T; DIM]);
impl<T: PartialOrd + PartialEq + Clone, const DIM: usize> std::ops::Index<usize> for Point<T, DIM> {
type Output = T;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
impl<T: PartialOrd + PartialEq + Clone, const DIM: usize> std::ops::IndexMut<usize>
for Point<T, DIM>
{
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.0[index]
}
}
pub trait FloatPoint<F: Float, const DIM: usize> {
fn squared_eucledian(&self, other: &Self) -> F;
fn distance_to_space(&self, min_bounds: &[F; DIM], max_bounds: &[F; DIM]) -> F;
}
impl<F: Float, const DIM: usize> FloatPoint<F, DIM> for Point<F, DIM> {
fn squared_eucledian(&self, other: &Self) -> F {
self.0
.iter()
.zip(other.0.iter())
.map(|(&x, &y)| (x - y) * (x - y))
.fold(F::zero(), std::ops::Add::add)
}
fn distance_to_space(&self, min_bounds: &[F; DIM], max_bounds: &[F; DIM]) -> F {
let mut other = [F::nan(); DIM];
for i in 0..DIM {
other[i] = if self[i] > max_bounds[i] {
max_bounds[i]
} else if self[i] < min_bounds[i] {
min_bounds[i]
} else {
self[i]
};
}
self.squared_eucledian(&Point(other))
}
}
pub trait IntPoint {
fn squared_eucledian(&self, other: Self) -> f64;
}
impl<I: PrimInt + ToPrimitive, const DIM: usize> IntPoint for Point<I, DIM> {
fn squared_eucledian(&self, other: Self) -> f64 {
self.0
.iter()
.zip(other.0.iter())
.map(|(&x, &y)| (x - y).to_f64().unwrap() * (x - y).to_f64().unwrap())
.fold(0., ::std::ops::Add::add)
}
}
impl<T: PartialOrd + PartialEq + Clone, const DIM: usize> From<[T; DIM]> for Point<T, DIM> {
fn from(input: [T; DIM]) -> Self {
Self(input)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normal_distance_to_space() {
let dis = Point([0.0, 0.0]).distance_to_space(&[1.0, 1.0], &[2.0, 2.0]);
assert_eq!(dis, 2.0);
}
#[test]
fn test_distance_outside_inf() {
let dis = Point([0.0, 0.0]).distance_to_space(&[1.0, 1.0], &[f64::INFINITY, f64::INFINITY]);
assert_eq!(dis, 2.0);
}
#[test]
fn test_distance_inside_inf() {
let dis = Point([2.0, 2.0]).distance_to_space(
&[f64::NEG_INFINITY, f64::NEG_INFINITY],
&[f64::INFINITY, f64::INFINITY],
);
assert_eq!(dis, 0.0);
}
#[test]
fn test_distance_inside_normal() {
let dis = Point([2.0, 2.0]).distance_to_space(&[0.0, 0.0], &[3.0, 3.0]);
assert_eq!(dis, 0.0);
}
#[test]
fn distance_to_half_space() {
let dis = Point([-2.0, 0.0])
.distance_to_space(&[0.0, f64::NEG_INFINITY], &[f64::INFINITY, f64::INFINITY]);
assert_eq!(dis, 4.0);
}
}