Skip to content

Instantly share code, notes, and snippets.

@n1chre
Last active January 8, 2017 19:10
Show Gist options
  • Save n1chre/2c9b274ce17aaa84403de6a2ffca52eb to your computer and use it in GitHub Desktop.
Save n1chre/2c9b274ce17aaa84403de6a2ffca52eb to your computer and use it in GitHub Desktop.
Basic tabu search implementation in Java
package hr.fer.tel.hmo.tabu.alg;
import java.util.Collection;
/**
* Interface for tabu search
*/
public interface TabuProblem<S> {
/**
* @return initial solution
*/
S initial();
/**
* @param s1 first solution
* @param s2 second solution
*
* @return is s1 better than s2
*/
boolean isBetter(S s1, S s2);
/**
* @param curr current solution
* @return neighbors of current solution
*/
Collection<S> neighborhood(S curr);
/**
* @param best best solution
* @return true if search should stop
*/
boolean stop(S best);
/**
* Update this object, called after every iteration
*
* @param curr current solution
* @param best best solution
*/
void update(S curr, S best);
}
package hr.fer.tel.hmo.tabu.alg;
import java.util.Comparator;
import java.util.Optional;
/**
* Basic tabu search implementation.
*/
public class TabuSearch {
/**
* Perform a search and return best found solution
*
* @param problem search will be performed on this problem
* @return best found solution
*/
public static <S> S search(TabuProblem<S> problem) {
S curr = problem.initial();
S best = curr;
Comparator<S> comparator = (s1, s2) -> problem.isBetter(s1, s2) ? -1 : 0;
do {
Optional<S> mini = problem.neighborhood(curr).parallelStream().min(comparator);
if (mini.isPresent()) {
curr = mini.get();
if (problem.isBetter(curr, best)) {
best = curr;
}
}
problem.update(curr, best);
} while (!problem.stop(best));
return best;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment