diff --git a/core-java/README.md b/core-java/README.md index ec475c1167..3abe1ba808 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -45,3 +45,4 @@ - [Getting Started with Java Properties](http://www.baeldung.com/java-properties) - [Grep in Java](http://www.baeldung.com/grep-in-java) - [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections) +- [Simulated Annealing for Travelling Salesman Problem](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman) diff --git a/core-java/src/main/java/com/baeldung/algorithms/City.java b/core-java/src/main/java/com/baeldung/algorithms/City.java index 32335cda80..1a96dc759d 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/City.java +++ b/core-java/src/main/java/com/baeldung/algorithms/City.java @@ -5,18 +5,18 @@ import lombok.Data; @Data public class City { - private int x; - private int y; + private int x; + private int y; - public City() { - this.x = (int) (Math.random() * 500); - this.y = (int) (Math.random() * 500); - } + public City() { + this.x = (int) (Math.random() * 500); + this.y = (int) (Math.random() * 500); + } - public double distanceToCity(City city) { - int x = Math.abs(getX() - city.getX()); - int y = Math.abs(getY() - city.getY()); - return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); - } + public double distanceToCity(City city) { + int x = Math.abs(getX() - city.getX()); + int y = Math.abs(getY() - city.getY()); + return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); + } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/SimulatedAnnealing.java b/core-java/src/main/java/com/baeldung/algorithms/SimulatedAnnealing.java index 3ccba9b3e9..cf1dad098e 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/SimulatedAnnealing.java +++ b/core-java/src/main/java/com/baeldung/algorithms/SimulatedAnnealing.java @@ -25,6 +25,8 @@ public class SimulatedAnnealing { currentSolution.revertSwap(); } t *= coolingRate; + } else { + continue; } if (i % 100 == 0) { System.out.println("Iteration #" + i); @@ -34,7 +36,7 @@ public class SimulatedAnnealing { } public static void main(String[] args) { - System.out.println("Optimized distance for travel: " + simulateAnnealing(10, 10000, 0.9)); + System.out.println("Optimized distance for travel: " + simulateAnnealing(10, 10000, 0.9995)); } } diff --git a/core-java/src/main/java/com/baeldung/algorithms/Travel.java b/core-java/src/main/java/com/baeldung/algorithms/Travel.java index 6e6059b3eb..af03b0abbb 100644 --- a/core-java/src/main/java/com/baeldung/algorithms/Travel.java +++ b/core-java/src/main/java/com/baeldung/algorithms/Travel.java @@ -27,7 +27,10 @@ public class Travel { int a = generateRandomIndex(); int b = generateRandomIndex(); previousTravel = travel; - travel.set(a, travel.get(b)); + City x = travel.get(a); + City y = travel.get(b); + travel.set(a, y); + travel.set(b, x); } public void revertSwap() {