Skip to content

Commit

Permalink
implement intra three opt
Browse files Browse the repository at this point in the history
  • Loading branch information
AlpMimaroglu committed Dec 25, 2023
1 parent 69bcbe9 commit db74618
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ categories = ["Algorithms"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
itertools = "0.12.0"
44 changes: 41 additions & 3 deletions src/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::vehicle::Vehicle;
use crate::location::Location;
use crate::route::Route;
use crate::errors::InfeasableProblem;
use itertools::Itertools;

pub struct UnsolvedProblem {
vehicles: Vec<Vehicle>,
Expand Down Expand Up @@ -99,7 +100,7 @@ impl SolvedProblem {
fn two_opt(route: &mut Route) {
let n_nodes = 2;
let mut best_cost = route.cost();
for i in 0..route.destinations.len()-n_nodes {
for i in 0..route.destinations.len()-(n_nodes-1) {
let mut candidate_route_destinations = route.destinations.clone();
candidate_route_destinations.swap(i, i+n_nodes);

Expand All @@ -120,8 +121,45 @@ impl SolvedProblem {
self
}

pub fn intra_three_opt(self) -> SolvedProblem {
todo!()
pub fn intra_three_opt(mut self) -> SolvedProblem {
fn three_opt(route: &mut Route) {
let n_nodes: usize = 3;
let mut best_cost = route.cost();

let route_len = route.destinations.len();
for i in 0..route_len-(n_nodes-1) {
for j in i..route_len-(n_nodes-2) {
for k in j..route_len {
let index = [i,j,k];
let options = index.iter().permutations(3);
'options: for option in options {
let i2 = *option[0]; // vec length should be 3 for 3-opt
let j2 = *option[1]; // vec length should be 3 for 3-opt
let k2 = *option[2]; // vec length should be 3 for 3-opt

let mut candidate_route_destinations = route.destinations.clone();
candidate_route_destinations.swap(i, i2);
candidate_route_destinations.swap(j, j2);
candidate_route_destinations.swap(k, k2);

std::mem::swap(&mut route.destinations, &mut candidate_route_destinations);
let cost = route.cost();
if cost < best_cost {
best_cost = cost;
break 'options;
} else {
std::mem::swap(&mut route.destinations, &mut candidate_route_destinations);
}
}
}
}
}
}
for route in self.routes.iter_mut() {
three_opt(route)
}

self
}


Expand Down

0 comments on commit db74618

Please sign in to comment.