From 0ef7b7f5f8bdcdf492b1fc419279e7a7ea3fe666 Mon Sep 17 00:00:00 2001 From: Rutherther Date: Sat, 1 Nov 2025 19:41:25 +0100 Subject: [PATCH] feat(tsp): add TSPInstance convertor to GenericGraph --- codes/tsp_hw01/src/tsp.rs | 45 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/codes/tsp_hw01/src/tsp.rs b/codes/tsp_hw01/src/tsp.rs index 13d9fa4218f0b0ee81cdbcd67f5c80b2f2d1f5e2..2ecbcf27fd0009bb03d57b3c2104ff8471ae27a8 100644 --- a/codes/tsp_hw01/src/tsp.rs +++ b/codes/tsp_hw01/src/tsp.rs @@ -5,11 +5,38 @@ use itertools::Itertools; use nalgebra::{allocator::Allocator, distance, Const, DefaultAllocator, Dim, Dyn, OMatrix, OVector, Point}; use plotters::prelude::*; +use crate::graph::{minimal_spanning_tree_kruskal, Edge, GenericGraph, Graph, WeightedEdge}; + #[derive(PartialEq, Clone, Debug)] pub struct TSPCity { point: Point } +#[derive(Debug)] +pub struct TSPEdge { + from: usize, + to: usize, + distance: f64 +} + +impl Edge for TSPEdge { + fn from_node(&self) -> usize { + self.from + } + + fn to_node(&self) -> usize { + self.to + } +} + +impl WeightedEdge for TSPEdge { + type Cost = f64; + + fn cost(&self) -> Self::Cost { + self.distance + } +} + #[derive(PartialEq, Clone, Debug)] pub struct NodePermutation where @@ -78,6 +105,23 @@ where distances } } + + pub fn to_graph(self) -> GenericGraph { + let cities = self.cities.len(); + let mut graph = GenericGraph::new(self.cities, false); + + for i in 0..cities { + for j in i+1..cities { + graph.add_generic_edge(TSPEdge { + from: i, + to: j, + distance: self.distances[(i, j)] + }); + } + } + + graph + } } impl TSPInstance @@ -435,7 +479,6 @@ mod tests { assert_eq!(vec![0usize, 1, 3, 4, 5, 2], offspring.permutation.into_iter().copied().collect::>()) } - #[test] fn test_reverse_subsequence_perturbation_behavior() { let perturbation = ReverseSubsequencePerturbation::>::new();