Merge pull request #8 from eugenp/master

Pulling latest changes
This commit is contained in:
Chandra Prakash 2018-11-07 17:11:15 -05:00 committed by GitHub
commit d578e45a8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2141 changed files with 88413 additions and 6733 deletions

4
.gitignore vendored
View File

@ -63,4 +63,6 @@ jmeter/src/main/resources/*-JMeter.csv
**/tmp **/tmp
**/out-tsc **/out-tsc
**/nbproject/ **/nbproject/
**/nb-configuration.xml **/nb-configuration.xml
core-scala/.cache-main
core-scala/.cache-tests

View File

@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip install: skip
script: travis_wait 60 mvn -q install -Pdefault script: travis_wait 60 mvn -q install -Pdefault-first,default-second
sudo: required sudo: required

View File

@ -21,3 +21,18 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
Building the project Building the project
==================== ====================
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false` To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
Building a single module
====================
To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory
Running a Spring Boot module
====================
To run a Spring Boot module run the command: `mvn spring-boot:run -Dgib.enabled=false` in the module directory

View File

@ -1,5 +1,4 @@
/target/ /target/
.settings/ .settings/
.classpath .classpath
.project .project

View File

@ -0,0 +1,6 @@
## Relevant articles:
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)

View File

@ -0,0 +1,64 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-genetic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.jenetics</groupId>
<artifactId>jenetics</artifactId>
<version>${io.jenetics.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${org.assertj.core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<io.jenetics.version>3.7.0</io.jenetics.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
</properties>
</project>

View File

@ -5,7 +5,6 @@ import java.util.Scanner;
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing; import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm { public class RunAlgorithm {
@ -13,11 +12,8 @@ public class RunAlgorithm {
Scanner in = new Scanner(System.in); Scanner in = new Scanner(System.in);
System.out.println("Run algorithm:"); System.out.println("Run algorithm:");
System.out.println("1 - Simulated Annealing"); System.out.println("1 - Simulated Annealing");
System.out.println("2 - Slope One"); System.out.println("2 - Simple Genetic Algorithm");
System.out.println("3 - Simple Genetic Algorithm"); System.out.println("3 - Ant Colony");
System.out.println("4 - Ant Colony");
System.out.println("5 - Dijkstra");
System.out.println("6 - All pairs in an array that add up to a given sum");
int decision = in.nextInt(); int decision = in.nextInt();
switch (decision) { switch (decision) {
case 1: case 1:
@ -25,19 +21,13 @@ public class RunAlgorithm {
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); "Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
break; break;
case 2: case 2:
SlopeOne.slopeOne(3);
break;
case 3:
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111"); ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
break; break;
case 4: case 3:
AntColonyOptimization antColony = new AntColonyOptimization(21); AntColonyOptimization antColony = new AntColonyOptimization(21);
antColony.startAntOptimization(); antColony.startAntOptimization();
break; break;
case 5:
System.out.println("Please run the DijkstraAlgorithmTest.");
break;
default: default:
System.out.println("Unknown option"); System.out.println("Unknown option");
break; break;

4
algorithms-miscellaneous-1/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/target/
.settings/
.classpath
.project

View File

@ -0,0 +1,13 @@
## Relevant articles:
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/java-finite-automata)
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)
- [Binary Search Algorithm in Java](http://www.baeldung.com/java-binary-search)
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)

View File

@ -0,0 +1,78 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-miscellaneous-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${org.assertj.core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version>
<configuration>
<instrumentation>
<ignores>
<ignore>com/baeldung/algorithms/dijkstra/*</ignore>
</ignores>
<excludes>
<exclude>com/baeldung/algorithms/dijkstra/*</exclude>
</excludes>
</instrumentation>
</configuration>
</plugin>
</plugins>
</reporting>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
</properties>
</project>

4
algorithms-miscellaneous-2/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/target/
.settings/
.classpath
.project

View File

@ -0,0 +1,19 @@
## Relevant articles:
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
- [Test a Linked List for Cyclicity](http://www.baeldung.com/java-linked-list-cyclicity)
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
- [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze)
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)

View File

@ -1,90 +1,90 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>algorithms</artifactId> <artifactId>algorithms-miscellaneous-2</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId> <artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version> <version>${commons-math3.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>commons-codec</groupId>
<artifactId>lombok</artifactId> <artifactId>commons-codec</artifactId>
<version>${lombok.version}</version> <version>${commons-codec.version}</version>
<scope>provided</scope> </dependency>
</dependency> <dependency>
<dependency> <groupId>org.projectlombok</groupId>
<groupId>io.jenetics</groupId> <artifactId>lombok</artifactId>
<artifactId>jenetics</artifactId> <version>${lombok.version}</version>
<version>${io.jenetics.version}</version> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.jgrapht</groupId> <groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId> <artifactId>jgrapht-core</artifactId>
<version>${org.jgrapht.core.version}</version> <version>${org.jgrapht.core.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>pl.allegro.finance</groupId> <groupId>pl.allegro.finance</groupId>
<artifactId>tradukisto</artifactId> <artifactId>tradukisto</artifactId>
<version>${tradukisto.version}</version> <version>${tradukisto.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
<version>${org.assertj.core.version}</version> <version>${org.assertj.core.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId> <artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version> <version>${exec-maven-plugin.version}</version>
</plugin> </plugin>
</plugins> </plugins>
</pluginManagement> </pluginManagement>
</build> </build>
<reporting> <reporting>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId> <artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version> <version>2.7</version>
<configuration> <configuration>
<instrumentation> <instrumentation>
<ignores> <ignores>
<ignore>com/baeldung/algorithms/dijkstra/*</ignore> <ignore>com/baeldung/algorithms/dijkstra/*</ignore>
</ignores> </ignores>
<excludes> <excludes>
<exclude>com/baeldung/algorithms/dijkstra/*</exclude> <exclude>com/baeldung/algorithms/dijkstra/*</exclude>
</excludes> </excludes>
</instrumentation> </instrumentation>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</reporting> </reporting>
<properties> <properties>
<lombok.version>1.16.12</lombok.version> <lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version> <commons-math3.version>3.6.1</commons-math3.version>
<tradukisto.version>1.0.1</tradukisto.version> <tradukisto.version>1.0.1</tradukisto.version>
<io.jenetics.version>3.7.0</io.jenetics.version> <org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version> <org.assertj.core.version>3.9.0</org.assertj.core.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version> <commons-codec.version>1.11</commons-codec.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,28 @@
package com.baeldung.algorithms;
import java.util.Scanner;
import com.baeldung.algorithms.slope_one.SlopeOne;
public class RunAlgorithm {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Scanner in = new Scanner(System.in);
System.out.println("1 - Slope One");
System.out.println("2 - Dijkstra");
int decision = in.nextInt();
switch (decision) {
case 1:
SlopeOne.slopeOne(3);
break;
case 2:
System.out.println("Please run the DijkstraAlgorithmLongRunningUnitTest.");
break;
default:
System.out.println("Unknown option");
break;
}
in.close();
}
}

View File

@ -0,0 +1,110 @@
package com.baeldung.algorithms.conversion;
import java.math.BigInteger;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import com.google.common.io.BaseEncoding;
public class HexStringConverter {
/**
* Create a byte Array from String of hexadecimal digits using Character conversion
* @param hexString - Hexadecimal digits as String
* @return Desired byte Array
*/
public byte[] decodeHexString(String hexString) {
if (hexString.length() % 2 == 1) {
throw new IllegalArgumentException("Invalid hexadecimal String supplied.");
}
byte[] bytes = new byte[hexString.length() / 2];
for (int i = 0; i < hexString.length(); i += 2) {
bytes[i / 2] = hexToByte(hexString.substring(i, i + 2));
}
return bytes;
}
/**
* Create a String of hexadecimal digits from a byte Array using Character conversion
* @param byteArray - The byte Array
* @return Desired String of hexadecimal digits in lower case
*/
public String encodeHexString(byte[] byteArray) {
StringBuffer hexStringBuffer = new StringBuffer();
for (int i = 0; i < byteArray.length; i++) {
hexStringBuffer.append(byteToHex(byteArray[i]));
}
return hexStringBuffer.toString();
}
public String byteToHex(byte num) {
char[] hexDigits = new char[2];
hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16);
hexDigits[1] = Character.forDigit((num & 0xF), 16);
return new String(hexDigits);
}
public byte hexToByte(String hexString) {
int firstDigit = toDigit(hexString.charAt(0));
int secondDigit = toDigit(hexString.charAt(1));
return (byte) ((firstDigit << 4) + secondDigit);
}
private int toDigit(char hexChar) {
int digit = Character.digit(hexChar, 16);
if(digit == -1) {
throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar);
}
return digit;
}
public String encodeUsingBigIntegerToString(byte[] bytes) {
BigInteger bigInteger = new BigInteger(1, bytes);
return bigInteger.toString(16);
}
public String encodeUsingBigIntegerStringFormat(byte[] bytes) {
BigInteger bigInteger = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "x", bigInteger);
}
public byte[] decodeUsingBigInteger(String hexString) {
byte[] byteArray = new BigInteger(hexString, 16).toByteArray();
if (byteArray[0] == 0) {
byte[] output = new byte[byteArray.length - 1];
System.arraycopy(byteArray, 1, output, 0, output.length);
return output;
}
return byteArray;
}
public String encodeUsingDataTypeConverter(byte[] bytes) {
return DatatypeConverter.printHexBinary(bytes);
}
public byte[] decodeUsingDataTypeConverter(String hexString) {
return DatatypeConverter.parseHexBinary(hexString);
}
public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException {
return Hex.encodeHexString(bytes);
}
public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException {
return Hex.decodeHex(hexString);
}
public String encodeUsingGuava(byte[] bytes) {
return BaseEncoding.base16()
.encode(bytes);
}
public byte[] decodeUsingGuava(String hexString) {
return BaseEncoding.base16()
.decode(hexString.toUpperCase());
}
}

View File

@ -1,15 +1,15 @@
package com.baeldung.algorithms.editdistance; package com.baeldung.algorithms.editdistance;
import java.util.Arrays; import java.util.Arrays;
public class EditDistanceBase { public class EditDistanceBase {
static int costOfSubstitution(char a, char b) { static int costOfSubstitution(char a, char b) {
return a == b ? 0 : 1; return a == b ? 0 : 1;
} }
static int min(int... numbers) { static int min(int... numbers) {
return Arrays.stream(numbers) return Arrays.stream(numbers)
.min().orElse(Integer.MAX_VALUE); .min().orElse(Integer.MAX_VALUE);
} }
} }

View File

@ -1,26 +1,26 @@
package com.baeldung.algorithms.editdistance; package com.baeldung.algorithms.editdistance;
public class EditDistanceDynamicProgramming extends EditDistanceBase { public class EditDistanceDynamicProgramming extends EditDistanceBase {
static int calculate(String x, String y) { static int calculate(String x, String y) {
int[][] dp = new int[x.length() + 1][y.length() + 1]; int[][] dp = new int[x.length() + 1][y.length() + 1];
for (int i = 0; i <= x.length(); i++) { for (int i = 0; i <= x.length(); i++) {
for (int j = 0; j <= y.length(); j++) { for (int j = 0; j <= y.length(); j++) {
if (i == 0) if (i == 0)
dp[i][j] = j; dp[i][j] = j;
else if (j == 0) else if (j == 0)
dp[i][j] = i; dp[i][j] = i;
else { else {
dp[i][j] = min(dp[i - 1][j - 1] dp[i][j] = min(dp[i - 1][j - 1]
+ costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)), + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)),
dp[i - 1][j] + 1, dp[i][j - 1] + 1); dp[i - 1][j] + 1, dp[i][j - 1] + 1);
} }
} }
} }
return dp[x.length()][y.length()]; return dp[x.length()][y.length()];
} }
} }

View File

@ -1,21 +1,21 @@
package com.baeldung.algorithms.editdistance; package com.baeldung.algorithms.editdistance;
public class EditDistanceRecursive extends EditDistanceBase { public class EditDistanceRecursive extends EditDistanceBase {
static int calculate(String x, String y) { static int calculate(String x, String y) {
if (x.isEmpty()) { if (x.isEmpty()) {
return y.length(); return y.length();
} }
if (y.isEmpty()) { if (y.isEmpty()) {
return x.length(); return x.length();
} }
int substitution = calculate(x.substring(1), y.substring(1)) + costOfSubstitution(x.charAt(0), y.charAt(0)); int substitution = calculate(x.substring(1), y.substring(1)) + costOfSubstitution(x.charAt(0), y.charAt(0));
int insertion = calculate(x, y.substring(1)) + 1; int insertion = calculate(x, y.substring(1)) + 1;
int deletion = calculate(x.substring(1), y) + 1; int deletion = calculate(x.substring(1), y) + 1;
return min(substitution, insertion, deletion); return min(substitution, insertion, deletion);
} }
} }

View File

@ -1,38 +1,38 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
public class CycleDetectionBruteForce { public class CycleDetectionBruteForce {
public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) { public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) {
if (head == null) { if (head == null) {
return new CycleDetectionResult<>(false, null); return new CycleDetectionResult<>(false, null);
} }
Node<T> it1 = head; Node<T> it1 = head;
int nodesTraversedByOuter = 0; int nodesTraversedByOuter = 0;
while (it1 != null && it1.next != null) { while (it1 != null && it1.next != null) {
it1 = it1.next; it1 = it1.next;
nodesTraversedByOuter++; nodesTraversedByOuter++;
int x = nodesTraversedByOuter; int x = nodesTraversedByOuter;
Node<T> it2 = head; Node<T> it2 = head;
int noOfTimesCurrentNodeVisited = 0; int noOfTimesCurrentNodeVisited = 0;
while (x > 0) { while (x > 0) {
it2 = it2.next; it2 = it2.next;
if (it2 == it1) { if (it2 == it1) {
noOfTimesCurrentNodeVisited++; noOfTimesCurrentNodeVisited++;
} }
if (noOfTimesCurrentNodeVisited == 2) { if (noOfTimesCurrentNodeVisited == 2) {
return new CycleDetectionResult<>(true, it1); return new CycleDetectionResult<>(true, it1);
} }
x--; x--;
} }
} }
return new CycleDetectionResult<>(false, null); return new CycleDetectionResult<>(false, null);
} }
} }

View File

@ -1,25 +1,25 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
public class CycleDetectionByFastAndSlowIterators { public class CycleDetectionByFastAndSlowIterators {
public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) { public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) {
if (head == null) { if (head == null) {
return new CycleDetectionResult<>(false, null); return new CycleDetectionResult<>(false, null);
} }
Node<T> slow = head; Node<T> slow = head;
Node<T> fast = head; Node<T> fast = head;
while (fast != null && fast.next != null) { while (fast != null && fast.next != null) {
slow = slow.next; slow = slow.next;
fast = fast.next.next; fast = fast.next.next;
if (slow == fast) { if (slow == fast) {
return new CycleDetectionResult<>(true, fast); return new CycleDetectionResult<>(true, fast);
} }
} }
return new CycleDetectionResult<>(false, null); return new CycleDetectionResult<>(false, null);
} }
} }

View File

@ -1,27 +1,27 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
public class CycleDetectionByHashing { public class CycleDetectionByHashing {
public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) { public static <T> CycleDetectionResult<T> detectCycle(Node<T> head) {
if (head == null) { if (head == null) {
return new CycleDetectionResult<>(false, null); return new CycleDetectionResult<>(false, null);
} }
Set<Node<T>> set = new HashSet<>(); Set<Node<T>> set = new HashSet<>();
Node<T> node = head; Node<T> node = head;
while (node != null) { while (node != null) {
if (set.contains(node)) { if (set.contains(node)) {
return new CycleDetectionResult<>(true, node); return new CycleDetectionResult<>(true, node);
} }
set.add(node); set.add(node);
node = node.next; node = node.next;
} }
return new CycleDetectionResult<>(false, null); return new CycleDetectionResult<>(false, null);
} }
} }

View File

@ -1,12 +1,12 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
public class CycleDetectionResult<T> { public class CycleDetectionResult<T> {
boolean cycleExists; boolean cycleExists;
Node<T> node; Node<T> node;
public CycleDetectionResult(boolean cycleExists, Node<T> node) { public CycleDetectionResult(boolean cycleExists, Node<T> node) {
super(); super();
this.cycleExists = cycleExists; this.cycleExists = cycleExists;
this.node = node; this.node = node;
} }
} }

View File

@ -1,56 +1,56 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
public class CycleRemovalBruteForce { public class CycleRemovalBruteForce {
public static <T> boolean detectAndRemoveCycle(Node<T> head) { public static <T> boolean detectAndRemoveCycle(Node<T> head) {
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head); CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) { if (result.cycleExists) {
removeCycle(result.node, head); removeCycle(result.node, head);
} }
return result.cycleExists; return result.cycleExists;
} }
/** /**
* @param loopNodeParam - reference to the node where Flyods cycle * @param loopNodeParam - reference to the node where Flyods cycle
* finding algorithm ends, i.e. the fast and the slow iterators * finding algorithm ends, i.e. the fast and the slow iterators
* meet. * meet.
* @param head - reference to the head of the list * @param head - reference to the head of the list
*/ */
private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) { private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) {
Node<T> it = head; Node<T> it = head;
while (it != null) { while (it != null) {
if (isNodeReachableFromLoopNode(it, loopNodeParam)) { if (isNodeReachableFromLoopNode(it, loopNodeParam)) {
Node<T> loopStart = it; Node<T> loopStart = it;
findEndNodeAndBreakCycle(loopStart); findEndNodeAndBreakCycle(loopStart);
break; break;
} }
it = it.next; it = it.next;
} }
} }
private static <T> boolean isNodeReachableFromLoopNode(Node<T> it, Node<T> loopNodeParam) { private static <T> boolean isNodeReachableFromLoopNode(Node<T> it, Node<T> loopNodeParam) {
Node<T> loopNode = loopNodeParam; Node<T> loopNode = loopNodeParam;
do { do {
if (it == loopNode) { if (it == loopNode) {
return true; return true;
} }
loopNode = loopNode.next; loopNode = loopNode.next;
} while (loopNode.next != loopNodeParam); } while (loopNode.next != loopNodeParam);
return false; return false;
} }
private static <T> void findEndNodeAndBreakCycle(Node<T> loopStartParam) { private static <T> void findEndNodeAndBreakCycle(Node<T> loopStartParam) {
Node<T> loopStart = loopStartParam; Node<T> loopStart = loopStartParam;
while (loopStart.next != loopStartParam) { while (loopStart.next != loopStartParam) {
loopStart = loopStart.next; loopStart = loopStart.next;
} }
loopStart.next = null; loopStart.next = null;
} }
} }

View File

@ -1,44 +1,44 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
public class CycleRemovalByCountingLoopNodes { public class CycleRemovalByCountingLoopNodes {
public static <T> boolean detectAndRemoveCycle(Node<T> head) { public static <T> boolean detectAndRemoveCycle(Node<T> head) {
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head); CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) { if (result.cycleExists) {
removeCycle(result.node, head); removeCycle(result.node, head);
} }
return result.cycleExists; return result.cycleExists;
} }
private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) { private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) {
int cycleLength = calculateCycleLength(loopNodeParam); int cycleLength = calculateCycleLength(loopNodeParam);
Node<T> cycleLengthAdvancedIterator = head; Node<T> cycleLengthAdvancedIterator = head;
Node<T> it = head; Node<T> it = head;
for (int i = 0; i < cycleLength; i++) { for (int i = 0; i < cycleLength; i++) {
cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next; cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next;
} }
while (it.next != cycleLengthAdvancedIterator.next) { while (it.next != cycleLengthAdvancedIterator.next) {
it = it.next; it = it.next;
cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next; cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next;
} }
cycleLengthAdvancedIterator.next = null; cycleLengthAdvancedIterator.next = null;
} }
private static <T> int calculateCycleLength(Node<T> loopNodeParam) { private static <T> int calculateCycleLength(Node<T> loopNodeParam) {
Node<T> loopNode = loopNodeParam; Node<T> loopNode = loopNodeParam;
int length = 1; int length = 1;
while (loopNode.next != loopNodeParam) { while (loopNode.next != loopNodeParam) {
length++; length++;
loopNode = loopNode.next; loopNode = loopNode.next;
} }
return length; return length;
} }
} }

View File

@ -1,27 +1,27 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
public class CycleRemovalWithoutCountingLoopNodes { public class CycleRemovalWithoutCountingLoopNodes {
public static <T> boolean detectAndRemoveCycle(Node<T> head) { public static <T> boolean detectAndRemoveCycle(Node<T> head) {
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head); CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) { if (result.cycleExists) {
removeCycle(result.node, head); removeCycle(result.node, head);
} }
return result.cycleExists; return result.cycleExists;
} }
private static <T> void removeCycle(Node<T> meetingPointParam, Node<T> head) { private static <T> void removeCycle(Node<T> meetingPointParam, Node<T> head) {
Node<T> loopNode = meetingPointParam; Node<T> loopNode = meetingPointParam;
Node<T> it = head; Node<T> it = head;
while (loopNode.next != it.next) { while (loopNode.next != it.next) {
it = it.next; it = it.next;
loopNode = loopNode.next; loopNode = loopNode.next;
} }
loopNode.next = null; loopNode.next = null;
} }
} }

View File

@ -1,38 +1,38 @@
package com.baeldung.algorithms.linkedlist; package com.baeldung.algorithms.linkedlist;
public class Node<T> { public class Node<T> {
T data; T data;
Node<T> next; Node<T> next;
public static <T> Node<T> createNewNode(T data, Node<T> next) { public static <T> Node<T> createNewNode(T data, Node<T> next) {
Node<T> node = new Node<T>(); Node<T> node = new Node<T>();
node.data = data; node.data = data;
node.next = next; node.next = next;
return node; return node;
} }
public static <T> void traverseList(Node<T> root) { public static <T> void traverseList(Node<T> root) {
if (root == null) { if (root == null) {
return; return;
} }
Node<T> node = root; Node<T> node = root;
while (node != null) { while (node != null) {
System.out.println(node.data); System.out.println(node.data);
node = node.next; node = node.next;
} }
} }
public static <T> Node<T> getTail(Node<T> root) { public static <T> Node<T> getTail(Node<T> root) {
if (root == null) { if (root == null) {
return null; return null;
} }
Node<T> node = root; Node<T> node = root;
while (node.next != null) { while (node.next != null) {
node = node.next; node = node.next;
} }
return node; return node;
} }
} }

View File

@ -1,52 +1,52 @@
package com.baeldung.algorithms.maze.solver; package com.baeldung.algorithms.maze.solver;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
public class BFSMazeSolver { public class BFSMazeSolver {
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
public List<Coordinate> solve(Maze maze) { public List<Coordinate> solve(Maze maze) {
LinkedList<Coordinate> nextToVisit = new LinkedList<>(); LinkedList<Coordinate> nextToVisit = new LinkedList<>();
Coordinate start = maze.getEntry(); Coordinate start = maze.getEntry();
nextToVisit.add(start); nextToVisit.add(start);
while (!nextToVisit.isEmpty()) { while (!nextToVisit.isEmpty()) {
Coordinate cur = nextToVisit.remove(); Coordinate cur = nextToVisit.remove();
if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) { if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) {
continue; continue;
} }
if (maze.isWall(cur.getX(), cur.getY())) { if (maze.isWall(cur.getX(), cur.getY())) {
maze.setVisited(cur.getX(), cur.getY(), true); maze.setVisited(cur.getX(), cur.getY(), true);
continue; continue;
} }
if (maze.isExit(cur.getX(), cur.getY())) { if (maze.isExit(cur.getX(), cur.getY())) {
return backtrackPath(cur); return backtrackPath(cur);
} }
for (int[] direction : DIRECTIONS) { for (int[] direction : DIRECTIONS) {
Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur); Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur);
nextToVisit.add(coordinate); nextToVisit.add(coordinate);
maze.setVisited(cur.getX(), cur.getY(), true); maze.setVisited(cur.getX(), cur.getY(), true);
} }
} }
return Collections.emptyList(); return Collections.emptyList();
} }
private List<Coordinate> backtrackPath(Coordinate cur) { private List<Coordinate> backtrackPath(Coordinate cur) {
List<Coordinate> path = new ArrayList<>(); List<Coordinate> path = new ArrayList<>();
Coordinate iter = cur; Coordinate iter = cur;
while (iter != null) { while (iter != null) {
path.add(iter); path.add(iter);
iter = iter.parent; iter = iter.parent;
} }
return path; return path;
} }
} }

View File

@ -1,31 +1,31 @@
package com.baeldung.algorithms.maze.solver; package com.baeldung.algorithms.maze.solver;
public class Coordinate { public class Coordinate {
int x; int x;
int y; int y;
Coordinate parent; Coordinate parent;
public Coordinate(int x, int y) { public Coordinate(int x, int y) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.parent = null; this.parent = null;
} }
public Coordinate(int x, int y, Coordinate parent) { public Coordinate(int x, int y, Coordinate parent) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.parent = parent; this.parent = parent;
} }
int getX() { int getX() {
return x; return x;
} }
int getY() { int getY() {
return y; return y;
} }
Coordinate getParent() { Coordinate getParent() {
return parent; return parent;
} }
} }

View File

@ -1,48 +1,48 @@
package com.baeldung.algorithms.maze.solver; package com.baeldung.algorithms.maze.solver;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
public class DFSMazeSolver { public class DFSMazeSolver {
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
public List<Coordinate> solve(Maze maze) { public List<Coordinate> solve(Maze maze) {
List<Coordinate> path = new ArrayList<>(); List<Coordinate> path = new ArrayList<>();
if (explore(maze, maze.getEntry() if (explore(maze, maze.getEntry()
.getX(), .getX(),
maze.getEntry() maze.getEntry()
.getY(), .getY(),
path)) { path)) {
return path; return path;
} }
return Collections.emptyList(); return Collections.emptyList();
} }
private boolean explore(Maze maze, int row, int col, List<Coordinate> path) { private boolean explore(Maze maze, int row, int col, List<Coordinate> path) {
if (!maze.isValidLocation(row, col) || maze.isWall(row, col) || maze.isExplored(row, col)) { if (!maze.isValidLocation(row, col) || maze.isWall(row, col) || maze.isExplored(row, col)) {
return false; return false;
} }
path.add(new Coordinate(row, col)); path.add(new Coordinate(row, col));
maze.setVisited(row, col, true); maze.setVisited(row, col, true);
if (maze.isExit(row, col)) { if (maze.isExit(row, col)) {
return true; return true;
} }
for (int[] direction : DIRECTIONS) { for (int[] direction : DIRECTIONS) {
Coordinate coordinate = getNextCoordinate(row, col, direction[0], direction[1]); Coordinate coordinate = getNextCoordinate(row, col, direction[0], direction[1]);
if (explore(maze, coordinate.getX(), coordinate.getY(), path)) { if (explore(maze, coordinate.getX(), coordinate.getY(), path)) {
return true; return true;
} }
} }
path.remove(path.size() - 1); path.remove(path.size() - 1);
return false; return false;
} }
private Coordinate getNextCoordinate(int row, int col, int i, int j) { private Coordinate getNextCoordinate(int row, int col, int i, int j) {
return new Coordinate(row + i, col + j); return new Coordinate(row + i, col + j);
} }
} }

View File

@ -1,141 +1,141 @@
package com.baeldung.algorithms.maze.solver; package com.baeldung.algorithms.maze.solver;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Scanner; import java.util.Scanner;
public class Maze { public class Maze {
private static final int ROAD = 0; private static final int ROAD = 0;
private static final int WALL = 1; private static final int WALL = 1;
private static final int START = 2; private static final int START = 2;
private static final int EXIT = 3; private static final int EXIT = 3;
private static final int PATH = 4; private static final int PATH = 4;
private int[][] maze; private int[][] maze;
private boolean[][] visited; private boolean[][] visited;
private Coordinate start; private Coordinate start;
private Coordinate end; private Coordinate end;
public Maze(File maze) throws FileNotFoundException { public Maze(File maze) throws FileNotFoundException {
String fileText = ""; String fileText = "";
try (Scanner input = new Scanner(maze)) { try (Scanner input = new Scanner(maze)) {
while (input.hasNextLine()) { while (input.hasNextLine()) {
fileText += input.nextLine() + "\n"; fileText += input.nextLine() + "\n";
} }
} }
initializeMaze(fileText); initializeMaze(fileText);
} }
private void initializeMaze(String text) { private void initializeMaze(String text) {
if (text == null || (text = text.trim()).length() == 0) { if (text == null || (text = text.trim()).length() == 0) {
throw new IllegalArgumentException("empty lines data"); throw new IllegalArgumentException("empty lines data");
} }
String[] lines = text.split("[\r]?\n"); String[] lines = text.split("[\r]?\n");
maze = new int[lines.length][lines[0].length()]; maze = new int[lines.length][lines[0].length()];
visited = new boolean[lines.length][lines[0].length()]; visited = new boolean[lines.length][lines[0].length()];
for (int row = 0; row < getHeight(); row++) { for (int row = 0; row < getHeight(); row++) {
if (lines[row].length() != getWidth()) { if (lines[row].length() != getWidth()) {
throw new IllegalArgumentException("line " + (row + 1) + " wrong length (was " + lines[row].length() + " but should be " + getWidth() + ")"); throw new IllegalArgumentException("line " + (row + 1) + " wrong length (was " + lines[row].length() + " but should be " + getWidth() + ")");
} }
for (int col = 0; col < getWidth(); col++) { for (int col = 0; col < getWidth(); col++) {
if (lines[row].charAt(col) == '#') if (lines[row].charAt(col) == '#')
maze[row][col] = WALL; maze[row][col] = WALL;
else if (lines[row].charAt(col) == 'S') { else if (lines[row].charAt(col) == 'S') {
maze[row][col] = START; maze[row][col] = START;
start = new Coordinate(row, col); start = new Coordinate(row, col);
} else if (lines[row].charAt(col) == 'E') { } else if (lines[row].charAt(col) == 'E') {
maze[row][col] = EXIT; maze[row][col] = EXIT;
end = new Coordinate(row, col); end = new Coordinate(row, col);
} else } else
maze[row][col] = ROAD; maze[row][col] = ROAD;
} }
} }
} }
public int getHeight() { public int getHeight() {
return maze.length; return maze.length;
} }
public int getWidth() { public int getWidth() {
return maze[0].length; return maze[0].length;
} }
public Coordinate getEntry() { public Coordinate getEntry() {
return start; return start;
} }
public Coordinate getExit() { public Coordinate getExit() {
return end; return end;
} }
public boolean isExit(int x, int y) { public boolean isExit(int x, int y) {
return x == end.getX() && y == end.getY(); return x == end.getX() && y == end.getY();
} }
public boolean isStart(int x, int y) { public boolean isStart(int x, int y) {
return x == start.getX() && y == start.getY(); return x == start.getX() && y == start.getY();
} }
public boolean isExplored(int row, int col) { public boolean isExplored(int row, int col) {
return visited[row][col]; return visited[row][col];
} }
public boolean isWall(int row, int col) { public boolean isWall(int row, int col) {
return maze[row][col] == WALL; return maze[row][col] == WALL;
} }
public void setVisited(int row, int col, boolean value) { public void setVisited(int row, int col, boolean value) {
visited[row][col] = value; visited[row][col] = value;
} }
public boolean isValidLocation(int row, int col) { public boolean isValidLocation(int row, int col) {
if (row < 0 || row >= getHeight() || col < 0 || col >= getWidth()) { if (row < 0 || row >= getHeight() || col < 0 || col >= getWidth()) {
return false; return false;
} }
return true; return true;
} }
public void printPath(List<Coordinate> path) { public void printPath(List<Coordinate> path) {
int[][] tempMaze = Arrays.stream(maze) int[][] tempMaze = Arrays.stream(maze)
.map(int[]::clone) .map(int[]::clone)
.toArray(int[][]::new); .toArray(int[][]::new);
for (Coordinate coordinate : path) { for (Coordinate coordinate : path) {
if (isStart(coordinate.getX(), coordinate.getY()) || isExit(coordinate.getX(), coordinate.getY())) { if (isStart(coordinate.getX(), coordinate.getY()) || isExit(coordinate.getX(), coordinate.getY())) {
continue; continue;
} }
tempMaze[coordinate.getX()][coordinate.getY()] = PATH; tempMaze[coordinate.getX()][coordinate.getY()] = PATH;
} }
System.out.println(toString(tempMaze)); System.out.println(toString(tempMaze));
} }
public String toString(int[][] maze) { public String toString(int[][] maze) {
StringBuilder result = new StringBuilder(getWidth() * (getHeight() + 1)); StringBuilder result = new StringBuilder(getWidth() * (getHeight() + 1));
for (int row = 0; row < getHeight(); row++) { for (int row = 0; row < getHeight(); row++) {
for (int col = 0; col < getWidth(); col++) { for (int col = 0; col < getWidth(); col++) {
if (maze[row][col] == ROAD) { if (maze[row][col] == ROAD) {
result.append(' '); result.append(' ');
} else if (maze[row][col] == WALL) { } else if (maze[row][col] == WALL) {
result.append('#'); result.append('#');
} else if (maze[row][col] == START) { } else if (maze[row][col] == START) {
result.append('S'); result.append('S');
} else if (maze[row][col] == EXIT) { } else if (maze[row][col] == EXIT) {
result.append('E'); result.append('E');
} else { } else {
result.append('.'); result.append('.');
} }
} }
result.append('\n'); result.append('\n');
} }
return result.toString(); return result.toString();
} }
public void reset() { public void reset() {
for (int i = 0; i < visited.length; i++) for (int i = 0; i < visited.length; i++)
Arrays.fill(visited[i], false); Arrays.fill(visited[i], false);
} }
} }

View File

@ -1,34 +1,34 @@
package com.baeldung.algorithms.maze.solver; package com.baeldung.algorithms.maze.solver;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
public class MazeDriver { public class MazeDriver {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
File maze1 = new File("src/main/resources/maze/maze1.txt"); File maze1 = new File("src/main/resources/maze/maze1.txt");
File maze2 = new File("src/main/resources/maze/maze2.txt"); File maze2 = new File("src/main/resources/maze/maze2.txt");
execute(maze1); execute(maze1);
execute(maze2); execute(maze2);
} }
private static void execute(File file) throws Exception { private static void execute(File file) throws Exception {
Maze maze = new Maze(file); Maze maze = new Maze(file);
dfs(maze); dfs(maze);
bfs(maze); bfs(maze);
} }
private static void bfs(Maze maze) { private static void bfs(Maze maze) {
BFSMazeSolver bfs = new BFSMazeSolver(); BFSMazeSolver bfs = new BFSMazeSolver();
List<Coordinate> path = bfs.solve(maze); List<Coordinate> path = bfs.solve(maze);
maze.printPath(path); maze.printPath(path);
maze.reset(); maze.reset();
} }
private static void dfs(Maze maze) { private static void dfs(Maze maze) {
DFSMazeSolver dfs = new DFSMazeSolver(); DFSMazeSolver dfs = new DFSMazeSolver();
List<Coordinate> path = dfs.solve(maze); List<Coordinate> path = dfs.solve(maze);
maze.printPath(path); maze.printPath(path);
maze.reset(); maze.reset();
} }
} }

Some files were not shown because too many files have changed in this diff Show More