tsp-solver 0.0.1

Genetic travelling salesman problem solver
Documentation
use crate::TspDistance;
use ndarray::Array1;
use num::Zero;
use rand::{thread_rng, Rng};
use serde::{Deserialize, Serialize};
use std::ops::Add;

#[derive(Clone, Serialize, Deserialize)]
pub struct Point2D {
    x: f32,
    y: f32,
}

impl TspDistance for Point2D {
    fn distance(&self, other: &Self) -> f64 {
        let x = self.x - other.x;
        let y = self.y - other.y;
        ((x * x + y * y) as f64).sqrt()
    }
}

impl Add<Self> for Point2D {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self { x: self.x + rhs.x, y: self.y + rhs.y }
    }
}

impl Zero for Point2D {
    fn zero() -> Self {
        Self { x: 0.0, y: 0.0 }
    }

    fn is_zero(&self) -> bool {
        self.x == 0.0 && self.y == 0.0
    }
}

impl Point2D {
    pub fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
    pub fn random(number: usize, width: f32, height: f32) -> Array1<Self> {
        let mut rng = thread_rng();
        let mut points = Array1::zeros((number,));
        for i in 0..number {
            let x = rng.gen_range(0.0..width);
            let y = rng.gen_range(0.0..height);
            points[i] = Self { x, y }
        }
        points
    }
}