From 8c11d274fc75e0a393e716d43792b7912d3ac756 Mon Sep 17 00:00:00 2001 From: alejeune Date: Wed, 5 Apr 2023 10:39:22 +0200 Subject: [PATCH] Added cycle detection and withdrawal --- .../java/jobshop/solvers/TabooSolver.java | 52 ++++++++++++++++--- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/src/main/java/jobshop/solvers/TabooSolver.java b/src/main/java/jobshop/solvers/TabooSolver.java index 6b23ecd..d09095a 100644 --- a/src/main/java/jobshop/solvers/TabooSolver.java +++ b/src/main/java/jobshop/solvers/TabooSolver.java @@ -8,10 +8,7 @@ import jobshop.encodings.Schedule; import jobshop.solvers.neighborhood.Neighborhood; import java.time.format.ResolverStyle; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; +import java.util.*; public class TabooSolver implements Solver { final Neighborhood neighborhood; @@ -32,6 +29,8 @@ public class TabooSolver implements Solver { Schedule schedule = baseSolver.solve(instance, deadline,randomness,randomRunNumber).get(); ResourceOrder order = new ResourceOrder(schedule); ResourceOrder result = order; + // Create an array to store the cycle + ArrayList historic = new ArrayList(); /*for output writing*/ FileWriter fw = null; @@ -82,9 +81,15 @@ public class TabooSolver implements Solver { .toArray(ResourceOrder[]::new)[0]; result = order; } - } catch (ArrayIndexOutOfBoundsException e2) { // no solution found ==> stop - + } catch (ArrayIndexOutOfBoundsException e2) { // no solution found ==> stop } + + /* Check if we have a cycle */ + if (isCycle(historic, result.toSchedule().get())){ + System.out.println("CYCLE"); + break; + } + System.out.println("\u001b[34m" + "Current makespam : " + result.toSchedule().get().makespan() + "\u001b[0m, " + "\u001b[32m" + "Current best makespam : " + best + "\u001b[0m, " + "\u001b[33m" + "Number of neighbours : " + getNumberOfNeighbours(neighbours) + "\u001b[0m, " @@ -140,5 +145,40 @@ public class TabooSolver implements Solver { } return forbiddenNeighbours; } + + private boolean isCycle(ArrayList historic, Schedule schedule){ + historic.add(schedule.hashCode()); + Boolean found = false; + Boolean result = true; + int indexCycle = 0; + int testTurtle = 0; + int testRabbit = 0; + if (historic.size() > 20) { + historic.remove(0); + } + int rabbit = 2; + for (int turtle = 1; turtle < (historic.size()/2) - 1; turtle ++){ + if (historic.get(turtle) == historic.get(rabbit)){ + indexCycle = turtle; + found = true; + testTurtle = turtle; + testRabbit = rabbit; + break; + } + rabbit = 2*turtle; + } + if (found){ + for (int i = indexCycle; i < historic.size() - rabbit; i++) + if (historic.get(testTurtle) != historic.get(testRabbit)){ + result = false; + testTurtle ++; + testRabbit ++; + } + } + if (result && found){ + return result; + } + return false; + } }