Merge branch 'master' into master
This commit is contained in:
commit
e146c2af4e
20
.gitignore
vendored
20
.gitignore
vendored
@ -42,3 +42,23 @@ spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
|
|||||||
*.springBeans
|
*.springBeans
|
||||||
|
|
||||||
20171220-JMeter.csv
|
20171220-JMeter.csv
|
||||||
|
|
||||||
|
.factorypath
|
||||||
|
dependency-reduced-pom.xml
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
*.dll
|
||||||
|
|
||||||
|
xml/src/test/resources/example_dom4j_new.xml
|
||||||
|
xml/src/test/resources/example_dom4j_updated.xml
|
||||||
|
xml/src/test/resources/example_jaxb_new.xml
|
||||||
|
core-java-io/hard_link.txt
|
||||||
|
core-java-io/target_link.txt
|
||||||
|
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
|
||||||
|
ethereum/logs/
|
||||||
|
jmeter/src/main/resources/*-JMeter.csv
|
||||||
|
|
||||||
|
**/node_modules/
|
||||||
|
**/dist
|
||||||
|
**/tmp
|
||||||
|
**/out-tsc
|
||||||
|
3
.gitmodules
vendored
3
.gitmodules
vendored
@ -1,3 +0,0 @@
|
|||||||
[submodule "testgitrepo"]
|
|
||||||
path = testgitrepo
|
|
||||||
url = /home/prd/Development/projects/idea/tutorials/spring-boot/src/main/resources/testgitrepo/
|
|
@ -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
|
script: travis_wait 60 mvn -q install -Pdefault
|
||||||
|
|
||||||
sudo: required
|
sudo: required
|
||||||
|
|
||||||
|
@ -1,11 +1,13 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<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">
|
<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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>JGitSnippets</artifactId>
|
<artifactId>JGit</artifactId>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<url>http://maven.apache.org</url>
|
<url>http://maven.apache.org</url>
|
||||||
|
<name>JGit</name>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
@ -45,7 +47,6 @@
|
|||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<org.eclipse.jgit.version>4.5.0.201609210915-r</org.eclipse.jgit.version>
|
<org.eclipse.jgit.version>4.5.0.201609210915-r</org.eclipse.jgit.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
13
JGit/src/main/resources/logback.xml
Normal file
13
JGit/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -2,7 +2,7 @@
|
|||||||
The "REST with Spring" Classes
|
The "REST with Spring" Classes
|
||||||
==============================
|
==============================
|
||||||
|
|
||||||
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
Here's the Master Class of REST With Spring (price changes permanently next Friday): <br/>
|
||||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||||
|
|
||||||
And here's the Master Class of Learn Spring Security: <br/>
|
And here's the Master Class of Learn Spring Security: <br/>
|
||||||
@ -19,7 +19,7 @@ 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 -Dgib.enabled=false`
|
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
||||||
|
|
||||||
|
|
||||||
Working with the code in Eclipse
|
Working with the code in Eclipse
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
<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/maven-v4_0_0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
<groupId>com.mabsisa</groupId>
|
<groupId>com.mabsisa</groupId>
|
||||||
<artifactId>Twitter4J</artifactId>
|
<artifactId>Twitter4J</artifactId>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
@ -14,17 +15,11 @@
|
|||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.twitter4j</groupId>
|
<groupId>org.twitter4j</groupId>
|
||||||
<artifactId>twitter4j-stream</artifactId>
|
<artifactId>twitter4j-stream</artifactId>
|
||||||
<version>4.0.6</version>
|
<version>${twitter4j-stream.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
@ -49,4 +44,8 @@
|
|||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<twitter4j-stream.version>4.0.6</twitter4j-stream.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
13
Twitter4J/src/main/resources/logback.xml
Normal file
13
Twitter4J/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -1,5 +1,5 @@
|
|||||||
<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>activejdbc</artifactId>
|
<artifactId>activejdbc</artifactId>
|
||||||
@ -15,12 +15,6 @@
|
|||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
|
||||||
<groupId>junit</groupId>
|
|
||||||
<artifactId>junit</artifactId>
|
|
||||||
<version>${junit.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.javalite</groupId>
|
<groupId>org.javalite</groupId>
|
||||||
<artifactId>activejdbc</artifactId>
|
<artifactId>activejdbc</artifactId>
|
||||||
@ -133,10 +127,8 @@
|
|||||||
</pluginRepositories>
|
</pluginRepositories>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<activejdbc.version>1.4.13</activejdbc.version>
|
<activejdbc.version>1.4.13</activejdbc.version>
|
||||||
<environments>development.test,development</environments>
|
<environments>development.test,development</environments>
|
||||||
<org.slf4j.version>1.7.9</org.slf4j.version>
|
|
||||||
<mysql.connector.version>5.1.34</mysql.connector.version>
|
<mysql.connector.version>5.1.34</mysql.connector.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
13
activejdbc/src/main/resources/logback.xml
Normal file
13
activejdbc/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<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>
|
||||||
<artifactId>akka-streams</artifactId>
|
<artifactId>akka-streams</artifactId>
|
||||||
<name>akka-streams</name>
|
<name>akka-streams</name>
|
||||||
|
13
akka-streams/src/main/resources/logback.xml
Normal file
13
akka-streams/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -5,7 +5,6 @@
|
|||||||
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
|
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
|
||||||
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/java-finite-automata)
|
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/java-finite-automata)
|
||||||
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
|
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
|
||||||
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)
|
|
||||||
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
|
- [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)
|
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)
|
||||||
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
|
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
|
||||||
@ -21,4 +20,7 @@
|
|||||||
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
|
- [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)
|
- [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)
|
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||||
- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum)
|
- [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)
|
||||||
|
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
|
||||||
|
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
<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</artifactId>
|
||||||
@ -79,7 +79,6 @@
|
|||||||
</reporting>
|
</reporting>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
|
|
||||||
<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>
|
||||||
|
@ -6,7 +6,6 @@ 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;
|
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||||
import com.baeldung.algorithms.pairsaddupnumber.FindPairs;
|
|
||||||
|
|
||||||
public class RunAlgorithm {
|
public class RunAlgorithm {
|
||||||
|
|
||||||
@ -39,12 +38,6 @@ public class RunAlgorithm {
|
|||||||
case 5:
|
case 5:
|
||||||
System.out.println("Please run the DijkstraAlgorithmTest.");
|
System.out.println("Please run the DijkstraAlgorithmTest.");
|
||||||
break;
|
break;
|
||||||
case 6:
|
|
||||||
final FindPairs findPairs = new FindPairs();
|
|
||||||
final int[] input = {1, 4, 3, 2, 1, 4, 4, 3, 3};
|
|
||||||
final int sum = 6;
|
|
||||||
findPairs.execute(input, sum);
|
|
||||||
break;
|
|
||||||
default:
|
default:
|
||||||
System.out.println("Unknown option");
|
System.out.println("Unknown option");
|
||||||
break;
|
break;
|
||||||
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.algorithms.distancebetweenpoints;
|
||||||
|
|
||||||
|
import java.awt.geom.Point2D;
|
||||||
|
|
||||||
|
public class DistanceBetweenPointsService {
|
||||||
|
|
||||||
|
public double calculateDistanceBetweenPoints(
|
||||||
|
double x1,
|
||||||
|
double y1,
|
||||||
|
double x2,
|
||||||
|
double y2) {
|
||||||
|
|
||||||
|
return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1));
|
||||||
|
}
|
||||||
|
|
||||||
|
public double calculateDistanceBetweenPointsWithHypot(
|
||||||
|
double x1,
|
||||||
|
double y1,
|
||||||
|
double x2,
|
||||||
|
double y2) {
|
||||||
|
|
||||||
|
double ac = Math.abs(y2 - y1);
|
||||||
|
double cb = Math.abs(x2 - x1);
|
||||||
|
|
||||||
|
return Math.hypot(ac, cb);
|
||||||
|
}
|
||||||
|
|
||||||
|
public double calculateDistanceBetweenPointsWithPoint2D(
|
||||||
|
double x1,
|
||||||
|
double y1,
|
||||||
|
double x2,
|
||||||
|
double y2) {
|
||||||
|
|
||||||
|
return Point2D.distance(x1, y1, x2, y2);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.algorithms.linesintersection;
|
||||||
|
|
||||||
|
import java.awt.Point;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public class LinesIntersectionService {
|
||||||
|
|
||||||
|
public Optional<Point> calculateIntersectionPoint(double m1, double b1, double m2, double b2) {
|
||||||
|
|
||||||
|
if (m1 == m2) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
double x = (b2 - b1) / (m1 - m2);
|
||||||
|
double y = m1 * x + b1;
|
||||||
|
|
||||||
|
Point point = new Point();
|
||||||
|
point.setLocation(x, y);
|
||||||
|
return Optional.of(point);
|
||||||
|
}
|
||||||
|
}
|
@ -10,7 +10,7 @@ public class MonteCarloTreeSearch {
|
|||||||
|
|
||||||
private static final int WIN_SCORE = 10;
|
private static final int WIN_SCORE = 10;
|
||||||
private int level;
|
private int level;
|
||||||
private int oponent;
|
private int opponent;
|
||||||
|
|
||||||
public MonteCarloTreeSearch() {
|
public MonteCarloTreeSearch() {
|
||||||
this.level = 3;
|
this.level = 3;
|
||||||
@ -32,11 +32,11 @@ public class MonteCarloTreeSearch {
|
|||||||
long start = System.currentTimeMillis();
|
long start = System.currentTimeMillis();
|
||||||
long end = start + 60 * getMillisForCurrentLevel();
|
long end = start + 60 * getMillisForCurrentLevel();
|
||||||
|
|
||||||
oponent = 3 - playerNo;
|
opponent = 3 - playerNo;
|
||||||
Tree tree = new Tree();
|
Tree tree = new Tree();
|
||||||
Node rootNode = tree.getRoot();
|
Node rootNode = tree.getRoot();
|
||||||
rootNode.getState().setBoard(board);
|
rootNode.getState().setBoard(board);
|
||||||
rootNode.getState().setPlayerNo(oponent);
|
rootNode.getState().setPlayerNo(opponent);
|
||||||
|
|
||||||
while (System.currentTimeMillis() < end) {
|
while (System.currentTimeMillis() < end) {
|
||||||
// Phase 1 - Selection
|
// Phase 1 - Selection
|
||||||
@ -93,7 +93,7 @@ public class MonteCarloTreeSearch {
|
|||||||
State tempState = tempNode.getState();
|
State tempState = tempNode.getState();
|
||||||
int boardStatus = tempState.getBoard().checkStatus();
|
int boardStatus = tempState.getBoard().checkStatus();
|
||||||
|
|
||||||
if (boardStatus == oponent) {
|
if (boardStatus == opponent) {
|
||||||
tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE);
|
tempNode.getParent().getState().setWinScore(Integer.MIN_VALUE);
|
||||||
return boardStatus;
|
return boardStatus;
|
||||||
}
|
}
|
||||||
|
@ -87,7 +87,7 @@ public class State {
|
|||||||
void randomPlay() {
|
void randomPlay() {
|
||||||
List<Position> availablePositions = this.board.getEmptyPositions();
|
List<Position> availablePositions = this.board.getEmptyPositions();
|
||||||
int totalPossibilities = availablePositions.size();
|
int totalPossibilities = availablePositions.size();
|
||||||
int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1));
|
int selectRandom = (int) (Math.random() * totalPossibilities);
|
||||||
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
|
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -148,7 +148,7 @@ public class Board {
|
|||||||
System.out.println("Game Draw");
|
System.out.println("Game Draw");
|
||||||
break;
|
break;
|
||||||
case IN_PROGRESS:
|
case IN_PROGRESS:
|
||||||
System.out.println("Game In rogress");
|
System.out.println("Game In Progress");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -65,7 +65,7 @@ public class Node {
|
|||||||
|
|
||||||
public Node getRandomChildNode() {
|
public Node getRandomChildNode() {
|
||||||
int noOfPossibleMoves = this.childArray.size();
|
int noOfPossibleMoves = this.childArray.size();
|
||||||
int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1));
|
int selectRandom = (int) (Math.random() * noOfPossibleMoves);
|
||||||
return this.childArray.get(selectRandom);
|
return this.childArray.get(selectRandom);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -0,0 +1,88 @@
|
|||||||
|
package com.baeldung.algorithms.middleelementlookup;
|
||||||
|
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public class MiddleElementLookup {
|
||||||
|
|
||||||
|
public static Optional<String> findMiddleElementLinkedList(LinkedList<String> linkedList) {
|
||||||
|
if (linkedList == null || linkedList.isEmpty()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Optional.ofNullable(linkedList.get((linkedList.size() - 1) / 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Optional<String> findMiddleElementFromHead(Node head) {
|
||||||
|
if (head == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
// calculate the size of the list
|
||||||
|
Node current = head;
|
||||||
|
int size = 1;
|
||||||
|
while (current.hasNext()) {
|
||||||
|
current = current.next();
|
||||||
|
size++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// iterate till the middle element
|
||||||
|
current = head;
|
||||||
|
for (int i = 0; i < (size - 1) / 2; i++) {
|
||||||
|
current = current.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Optional.ofNullable(current.data());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Optional<String> findMiddleElementFromHead1PassRecursively(Node head) {
|
||||||
|
if (head == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
MiddleAuxRecursion middleAux = new MiddleAuxRecursion();
|
||||||
|
findMiddleRecursively(head, middleAux);
|
||||||
|
return Optional.ofNullable(middleAux.middle.data());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) {
|
||||||
|
if (node == null) {
|
||||||
|
// reached the end
|
||||||
|
middleAux.length = middleAux.length / 2;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
middleAux.length++;
|
||||||
|
findMiddleRecursively(node.next(), middleAux);
|
||||||
|
|
||||||
|
if (middleAux.length == 0) {
|
||||||
|
// found the middle
|
||||||
|
middleAux.middle = node;
|
||||||
|
}
|
||||||
|
|
||||||
|
middleAux.length--;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Optional<String> findMiddleElementFromHead1PassIteratively(Node head) {
|
||||||
|
if (head == null) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
Node slowPointer = head;
|
||||||
|
Node fastPointer = head;
|
||||||
|
|
||||||
|
while (fastPointer.hasNext() && fastPointer.next()
|
||||||
|
.hasNext()) {
|
||||||
|
fastPointer = fastPointer.next()
|
||||||
|
.next();
|
||||||
|
slowPointer = slowPointer.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Optional.ofNullable(slowPointer.data());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class MiddleAuxRecursion {
|
||||||
|
Node middle;
|
||||||
|
int length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.algorithms.middleelementlookup;
|
||||||
|
|
||||||
|
public class Node {
|
||||||
|
private Node next;
|
||||||
|
private String data;
|
||||||
|
|
||||||
|
public Node(String data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String data() {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setData(String data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasNext() {
|
||||||
|
return next != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Node next() {
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setNext(Node next) {
|
||||||
|
this.next = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String toString() {
|
||||||
|
return this.data;
|
||||||
|
}
|
||||||
|
}
|
@ -1,59 +0,0 @@
|
|||||||
package com.baeldung.algorithms.prime;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.LinkedList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
import java.util.stream.IntStream;
|
|
||||||
|
|
||||||
public class PrimeGenerator {
|
|
||||||
public static List<Integer> sieveOfEratosthenes(int n) {
|
|
||||||
final boolean prime[] = new boolean[n + 1];
|
|
||||||
Arrays.fill(prime, true);
|
|
||||||
|
|
||||||
for (int p = 2; p * p <= n; p++) {
|
|
||||||
if (prime[p]) {
|
|
||||||
for (int i = p * 2; i <= n; i += p)
|
|
||||||
prime[i] = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
final List<Integer> primes = new LinkedList<>();
|
|
||||||
for (int i = 2; i <= n; i++) {
|
|
||||||
if (prime[i])
|
|
||||||
primes.add(i);
|
|
||||||
}
|
|
||||||
return primes;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static List<Integer> primeNumbersBruteForce(int max) {
|
|
||||||
final List<Integer> primeNumbers = new LinkedList<Integer>();
|
|
||||||
for (int i = 2; i <= max; i++) {
|
|
||||||
if (isPrimeBruteForce(i)) {
|
|
||||||
primeNumbers.add(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return primeNumbers;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean isPrimeBruteForce(int x) {
|
|
||||||
for (int i = 2; i < x; i++) {
|
|
||||||
if (x % i == 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static List<Integer> primeNumbersTill(int max) {
|
|
||||||
return IntStream.rangeClosed(2, max)
|
|
||||||
.filter(x -> isPrime(x))
|
|
||||||
.boxed()
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean isPrime(int x) {
|
|
||||||
return IntStream.rangeClosed(2, (int) (Math.sqrt(x)))
|
|
||||||
.allMatch(n -> x % n != 0);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.algorithms.rectanglesoverlap;
|
||||||
|
|
||||||
|
public class Point {
|
||||||
|
|
||||||
|
private int x;
|
||||||
|
private int y;
|
||||||
|
|
||||||
|
public Point(int x, int y) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getX() {
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setX(int x) {
|
||||||
|
this.x = x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getY() {
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setY(int y) {
|
||||||
|
this.y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
package com.baeldung.algorithms.rectanglesoverlap;
|
||||||
|
|
||||||
|
public class Rectangle {
|
||||||
|
|
||||||
|
private Point bottomLeft;
|
||||||
|
private Point topRight;
|
||||||
|
|
||||||
|
public Rectangle(Point bottomLeft, Point topRight) {
|
||||||
|
this.bottomLeft = bottomLeft;
|
||||||
|
this.topRight = topRight;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Point getBottomLeft() {
|
||||||
|
return bottomLeft;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBottomLeft(Point bottomLeft) {
|
||||||
|
this.bottomLeft = bottomLeft;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Point getTopRight() {
|
||||||
|
return topRight;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTopRight(Point topRight) {
|
||||||
|
this.topRight = topRight;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isOverlapping(Rectangle other) {
|
||||||
|
// one rectangle is to the top of the other
|
||||||
|
if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// one rectangle is to the left of the other
|
||||||
|
if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,52 @@
|
|||||||
|
package com.baeldung.algorithms.romannumerals;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
class RomanArabicConverter {
|
||||||
|
|
||||||
|
public static int romanToArabic(String input) {
|
||||||
|
String romanNumeral = input.toUpperCase();
|
||||||
|
int result = 0;
|
||||||
|
|
||||||
|
List<RomanNumeral> romanNumerals = RomanNumeral.getReverseSortedValues();
|
||||||
|
|
||||||
|
int i = 0;
|
||||||
|
|
||||||
|
while ((romanNumeral.length() > 0) && (i < romanNumerals.size())) {
|
||||||
|
RomanNumeral symbol = romanNumerals.get(i);
|
||||||
|
if (romanNumeral.startsWith(symbol.name())) {
|
||||||
|
result += symbol.getValue();
|
||||||
|
romanNumeral = romanNumeral.substring(symbol.name().length());
|
||||||
|
} else {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (romanNumeral.length() > 0) {
|
||||||
|
throw new IllegalArgumentException(input + " cannot be converted to a Roman Numeral");
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String arabicToRoman(int number) {
|
||||||
|
if ((number <= 0) || (number > 4000)) {
|
||||||
|
throw new IllegalArgumentException(number + " is not in range (0,4000]");
|
||||||
|
}
|
||||||
|
|
||||||
|
List<RomanNumeral> romanNumerals = RomanNumeral.getReverseSortedValues();
|
||||||
|
|
||||||
|
int i = 0;
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
|
||||||
|
while (number > 0 && i < romanNumerals.size()) {
|
||||||
|
RomanNumeral currentSymbol = romanNumerals.get(i);
|
||||||
|
if (currentSymbol.getValue() <= number) {
|
||||||
|
sb.append(currentSymbol.name());
|
||||||
|
number -= currentSymbol.getValue();
|
||||||
|
} else {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.algorithms.romannumerals;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
enum RomanNumeral {
|
||||||
|
I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
|
||||||
|
|
||||||
|
private int value;
|
||||||
|
|
||||||
|
RomanNumeral(int value) {
|
||||||
|
this.value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getValue() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<RomanNumeral> getReverseSortedValues() {
|
||||||
|
return Arrays.stream(values())
|
||||||
|
.sorted(Comparator.comparing((RomanNumeral e) -> e.value).reversed())
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.algorithms.string;
|
||||||
|
|
||||||
|
public class EnglishAlphabetLetters {
|
||||||
|
|
||||||
|
public static boolean checkStringForAllTheLetters(String input) {
|
||||||
|
boolean[] visited = new boolean[26];
|
||||||
|
|
||||||
|
int index = 0;
|
||||||
|
|
||||||
|
for (int id = 0; id < input.length(); id++) {
|
||||||
|
if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
|
||||||
|
index = input.charAt(id) - 'a';
|
||||||
|
} else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
|
||||||
|
index = input.charAt(id) - 'A';
|
||||||
|
}
|
||||||
|
visited[index] = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int id = 0; id < 26; id++) {
|
||||||
|
if (!visited[id]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean checkStringForAllLetterUsingStream(String input) {
|
||||||
|
long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count();
|
||||||
|
return c == 26;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
checkStringForAllLetterUsingStream("intit");
|
||||||
|
}
|
||||||
|
}
|
13
algorithms/src/main/resources/logback.xml
Normal file
13
algorithms/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -1,58 +0,0 @@
|
|||||||
package algorithms;
|
|
||||||
|
|
||||||
import com.baeldung.algorithms.hillclimbing.HillClimbing;
|
|
||||||
import com.baeldung.algorithms.hillclimbing.State;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Stack;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertNotNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
public class HillClimbingAlgorithmTest {
|
|
||||||
private Stack<String> initStack;
|
|
||||||
private Stack<String> goalStack;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void initStacks() {
|
|
||||||
String blockArr[] = { "B", "C", "D", "A" };
|
|
||||||
String goalBlockArr[] = { "A", "B", "C", "D" };
|
|
||||||
initStack = new Stack<>();
|
|
||||||
for (String block : blockArr)
|
|
||||||
initStack.push(block);
|
|
||||||
goalStack = new Stack<>();
|
|
||||||
for (String block : goalBlockArr)
|
|
||||||
goalStack.push(block);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
|
|
||||||
HillClimbing hillClimbing = new HillClimbing();
|
|
||||||
|
|
||||||
List<State> path;
|
|
||||||
try {
|
|
||||||
path = hillClimbing.getRouteWithHillClimbing(initStack, goalStack);
|
|
||||||
assertNotNull(path);
|
|
||||||
assertEquals(path.get(path.size() - 1)
|
|
||||||
.getState()
|
|
||||||
.get(0), goalStack);
|
|
||||||
} catch (Exception e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
|
|
||||||
HillClimbing hillClimbing = new HillClimbing();
|
|
||||||
List<Stack<String>> initList = new ArrayList<>();
|
|
||||||
initList.add(initStack);
|
|
||||||
State currentState = new State(initList);
|
|
||||||
currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack));
|
|
||||||
State nextState = hillClimbing.findNextState(currentState, goalStack);
|
|
||||||
assertTrue(nextState.getHeuristics() > currentState.getHeuristics());
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,25 +0,0 @@
|
|||||||
package algorithms;
|
|
||||||
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import com.baeldung.algorithms.string.search.StringSearchAlgorithms;
|
|
||||||
|
|
||||||
public class StringSearchAlgorithmsTest {
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testStringSearchAlgorithms(){
|
|
||||||
String text = "This is some nice text.";
|
|
||||||
String pattern = "some";
|
|
||||||
|
|
||||||
int realPosition = text.indexOf(pattern);
|
|
||||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()));
|
|
||||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()));
|
|
||||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()));
|
|
||||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()));
|
|
||||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,43 +0,0 @@
|
|||||||
package algorithms.binarysearch;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
import com.baeldung.algorithms.binarysearch.BinarySearch;
|
|
||||||
|
|
||||||
public class BinarySearchTest {
|
|
||||||
|
|
||||||
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
|
||||||
int key = 6;
|
|
||||||
int expectedIndexForSearchKey = 7;
|
|
||||||
int low = 0;
|
|
||||||
int high = sortedArray.length - 1;
|
|
||||||
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
|
|
||||||
BinarySearch binSearch = new BinarySearch();
|
|
||||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
|
|
||||||
BinarySearch binSearch = new BinarySearch();
|
|
||||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
|
||||||
BinarySearch binSearch = new BinarySearch();
|
|
||||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
|
||||||
BinarySearch binSearch = new BinarySearch();
|
|
||||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,92 +0,0 @@
|
|||||||
package algorithms.mcts;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
|
|
||||||
import com.baeldung.algorithms.mcts.montecarlo.State;
|
|
||||||
import com.baeldung.algorithms.mcts.montecarlo.UCT;
|
|
||||||
import com.baeldung.algorithms.mcts.tictactoe.Board;
|
|
||||||
import com.baeldung.algorithms.mcts.tictactoe.Position;
|
|
||||||
import com.baeldung.algorithms.mcts.tree.Tree;
|
|
||||||
|
|
||||||
public class MCTSTest {
|
|
||||||
private Tree gameTree;
|
|
||||||
private MonteCarloTreeSearch mcts;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void initGameTree() {
|
|
||||||
gameTree = new Tree();
|
|
||||||
mcts = new MonteCarloTreeSearch();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
|
|
||||||
double uctValue = 15.79;
|
|
||||||
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
|
|
||||||
State initState = gameTree.getRoot().getState();
|
|
||||||
List<State> possibleStates = initState.getAllPossibleStates();
|
|
||||||
assertTrue(possibleStates.size() > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
|
|
||||||
Board board = new Board();
|
|
||||||
int initAvailablePositions = board.getEmptyPositions().size();
|
|
||||||
board.performMove(Board.P1, new Position(1, 1));
|
|
||||||
int availablePositions = board.getEmptyPositions().size();
|
|
||||||
assertTrue(initAvailablePositions > availablePositions);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
|
|
||||||
Board board = new Board();
|
|
||||||
|
|
||||||
int player = Board.P1;
|
|
||||||
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
|
|
||||||
for (int i = 0; i < totalMoves; i++) {
|
|
||||||
board = mcts.findNextMove(board, player);
|
|
||||||
if (board.checkStatus() != -1) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
player = 3 - player;
|
|
||||||
}
|
|
||||||
int winStatus = board.checkStatus();
|
|
||||||
assertEquals(winStatus, Board.DRAW);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
|
|
||||||
Board board = new Board();
|
|
||||||
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
|
|
||||||
mcts1.setLevel(1);
|
|
||||||
MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
|
|
||||||
mcts3.setLevel(3);
|
|
||||||
|
|
||||||
int player = Board.P1;
|
|
||||||
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
|
|
||||||
for (int i = 0; i < totalMoves; i++) {
|
|
||||||
if (player == Board.P1)
|
|
||||||
board = mcts3.findNextMove(board, player);
|
|
||||||
else
|
|
||||||
board = mcts1.findNextMove(board, player);
|
|
||||||
|
|
||||||
if (board.checkStatus() != -1) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
player = 3 - player;
|
|
||||||
}
|
|
||||||
int winStatus = board.checkStatus();
|
|
||||||
assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,36 +0,0 @@
|
|||||||
package algorithms.minimax;
|
|
||||||
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
import com.baeldung.algorithms.minimax.MiniMax;
|
|
||||||
import com.baeldung.algorithms.minimax.Tree;
|
|
||||||
|
|
||||||
public class MinimaxTest {
|
|
||||||
private Tree gameTree;
|
|
||||||
private MiniMax miniMax;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void initMiniMaxUtility() {
|
|
||||||
miniMax = new MiniMax();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenMiniMax_whenConstructTree_thenNotNullTree() {
|
|
||||||
assertNull(gameTree);
|
|
||||||
miniMax.constructTree(6);
|
|
||||||
gameTree = miniMax.getTree();
|
|
||||||
assertNotNull(gameTree);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenMiniMax_whenCheckWin_thenComputeOptimal() {
|
|
||||||
miniMax.constructTree(6);
|
|
||||||
boolean result = miniMax.checkWin();
|
|
||||||
assertTrue(result);
|
|
||||||
miniMax.constructTree(8);
|
|
||||||
result = miniMax.checkWin();
|
|
||||||
assertFalse(result);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,4 +1,4 @@
|
|||||||
package algorithms;
|
package com.baeldung.algorithms;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
@ -1,4 +1,4 @@
|
|||||||
package algorithms;
|
package com.baeldung.algorithms;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
@ -1,4 +1,4 @@
|
|||||||
package algorithms;
|
package com.baeldung.algorithms;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
@ -0,0 +1,58 @@
|
|||||||
|
package com.baeldung.algorithms;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.hillclimbing.HillClimbing;
|
||||||
|
import com.baeldung.algorithms.hillclimbing.State;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Stack;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class HillClimbingAlgorithmUnitTest {
|
||||||
|
private Stack<String> initStack;
|
||||||
|
private Stack<String> goalStack;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void initStacks() {
|
||||||
|
String blockArr[] = { "B", "C", "D", "A" };
|
||||||
|
String goalBlockArr[] = { "A", "B", "C", "D" };
|
||||||
|
initStack = new Stack<>();
|
||||||
|
for (String block : blockArr)
|
||||||
|
initStack.push(block);
|
||||||
|
goalStack = new Stack<>();
|
||||||
|
for (String block : goalBlockArr)
|
||||||
|
goalStack.push(block);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() {
|
||||||
|
HillClimbing hillClimbing = new HillClimbing();
|
||||||
|
|
||||||
|
List<State> path;
|
||||||
|
try {
|
||||||
|
path = hillClimbing.getRouteWithHillClimbing(initStack, goalStack);
|
||||||
|
assertNotNull(path);
|
||||||
|
assertEquals(path.get(path.size() - 1)
|
||||||
|
.getState()
|
||||||
|
.get(0), goalStack);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
|
||||||
|
HillClimbing hillClimbing = new HillClimbing();
|
||||||
|
List<Stack<String>> initList = new ArrayList<>();
|
||||||
|
initList.add(initStack);
|
||||||
|
State currentState = new State(initList);
|
||||||
|
currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack));
|
||||||
|
State nextState = hillClimbing.findNextState(currentState, goalStack);
|
||||||
|
assertTrue(nextState.getHeuristics() > currentState.getHeuristics());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,118 @@
|
|||||||
|
package com.baeldung.algorithms;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
|
||||||
|
import com.baeldung.algorithms.middleelementlookup.Node;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.LinkedList;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
|
||||||
|
public class MiddleElementLookupUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindingMiddleLinkedList_thenMiddleFound() {
|
||||||
|
assertEquals("3", MiddleElementLookup
|
||||||
|
.findMiddleElementLinkedList(createLinkedList(5))
|
||||||
|
.get());
|
||||||
|
assertEquals("2", MiddleElementLookup
|
||||||
|
.findMiddleElementLinkedList(createLinkedList(4))
|
||||||
|
.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindingMiddleFromHead_thenMiddleFound() {
|
||||||
|
assertEquals("3", MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead(createNodesList(5))
|
||||||
|
.get());
|
||||||
|
assertEquals("2", MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead(createNodesList(4))
|
||||||
|
.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() {
|
||||||
|
assertEquals("3", MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead1PassRecursively(createNodesList(5))
|
||||||
|
.get());
|
||||||
|
assertEquals("2", MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead1PassRecursively(createNodesList(4))
|
||||||
|
.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() {
|
||||||
|
assertEquals("3", MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead1PassIteratively(createNodesList(5))
|
||||||
|
.get());
|
||||||
|
assertEquals("2", MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead1PassIteratively(createNodesList(4))
|
||||||
|
.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenListEmptyOrNull_thenMiddleNotFound() {
|
||||||
|
// null list
|
||||||
|
assertFalse(MiddleElementLookup
|
||||||
|
.findMiddleElementLinkedList(null)
|
||||||
|
.isPresent());
|
||||||
|
assertFalse(MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead(null)
|
||||||
|
.isPresent());
|
||||||
|
assertFalse(MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead1PassIteratively(null)
|
||||||
|
.isPresent());
|
||||||
|
assertFalse(MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead1PassRecursively(null)
|
||||||
|
.isPresent());
|
||||||
|
|
||||||
|
// empty LinkedList
|
||||||
|
assertFalse(MiddleElementLookup
|
||||||
|
.findMiddleElementLinkedList(new LinkedList<>())
|
||||||
|
.isPresent());
|
||||||
|
|
||||||
|
// LinkedList with nulls
|
||||||
|
LinkedList<String> nullsList = new LinkedList<>();
|
||||||
|
nullsList.add(null);
|
||||||
|
nullsList.add(null);
|
||||||
|
assertFalse(MiddleElementLookup
|
||||||
|
.findMiddleElementLinkedList(nullsList)
|
||||||
|
.isPresent());
|
||||||
|
|
||||||
|
// nodes with null values
|
||||||
|
assertFalse(MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead(new Node(null))
|
||||||
|
.isPresent());
|
||||||
|
assertFalse(MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead1PassIteratively(new Node(null))
|
||||||
|
.isPresent());
|
||||||
|
assertFalse(MiddleElementLookup
|
||||||
|
.findMiddleElementFromHead1PassRecursively(new Node(null))
|
||||||
|
.isPresent());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LinkedList<String> createLinkedList(int n) {
|
||||||
|
LinkedList<String> list = new LinkedList<>();
|
||||||
|
|
||||||
|
for (int i = 1; i <= n; i++) {
|
||||||
|
list.add(String.valueOf(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Node createNodesList(int n) {
|
||||||
|
Node head = new Node("1");
|
||||||
|
Node current = head;
|
||||||
|
|
||||||
|
for (int i = 2; i <= n; i++) {
|
||||||
|
Node newNode = new Node(String.valueOf(i));
|
||||||
|
current.setNext(newNode);
|
||||||
|
current = newNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
package algorithms;
|
package com.baeldung.algorithms;
|
||||||
|
|
||||||
import com.baeldung.algorithms.automata.*;
|
import com.baeldung.algorithms.automata.*;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
@ -1,4 +1,4 @@
|
|||||||
package algorithms;
|
package com.baeldung.algorithms;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.algorithms;
|
||||||
|
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.string.search.StringSearchAlgorithms;
|
||||||
|
|
||||||
|
public class StringSearchAlgorithmsUnitTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testStringSearchAlgorithms(){
|
||||||
|
String text = "This is some nice text.";
|
||||||
|
String pattern = "some";
|
||||||
|
|
||||||
|
int realPosition = text.indexOf(pattern);
|
||||||
|
Assert.assertTrue(realPosition == StringSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()));
|
||||||
|
Assert.assertTrue(realPosition == StringSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()));
|
||||||
|
Assert.assertTrue(realPosition == StringSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()));
|
||||||
|
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()));
|
||||||
|
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,139 @@
|
|||||||
|
package com.baeldung.algorithms.analysis;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class AnalysisRunnerLiveTest {
|
||||||
|
|
||||||
|
int n = 10;
|
||||||
|
int total = 0;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenConstantComplexity_thenConstantRuntime() {
|
||||||
|
|
||||||
|
System.out.println("**** n = " + n + " ****");
|
||||||
|
System.out.println();
|
||||||
|
|
||||||
|
// Constant Time
|
||||||
|
System.out.println("**** Constant time ****");
|
||||||
|
|
||||||
|
System.out.println("Hey - your input is: " + n);
|
||||||
|
System.out.println("Running time not dependent on input size!");
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLogarithmicComplexity_thenLogarithmicRuntime() {
|
||||||
|
// Logarithmic Time
|
||||||
|
System.out.println("**** Logarithmic Time ****");
|
||||||
|
for (int i = 1; i < n; i = i * 2) {
|
||||||
|
// System.out.println("Hey - I'm busy looking at: " + i);
|
||||||
|
total++;
|
||||||
|
}
|
||||||
|
System.out.println("Total amount of times run: " + total);
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLinearComplexity_thenLinearRuntime() {
|
||||||
|
// Linear Time
|
||||||
|
System.out.println("**** Linear Time ****");
|
||||||
|
for (int i = 0; i < n; i++) {
|
||||||
|
// System.out.println("Hey - I'm busy looking at: " + i);
|
||||||
|
total++;
|
||||||
|
}
|
||||||
|
System.out.println("Total amount of times run: " + total);
|
||||||
|
System.out.println();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNLogNComplexity_thenNLogNRuntime() {
|
||||||
|
// N Log N Time
|
||||||
|
System.out.println("**** nlogn Time ****");
|
||||||
|
total = 0;
|
||||||
|
for (
|
||||||
|
|
||||||
|
int i = 1; i <= n; i++) {
|
||||||
|
for (int j = 1; j < n; j = j * 2) {
|
||||||
|
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
|
||||||
|
total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
System.out.println("Total amount of times run: " + total);
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenQuadraticComplexity_thenQuadraticRuntime() {
|
||||||
|
// Quadratic Time
|
||||||
|
System.out.println("**** Quadratic Time ****");
|
||||||
|
total = 0;
|
||||||
|
for (
|
||||||
|
|
||||||
|
int i = 1; i <= n; i++) {
|
||||||
|
for (int j = 1; j <= n; j++) {
|
||||||
|
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
|
||||||
|
total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
System.out.println("Total amount of times run: " + total);
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCubicComplexity_thenCubicRuntime() {
|
||||||
|
// Cubic Time
|
||||||
|
System.out.println("**** Cubic Time ****");
|
||||||
|
total = 0;
|
||||||
|
for (
|
||||||
|
|
||||||
|
int i = 1; i <= n; i++) {
|
||||||
|
for (int j = 1; j <= n; j++) {
|
||||||
|
for (int k = 1; k <= n; k++) {
|
||||||
|
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j + " and " + k);
|
||||||
|
total++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
System.out.println("Total amount of times run: " + total);
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenExponentialComplexity_thenExponentialRuntime() {
|
||||||
|
// Exponential Time
|
||||||
|
System.out.println("**** Exponential Time ****");
|
||||||
|
total = 0;
|
||||||
|
for (
|
||||||
|
|
||||||
|
int i = 1; i <= Math.pow(2, n); i++) {
|
||||||
|
// System.out.println("Hey - I'm busy looking at: " + i);
|
||||||
|
total++;
|
||||||
|
}
|
||||||
|
System.out.println("Total amount of times run: " + total);
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFactorialComplexity_thenFactorialRuntime() {
|
||||||
|
// Factorial Time
|
||||||
|
System.out.println("**** Factorial Time ****");
|
||||||
|
total = 0;
|
||||||
|
for (
|
||||||
|
|
||||||
|
int i = 1; i <=
|
||||||
|
|
||||||
|
factorial(n); i++) {
|
||||||
|
// System.out.println("Hey - I'm busy looking at: " + i);
|
||||||
|
total++;
|
||||||
|
}
|
||||||
|
System.out.println("Total amount of times run: " + total);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int factorial(int n) {
|
||||||
|
if (n == 0 || n == 1)
|
||||||
|
return 1;
|
||||||
|
else
|
||||||
|
return n * factorial(n - 1);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.algorithms.binarysearch;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import com.baeldung.algorithms.binarysearch.BinarySearch;
|
||||||
|
|
||||||
|
public class BinarySearchUnitTest {
|
||||||
|
|
||||||
|
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
||||||
|
int key = 6;
|
||||||
|
int expectedIndexForSearchKey = 7;
|
||||||
|
int low = 0;
|
||||||
|
int high = sortedArray.length - 1;
|
||||||
|
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
|
||||||
|
BinarySearch binSearch = new BinarySearch();
|
||||||
|
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
|
||||||
|
BinarySearch binSearch = new BinarySearch();
|
||||||
|
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||||
|
BinarySearch binSearch = new BinarySearch();
|
||||||
|
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||||
|
BinarySearch binSearch = new BinarySearch();
|
||||||
|
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,26 +0,0 @@
|
|||||||
package com.baeldung.algorithms.bubblesort;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class BubbleSortTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() {
|
|
||||||
Integer[] array = { 2, 1, 4, 6, 3, 5 };
|
|
||||||
Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 };
|
|
||||||
BubbleSort bubbleSort = new BubbleSort();
|
|
||||||
bubbleSort.bubbleSort(array);
|
|
||||||
assertArrayEquals(array, sortedArray);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() {
|
|
||||||
Integer[] array = { 2, 1, 4, 6, 3, 5 };
|
|
||||||
Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 };
|
|
||||||
BubbleSort bubbleSort = new BubbleSort();
|
|
||||||
bubbleSort.optimizedBubbleSort(array);
|
|
||||||
assertArrayEquals(array, sortedArray);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,26 @@
|
|||||||
|
package com.baeldung.algorithms.bubblesort;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class BubbleSortUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() {
|
||||||
|
Integer[] array = { 2, 1, 4, 6, 3, 5 };
|
||||||
|
Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 };
|
||||||
|
BubbleSort bubbleSort = new BubbleSort();
|
||||||
|
bubbleSort.bubbleSort(array);
|
||||||
|
assertArrayEquals(array, sortedArray);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() {
|
||||||
|
Integer[] array = { 2, 1, 4, 6, 3, 5 };
|
||||||
|
Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 };
|
||||||
|
BubbleSort bubbleSort = new BubbleSort();
|
||||||
|
bubbleSort.optimizedBubbleSort(array);
|
||||||
|
assertArrayEquals(array, sortedArray);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,54 @@
|
|||||||
|
package com.baeldung.algorithms.distancebetweenpoints;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.distancebetweenpoints.DistanceBetweenPointsService;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class DistanceBetweenPointsServiceUnitTest {
|
||||||
|
|
||||||
|
private DistanceBetweenPointsService service = new DistanceBetweenPointsService();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoPoints_whenCalculateDistanceByFormula_thenCorrect() {
|
||||||
|
|
||||||
|
double x1 = 3;
|
||||||
|
double y1 = 4;
|
||||||
|
double x2 = 7;
|
||||||
|
double y2 = 1;
|
||||||
|
|
||||||
|
double distance = service.calculateDistanceBetweenPoints(x1, y1, x2, y2);
|
||||||
|
|
||||||
|
assertEquals(distance, 5, 0.001);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoPoints_whenCalculateDistanceWithHypot_thenCorrect() {
|
||||||
|
|
||||||
|
double x1 = 3;
|
||||||
|
double y1 = 4;
|
||||||
|
double x2 = 7;
|
||||||
|
double y2 = 1;
|
||||||
|
|
||||||
|
double distance = service.calculateDistanceBetweenPointsWithHypot(x1, y1, x2, y2);
|
||||||
|
|
||||||
|
assertEquals(distance, 5, 0.001);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoPoints_whenCalculateDistanceWithPoint2D_thenCorrect() {
|
||||||
|
|
||||||
|
double x1 = 3;
|
||||||
|
double y1 = 4;
|
||||||
|
double x2 = 7;
|
||||||
|
double y2 = 1;
|
||||||
|
|
||||||
|
double distance = service.calculateDistanceBetweenPointsWithPoint2D(x1, y1, x2, y2);
|
||||||
|
|
||||||
|
assertEquals(distance, 5, 0.001);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -1,32 +0,0 @@
|
|||||||
package com.baeldung.algorithms.editdistance;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.junit.runners.Parameterized;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
@RunWith(Parameterized.class)
|
|
||||||
public class EditDistanceTest extends EditDistanceDataProvider {
|
|
||||||
|
|
||||||
private String x;
|
|
||||||
private String y;
|
|
||||||
private int result;
|
|
||||||
|
|
||||||
public EditDistanceTest(String a, String b, int res) {
|
|
||||||
super();
|
|
||||||
x = a;
|
|
||||||
y = b;
|
|
||||||
result = res;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testEditDistance_RecursiveImplementation() {
|
|
||||||
assertEquals(result, EditDistanceRecursive.calculate(x, y));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testEditDistance_givenDynamicProgrammingImplementation() {
|
|
||||||
assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y));
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.algorithms.editdistance;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.Parameterized;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
@RunWith(Parameterized.class)
|
||||||
|
public class EditDistanceUnitTest extends EditDistanceDataProvider {
|
||||||
|
|
||||||
|
private String x;
|
||||||
|
private String y;
|
||||||
|
private int result;
|
||||||
|
|
||||||
|
public EditDistanceUnitTest(String a, String b, int res) {
|
||||||
|
super();
|
||||||
|
x = a;
|
||||||
|
y = b;
|
||||||
|
result = res;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testEditDistance_RecursiveImplementation() {
|
||||||
|
assertEquals(result, EditDistanceRecursive.calculate(x, y));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testEditDistance_givenDynamicProgrammingImplementation() {
|
||||||
|
assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
package com.baeldung.algorithms.linesintersection;
|
||||||
|
|
||||||
|
import java.awt.Point;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class LinesIntersectionServiceUnitTest {
|
||||||
|
private LinesIntersectionService service = new LinesIntersectionService();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
|
||||||
|
|
||||||
|
double m1 = 0;
|
||||||
|
double b1 = 0;
|
||||||
|
double m2 = 1;
|
||||||
|
double b2 = -1;
|
||||||
|
|
||||||
|
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
|
||||||
|
|
||||||
|
assertTrue(point.isPresent());
|
||||||
|
assertEquals(point.get().getX(), 1, 0.001);
|
||||||
|
assertEquals(point.get().getY(), 0, 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenParallelLines_whenCalculatePoint_thenEmpty() {
|
||||||
|
double m1 = 1;
|
||||||
|
double b1 = 0;
|
||||||
|
double m2 = 1;
|
||||||
|
double b2 = -1;
|
||||||
|
|
||||||
|
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
|
||||||
|
|
||||||
|
assertFalse(point.isPresent());
|
||||||
|
}
|
||||||
|
}
|
@ -1,23 +0,0 @@
|
|||||||
package com.baeldung.algorithms.linkedlist;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.junit.runners.Parameterized;
|
|
||||||
|
|
||||||
@RunWith(value = Parameterized.class)
|
|
||||||
public class CycleDetectionBruteForceTest extends CycleDetectionTestBase {
|
|
||||||
boolean cycleExists;
|
|
||||||
Node<Integer> head;
|
|
||||||
|
|
||||||
public CycleDetectionBruteForceTest(Node<Integer> head, boolean cycleExists) {
|
|
||||||
super();
|
|
||||||
this.cycleExists = cycleExists;
|
|
||||||
this.head = head;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenList_detectLoop() {
|
|
||||||
Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.algorithms.linkedlist;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.Parameterized;
|
||||||
|
|
||||||
|
@RunWith(value = Parameterized.class)
|
||||||
|
public class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase {
|
||||||
|
boolean cycleExists;
|
||||||
|
Node<Integer> head;
|
||||||
|
|
||||||
|
public CycleDetectionBruteForceUnitTest(Node<Integer> head, boolean cycleExists) {
|
||||||
|
super();
|
||||||
|
this.cycleExists = cycleExists;
|
||||||
|
this.head = head;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenList_detectLoop() {
|
||||||
|
Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists);
|
||||||
|
}
|
||||||
|
}
|
@ -1,23 +0,0 @@
|
|||||||
package com.baeldung.algorithms.linkedlist;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.junit.runners.Parameterized;
|
|
||||||
|
|
||||||
@RunWith(value = Parameterized.class)
|
|
||||||
public class CycleDetectionByFastAndSlowIteratorsTest extends CycleDetectionTestBase {
|
|
||||||
boolean cycleExists;
|
|
||||||
Node<Integer> head;
|
|
||||||
|
|
||||||
public CycleDetectionByFastAndSlowIteratorsTest(Node<Integer> head, boolean cycleExists) {
|
|
||||||
super();
|
|
||||||
this.cycleExists = cycleExists;
|
|
||||||
this.head = head;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenList_detectLoop() {
|
|
||||||
Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.algorithms.linkedlist;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.Parameterized;
|
||||||
|
|
||||||
|
@RunWith(value = Parameterized.class)
|
||||||
|
public class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase {
|
||||||
|
boolean cycleExists;
|
||||||
|
Node<Integer> head;
|
||||||
|
|
||||||
|
public CycleDetectionByFastAndSlowIteratorsUnitTest(Node<Integer> head, boolean cycleExists) {
|
||||||
|
super();
|
||||||
|
this.cycleExists = cycleExists;
|
||||||
|
this.head = head;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenList_detectLoop() {
|
||||||
|
Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
|
||||||
|
}
|
||||||
|
}
|
@ -1,23 +0,0 @@
|
|||||||
package com.baeldung.algorithms.linkedlist;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.junit.runners.Parameterized;
|
|
||||||
|
|
||||||
@RunWith(value = Parameterized.class)
|
|
||||||
public class CycleDetectionByHashingTest extends CycleDetectionTestBase {
|
|
||||||
boolean cycleExists;
|
|
||||||
Node<Integer> head;
|
|
||||||
|
|
||||||
public CycleDetectionByHashingTest(Node<Integer> head, boolean cycleExists) {
|
|
||||||
super();
|
|
||||||
this.cycleExists = cycleExists;
|
|
||||||
this.head = head;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenList_detectLoop() {
|
|
||||||
Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.algorithms.linkedlist;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.Parameterized;
|
||||||
|
|
||||||
|
@RunWith(value = Parameterized.class)
|
||||||
|
public class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase {
|
||||||
|
boolean cycleExists;
|
||||||
|
Node<Integer> head;
|
||||||
|
|
||||||
|
public CycleDetectionByHashingUnitTest(Node<Integer> head, boolean cycleExists) {
|
||||||
|
super();
|
||||||
|
this.cycleExists = cycleExists;
|
||||||
|
this.head = head;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenList_detectLoop() {
|
||||||
|
Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists);
|
||||||
|
}
|
||||||
|
}
|
@ -1,24 +0,0 @@
|
|||||||
package com.baeldung.algorithms.linkedlist;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.junit.runners.Parameterized;
|
|
||||||
|
|
||||||
@RunWith(value = Parameterized.class)
|
|
||||||
public class CycleRemovalBruteForceTest extends CycleDetectionTestBase {
|
|
||||||
boolean cycleExists;
|
|
||||||
Node<Integer> head;
|
|
||||||
|
|
||||||
public CycleRemovalBruteForceTest(Node<Integer> head, boolean cycleExists) {
|
|
||||||
super();
|
|
||||||
this.cycleExists = cycleExists;
|
|
||||||
this.head = head;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
|
|
||||||
Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head));
|
|
||||||
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.algorithms.linkedlist;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.Parameterized;
|
||||||
|
|
||||||
|
@RunWith(value = Parameterized.class)
|
||||||
|
public class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase {
|
||||||
|
boolean cycleExists;
|
||||||
|
Node<Integer> head;
|
||||||
|
|
||||||
|
public CycleRemovalBruteForceUnitTest(Node<Integer> head, boolean cycleExists) {
|
||||||
|
super();
|
||||||
|
this.cycleExists = cycleExists;
|
||||||
|
this.head = head;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
|
||||||
|
Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head));
|
||||||
|
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
|
||||||
|
}
|
||||||
|
}
|
@ -1,24 +0,0 @@
|
|||||||
package com.baeldung.algorithms.linkedlist;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.junit.runners.Parameterized;
|
|
||||||
|
|
||||||
@RunWith(value = Parameterized.class)
|
|
||||||
public class CycleRemovalByCountingLoopNodesTest extends CycleDetectionTestBase {
|
|
||||||
boolean cycleExists;
|
|
||||||
Node<Integer> head;
|
|
||||||
|
|
||||||
public CycleRemovalByCountingLoopNodesTest(Node<Integer> head, boolean cycleExists) {
|
|
||||||
super();
|
|
||||||
this.cycleExists = cycleExists;
|
|
||||||
this.head = head;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
|
|
||||||
Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head));
|
|
||||||
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.algorithms.linkedlist;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.Parameterized;
|
||||||
|
|
||||||
|
@RunWith(value = Parameterized.class)
|
||||||
|
public class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase {
|
||||||
|
boolean cycleExists;
|
||||||
|
Node<Integer> head;
|
||||||
|
|
||||||
|
public CycleRemovalByCountingLoopNodesUnitTest(Node<Integer> head, boolean cycleExists) {
|
||||||
|
super();
|
||||||
|
this.cycleExists = cycleExists;
|
||||||
|
this.head = head;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
|
||||||
|
Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head));
|
||||||
|
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
|
||||||
|
}
|
||||||
|
}
|
@ -1,24 +0,0 @@
|
|||||||
package com.baeldung.algorithms.linkedlist;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.junit.runners.Parameterized;
|
|
||||||
|
|
||||||
@RunWith(value = Parameterized.class)
|
|
||||||
public class CycleRemovalWithoutCountingLoopNodesTest extends CycleDetectionTestBase {
|
|
||||||
boolean cycleExists;
|
|
||||||
Node<Integer> head;
|
|
||||||
|
|
||||||
public CycleRemovalWithoutCountingLoopNodesTest(Node<Integer> head, boolean cycleExists) {
|
|
||||||
super();
|
|
||||||
this.cycleExists = cycleExists;
|
|
||||||
this.head = head;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
|
|
||||||
Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head));
|
|
||||||
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.algorithms.linkedlist;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.Parameterized;
|
||||||
|
|
||||||
|
@RunWith(value = Parameterized.class)
|
||||||
|
public class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase {
|
||||||
|
boolean cycleExists;
|
||||||
|
Node<Integer> head;
|
||||||
|
|
||||||
|
public CycleRemovalWithoutCountingLoopNodesUnitTest(Node<Integer> head, boolean cycleExists) {
|
||||||
|
super();
|
||||||
|
this.cycleExists = cycleExists;
|
||||||
|
this.head = head;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenList_ifLoopExists_thenDetectAndRemoveLoop() {
|
||||||
|
Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head));
|
||||||
|
Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,92 @@
|
|||||||
|
package com.baeldung.algorithms.mcts;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
|
||||||
|
import com.baeldung.algorithms.mcts.montecarlo.State;
|
||||||
|
import com.baeldung.algorithms.mcts.montecarlo.UCT;
|
||||||
|
import com.baeldung.algorithms.mcts.tictactoe.Board;
|
||||||
|
import com.baeldung.algorithms.mcts.tictactoe.Position;
|
||||||
|
import com.baeldung.algorithms.mcts.tree.Tree;
|
||||||
|
|
||||||
|
public class MCTSUnitTest {
|
||||||
|
private Tree gameTree;
|
||||||
|
private MonteCarloTreeSearch mcts;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void initGameTree() {
|
||||||
|
gameTree = new Tree();
|
||||||
|
mcts = new MonteCarloTreeSearch();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
|
||||||
|
double uctValue = 15.79;
|
||||||
|
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
|
||||||
|
State initState = gameTree.getRoot().getState();
|
||||||
|
List<State> possibleStates = initState.getAllPossibleStates();
|
||||||
|
assertTrue(possibleStates.size() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
|
||||||
|
Board board = new Board();
|
||||||
|
int initAvailablePositions = board.getEmptyPositions().size();
|
||||||
|
board.performMove(Board.P1, new Position(1, 1));
|
||||||
|
int availablePositions = board.getEmptyPositions().size();
|
||||||
|
assertTrue(initAvailablePositions > availablePositions);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
|
||||||
|
Board board = new Board();
|
||||||
|
|
||||||
|
int player = Board.P1;
|
||||||
|
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
|
||||||
|
for (int i = 0; i < totalMoves; i++) {
|
||||||
|
board = mcts.findNextMove(board, player);
|
||||||
|
if (board.checkStatus() != -1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
player = 3 - player;
|
||||||
|
}
|
||||||
|
int winStatus = board.checkStatus();
|
||||||
|
assertEquals(winStatus, Board.DRAW);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
|
||||||
|
Board board = new Board();
|
||||||
|
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
|
||||||
|
mcts1.setLevel(1);
|
||||||
|
MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
|
||||||
|
mcts3.setLevel(3);
|
||||||
|
|
||||||
|
int player = Board.P1;
|
||||||
|
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
|
||||||
|
for (int i = 0; i < totalMoves; i++) {
|
||||||
|
if (player == Board.P1)
|
||||||
|
board = mcts3.findNextMove(board, player);
|
||||||
|
else
|
||||||
|
board = mcts1.findNextMove(board, player);
|
||||||
|
|
||||||
|
if (board.checkStatus() != -1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
player = 3 - player;
|
||||||
|
}
|
||||||
|
int winStatus = board.checkStatus();
|
||||||
|
assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.algorithms.minimax;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
import com.baeldung.algorithms.minimax.MiniMax;
|
||||||
|
import com.baeldung.algorithms.minimax.Tree;
|
||||||
|
|
||||||
|
public class MinimaxUnitTest {
|
||||||
|
private Tree gameTree;
|
||||||
|
private MiniMax miniMax;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void initMiniMaxUtility() {
|
||||||
|
miniMax = new MiniMax();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMiniMax_whenConstructTree_thenNotNullTree() {
|
||||||
|
assertNull(gameTree);
|
||||||
|
miniMax.constructTree(6);
|
||||||
|
gameTree = miniMax.getTree();
|
||||||
|
assertNotNull(gameTree);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMiniMax_whenCheckWin_thenComputeOptimal() {
|
||||||
|
miniMax.constructTree(6);
|
||||||
|
boolean result = miniMax.checkWin();
|
||||||
|
assertTrue(result);
|
||||||
|
miniMax.constructTree(8);
|
||||||
|
result = miniMax.checkWin();
|
||||||
|
assertFalse(result);
|
||||||
|
}
|
||||||
|
}
|
@ -1,84 +0,0 @@
|
|||||||
package com.baeldung.algorithms.moneywords;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import com.baeldung.algorithms.numberwordconverter.NumberWordConverter;
|
|
||||||
|
|
||||||
public class NumberWordConverterTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenMoneyNegative_thenReturnInvalidInput() {
|
|
||||||
assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenZeroDollarsGiven_thenReturnEmptyString() {
|
|
||||||
assertEquals("", NumberWordConverter.getMoneyIntoWords(0));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenOnlyDollarsGiven_thenReturnWords() {
|
|
||||||
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenOnlyCentsGiven_thenReturnWords() {
|
|
||||||
assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenAlmostAMillioDollarsGiven_thenReturnWords() {
|
|
||||||
String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars";
|
|
||||||
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenThirtyMillionDollarsGiven_thenReturnWords() {
|
|
||||||
String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars";
|
|
||||||
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenTwoBillionDollarsGiven_thenReturnWords() {
|
|
||||||
String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars";
|
|
||||||
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenGivenDollarsAndCents_thenReturnWords() {
|
|
||||||
String expectedResult = "nine hundred twenty four dollars and sixty cents";
|
|
||||||
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenOneDollarAndNoCents_thenReturnDollarSingular() {
|
|
||||||
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenNoDollarsAndOneCent_thenReturnCentSingular() {
|
|
||||||
assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() {
|
|
||||||
assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenNoDollarsAndNinetyNineCents_thenReturnWords() {
|
|
||||||
assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() {
|
|
||||||
assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() {
|
|
||||||
assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310"));
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,84 @@
|
|||||||
|
package com.baeldung.algorithms.moneywords;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.numberwordconverter.NumberWordConverter;
|
||||||
|
|
||||||
|
public class NumberWordConverterUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMoneyNegative_thenReturnInvalidInput() {
|
||||||
|
assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenZeroDollarsGiven_thenReturnEmptyString() {
|
||||||
|
assertEquals("", NumberWordConverter.getMoneyIntoWords(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenOnlyDollarsGiven_thenReturnWords() {
|
||||||
|
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenOnlyCentsGiven_thenReturnWords() {
|
||||||
|
assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAlmostAMillioDollarsGiven_thenReturnWords() {
|
||||||
|
String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars";
|
||||||
|
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenThirtyMillionDollarsGiven_thenReturnWords() {
|
||||||
|
String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars";
|
||||||
|
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenTwoBillionDollarsGiven_thenReturnWords() {
|
||||||
|
String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars";
|
||||||
|
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGivenDollarsAndCents_thenReturnWords() {
|
||||||
|
String expectedResult = "nine hundred twenty four dollars and sixty cents";
|
||||||
|
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenOneDollarAndNoCents_thenReturnDollarSingular() {
|
||||||
|
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoDollarsAndOneCent_thenReturnCentSingular() {
|
||||||
|
assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() {
|
||||||
|
assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoDollarsAndNinetyNineCents_thenReturnWords() {
|
||||||
|
assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() {
|
||||||
|
assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() {
|
||||||
|
assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310"));
|
||||||
|
}
|
||||||
|
}
|
@ -1,28 +0,0 @@
|
|||||||
package com.baeldung.algorithms.prime;
|
|
||||||
|
|
||||||
import static com.baeldung.algorithms.prime.PrimeGenerator.*;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
import org.junit.Test;
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
public class PrimeGeneratorTest {
|
|
||||||
@Test
|
|
||||||
public void whenBruteForced_returnsSuccessfully() {
|
|
||||||
final List<Integer> primeNumbers = primeNumbersBruteForce(20);
|
|
||||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenOptimized_returnsSuccessfully() {
|
|
||||||
final List<Integer> primeNumbers = primeNumbersTill(20);
|
|
||||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenSieveOfEratosthenes_returnsSuccessfully() {
|
|
||||||
final List<Integer> primeNumbers = sieveOfEratosthenes(20);
|
|
||||||
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,42 @@
|
|||||||
|
package com.baeldung.algorithms.rectanglesoverlap;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.rectanglesoverlap.Point;
|
||||||
|
import com.baeldung.algorithms.rectanglesoverlap.Rectangle;
|
||||||
|
|
||||||
|
public class RectangleUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoOverlappingRectangles_whenisOverlappingCalled_shouldReturnTrue() {
|
||||||
|
Rectangle rectangle1 = new Rectangle(new Point(2, 1), new Point(4, 3));
|
||||||
|
Rectangle rectangle2 = new Rectangle(new Point(1, 1), new Point(6, 4));
|
||||||
|
assertTrue(rectangle1.isOverlapping(rectangle2));
|
||||||
|
|
||||||
|
rectangle1 = new Rectangle(new Point(-5, -2), new Point(2, 3));
|
||||||
|
rectangle2 = new Rectangle(new Point(-2, -1), new Point(5, 2));
|
||||||
|
assertTrue(rectangle1.isOverlapping(rectangle2));
|
||||||
|
|
||||||
|
rectangle1 = new Rectangle(new Point(-5, 1), new Point(2, 4));
|
||||||
|
rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5));
|
||||||
|
assertTrue(rectangle1.isOverlapping(rectangle2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoNonOverlappingRectangles_whenisOverlappingCalled_shouldReturnFalse() {
|
||||||
|
Rectangle rectangle1 = new Rectangle(new Point(-5, 1), new Point(-3, 4));
|
||||||
|
Rectangle rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5));
|
||||||
|
assertFalse(rectangle1.isOverlapping(rectangle2));
|
||||||
|
|
||||||
|
rectangle1 = new Rectangle(new Point(-5, 1), new Point(3, 4));
|
||||||
|
rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, -1));
|
||||||
|
assertFalse(rectangle1.isOverlapping(rectangle2));
|
||||||
|
|
||||||
|
rectangle1 = new Rectangle(new Point(-2, 1), new Point(0, 3));
|
||||||
|
rectangle2 = new Rectangle(new Point(3, 1), new Point(5, 4));
|
||||||
|
assertFalse(rectangle1.isOverlapping(rectangle2));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,29 @@
|
|||||||
|
package com.baeldung.algorithms.romannumerals;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class RomanArabicConverterUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void given2018Roman_WhenConvertingToArabic_ThenReturn2018() {
|
||||||
|
|
||||||
|
String roman2018 = "MMXVIII";
|
||||||
|
|
||||||
|
int result = RomanArabicConverter.romanToArabic(roman2018);
|
||||||
|
|
||||||
|
assertThat(result).isEqualTo(2018);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() {
|
||||||
|
|
||||||
|
int arabic1999 = 1999;
|
||||||
|
|
||||||
|
String result = RomanArabicConverter.arabicToRoman(arabic1999);
|
||||||
|
|
||||||
|
assertThat(result).isEqualTo("MCMXCIX");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.algorithms.string;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Assertions;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class EnglishAlphabetLettersUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenString_whenContainsAllCharacter_thenTrue() {
|
||||||
|
String input = "Farmer jack realized that big yellow quilts were expensive";
|
||||||
|
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() {
|
||||||
|
String input = "Farmer jack realized that big yellow quilts were expensive";
|
||||||
|
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,38 +0,0 @@
|
|||||||
package com.baeldung.jgrapht;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.jgrapht.VertexFactory;
|
|
||||||
import org.jgrapht.alg.HamiltonianCycle;
|
|
||||||
import org.jgrapht.generate.CompleteGraphGenerator;
|
|
||||||
import org.jgrapht.graph.DefaultEdge;
|
|
||||||
import org.jgrapht.graph.SimpleWeightedGraph;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class CompleteGraphTest {
|
|
||||||
|
|
||||||
static SimpleWeightedGraph<String, DefaultEdge> completeGraph;
|
|
||||||
static int size = 10;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void createCompleteGraph() {
|
|
||||||
completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
|
|
||||||
CompleteGraphGenerator<String, DefaultEdge> completeGenerator = new CompleteGraphGenerator<String, DefaultEdge>(size);
|
|
||||||
VertexFactory<String> vFactory = new VertexFactory<String>() {
|
|
||||||
private int id = 0;
|
|
||||||
public String createVertex() {
|
|
||||||
return "v" + id++;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
completeGenerator.generateGraph(completeGraph, vFactory, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenCompleteGraph_whenGetHamiltonianCyclePath_thenGetVerticeListInSequence() {
|
|
||||||
List<String> verticeList = HamiltonianCycle.getApproximateOptimalForCompleteGraph(completeGraph);
|
|
||||||
assertEquals(verticeList.size(), completeGraph.vertexSet().size());
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.jgrapht;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.jgrapht.VertexFactory;
|
||||||
|
import org.jgrapht.alg.HamiltonianCycle;
|
||||||
|
import org.jgrapht.generate.CompleteGraphGenerator;
|
||||||
|
import org.jgrapht.graph.DefaultEdge;
|
||||||
|
import org.jgrapht.graph.SimpleWeightedGraph;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CompleteGraphUnitTest {
|
||||||
|
|
||||||
|
static SimpleWeightedGraph<String, DefaultEdge> completeGraph;
|
||||||
|
static int size = 10;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void createCompleteGraph() {
|
||||||
|
completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
|
||||||
|
CompleteGraphGenerator<String, DefaultEdge> completeGenerator = new CompleteGraphGenerator<String, DefaultEdge>(size);
|
||||||
|
VertexFactory<String> vFactory = new VertexFactory<String>() {
|
||||||
|
private int id = 0;
|
||||||
|
public String createVertex() {
|
||||||
|
return "v" + id++;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
completeGenerator.generateGraph(completeGraph, vFactory, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCompleteGraph_whenGetHamiltonianCyclePath_thenGetVerticeListInSequence() {
|
||||||
|
List<String> verticeList = HamiltonianCycle.getApproximateOptimalForCompleteGraph(completeGraph);
|
||||||
|
assertEquals(verticeList.size(), completeGraph.vertexSet().size());
|
||||||
|
}
|
||||||
|
}
|
@ -1,95 +0,0 @@
|
|||||||
package com.baeldung.jgrapht;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertNotNull;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.stream.IntStream;
|
|
||||||
|
|
||||||
import org.jgrapht.DirectedGraph;
|
|
||||||
import org.jgrapht.GraphPath;
|
|
||||||
import org.jgrapht.alg.CycleDetector;
|
|
||||||
import org.jgrapht.alg.KosarajuStrongConnectivityInspector;
|
|
||||||
import org.jgrapht.alg.interfaces.StrongConnectivityAlgorithm;
|
|
||||||
import org.jgrapht.alg.shortestpath.AllDirectedPaths;
|
|
||||||
import org.jgrapht.alg.shortestpath.BellmanFordShortestPath;
|
|
||||||
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
|
|
||||||
import org.jgrapht.graph.DefaultDirectedGraph;
|
|
||||||
import org.jgrapht.graph.DefaultEdge;
|
|
||||||
import org.jgrapht.graph.DirectedSubgraph;
|
|
||||||
import org.jgrapht.traverse.BreadthFirstIterator;
|
|
||||||
import org.jgrapht.traverse.DepthFirstIterator;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class DirectedGraphTests {
|
|
||||||
DirectedGraph<String, DefaultEdge> directedGraph;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void createDirectedGraph() {
|
|
||||||
directedGraph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
|
|
||||||
IntStream.range(1, 10).forEach(i -> {
|
|
||||||
directedGraph.addVertex("v" + i);
|
|
||||||
});
|
|
||||||
directedGraph.addEdge("v1", "v2");
|
|
||||||
directedGraph.addEdge("v2", "v4");
|
|
||||||
directedGraph.addEdge("v4", "v3");
|
|
||||||
directedGraph.addEdge("v3", "v1");
|
|
||||||
directedGraph.addEdge("v5", "v4");
|
|
||||||
directedGraph.addEdge("v5", "v6");
|
|
||||||
directedGraph.addEdge("v6", "v7");
|
|
||||||
directedGraph.addEdge("v7", "v5");
|
|
||||||
directedGraph.addEdge("v8", "v5");
|
|
||||||
directedGraph.addEdge("v9", "v8");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() {
|
|
||||||
StrongConnectivityAlgorithm<String, DefaultEdge> scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph);
|
|
||||||
List<DirectedSubgraph<String, DefaultEdge>> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs();
|
|
||||||
List<String> stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet());
|
|
||||||
|
|
||||||
String randomVertex1 = stronglyConnectedVertices.get(0);
|
|
||||||
String randomVertex2 = stronglyConnectedVertices.get(3);
|
|
||||||
AllDirectedPaths<String, DefaultEdge> allDirectedPaths = new AllDirectedPaths<>(directedGraph);
|
|
||||||
|
|
||||||
List<GraphPath<String, DefaultEdge>> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size());
|
|
||||||
assertTrue(possiblePathList.size() > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() {
|
|
||||||
CycleDetector<String, DefaultEdge> cycleDetector = new CycleDetector<String, DefaultEdge>(directedGraph);
|
|
||||||
assertTrue(cycleDetector.detectCycles());
|
|
||||||
Set<String> cycleVertices = cycleDetector.findCycles();
|
|
||||||
assertTrue(cycleVertices.size() > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() {
|
|
||||||
DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph);
|
|
||||||
assertNotNull(depthFirstIterator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() {
|
|
||||||
BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph);
|
|
||||||
assertNotNull(breadthFirstIterator);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() {
|
|
||||||
DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph);
|
|
||||||
List<String> shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList();
|
|
||||||
assertNotNull(shortestPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() {
|
|
||||||
BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph);
|
|
||||||
List<String> shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList();
|
|
||||||
assertNotNull(shortestPath);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,95 @@
|
|||||||
|
package com.baeldung.jgrapht;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertNotNull;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.jgrapht.DirectedGraph;
|
||||||
|
import org.jgrapht.GraphPath;
|
||||||
|
import org.jgrapht.alg.CycleDetector;
|
||||||
|
import org.jgrapht.alg.KosarajuStrongConnectivityInspector;
|
||||||
|
import org.jgrapht.alg.interfaces.StrongConnectivityAlgorithm;
|
||||||
|
import org.jgrapht.alg.shortestpath.AllDirectedPaths;
|
||||||
|
import org.jgrapht.alg.shortestpath.BellmanFordShortestPath;
|
||||||
|
import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
|
||||||
|
import org.jgrapht.graph.DefaultDirectedGraph;
|
||||||
|
import org.jgrapht.graph.DefaultEdge;
|
||||||
|
import org.jgrapht.graph.DirectedSubgraph;
|
||||||
|
import org.jgrapht.traverse.BreadthFirstIterator;
|
||||||
|
import org.jgrapht.traverse.DepthFirstIterator;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class DirectedGraphUnitTest {
|
||||||
|
DirectedGraph<String, DefaultEdge> directedGraph;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void createDirectedGraph() {
|
||||||
|
directedGraph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
|
||||||
|
IntStream.range(1, 10).forEach(i -> {
|
||||||
|
directedGraph.addVertex("v" + i);
|
||||||
|
});
|
||||||
|
directedGraph.addEdge("v1", "v2");
|
||||||
|
directedGraph.addEdge("v2", "v4");
|
||||||
|
directedGraph.addEdge("v4", "v3");
|
||||||
|
directedGraph.addEdge("v3", "v1");
|
||||||
|
directedGraph.addEdge("v5", "v4");
|
||||||
|
directedGraph.addEdge("v5", "v6");
|
||||||
|
directedGraph.addEdge("v6", "v7");
|
||||||
|
directedGraph.addEdge("v7", "v5");
|
||||||
|
directedGraph.addEdge("v8", "v5");
|
||||||
|
directedGraph.addEdge("v9", "v8");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() {
|
||||||
|
StrongConnectivityAlgorithm<String, DefaultEdge> scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph);
|
||||||
|
List<DirectedSubgraph<String, DefaultEdge>> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs();
|
||||||
|
List<String> stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet());
|
||||||
|
|
||||||
|
String randomVertex1 = stronglyConnectedVertices.get(0);
|
||||||
|
String randomVertex2 = stronglyConnectedVertices.get(3);
|
||||||
|
AllDirectedPaths<String, DefaultEdge> allDirectedPaths = new AllDirectedPaths<>(directedGraph);
|
||||||
|
|
||||||
|
List<GraphPath<String, DefaultEdge>> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size());
|
||||||
|
assertTrue(possiblePathList.size() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() {
|
||||||
|
CycleDetector<String, DefaultEdge> cycleDetector = new CycleDetector<String, DefaultEdge>(directedGraph);
|
||||||
|
assertTrue(cycleDetector.detectCycles());
|
||||||
|
Set<String> cycleVertices = cycleDetector.findCycles();
|
||||||
|
assertTrue(cycleVertices.size() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() {
|
||||||
|
DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph);
|
||||||
|
assertNotNull(depthFirstIterator);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() {
|
||||||
|
BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph);
|
||||||
|
assertNotNull(breadthFirstIterator);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() {
|
||||||
|
DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph);
|
||||||
|
List<String> shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList();
|
||||||
|
assertNotNull(shortestPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() {
|
||||||
|
BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph);
|
||||||
|
List<String> shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList();
|
||||||
|
assertNotNull(shortestPath);
|
||||||
|
}
|
||||||
|
}
|
@ -1,42 +0,0 @@
|
|||||||
package com.baeldung.jgrapht;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.util.stream.IntStream;
|
|
||||||
|
|
||||||
import org.jgrapht.GraphPath;
|
|
||||||
import org.jgrapht.alg.cycle.HierholzerEulerianCycle;
|
|
||||||
import org.jgrapht.graph.DefaultEdge;
|
|
||||||
import org.jgrapht.graph.SimpleWeightedGraph;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class EulerianCircuitTest {
|
|
||||||
SimpleWeightedGraph<String, DefaultEdge> simpleGraph;
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void createGraphWithEulerianCircuit() {
|
|
||||||
simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
|
|
||||||
IntStream.range(1, 6).forEach(i -> {
|
|
||||||
simpleGraph.addVertex("v" + i);
|
|
||||||
});
|
|
||||||
IntStream.range(1, 6).forEach(i -> {
|
|
||||||
int endVertexNo = (i + 1) > 5 ? 1 : i + 1;
|
|
||||||
simpleGraph.addEdge("v" + i, "v" + endVertexNo);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenGraph_whenCheckEluerianCycle_thenGetResult() {
|
|
||||||
HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>();
|
|
||||||
assertTrue(eulerianCycle.isEulerian(simpleGraph));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenGraphWithEulerianCircuit_whenGetEulerianCycle_thenGetGraphPath() {
|
|
||||||
HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>();
|
|
||||||
GraphPath path = eulerianCycle.getEulerianCycle(simpleGraph);
|
|
||||||
assertTrue(path.getEdgeList().containsAll(simpleGraph.edgeSet()));
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,42 @@
|
|||||||
|
package com.baeldung.jgrapht;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.jgrapht.GraphPath;
|
||||||
|
import org.jgrapht.alg.cycle.HierholzerEulerianCycle;
|
||||||
|
import org.jgrapht.graph.DefaultEdge;
|
||||||
|
import org.jgrapht.graph.SimpleWeightedGraph;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class EulerianCircuitUnitTest {
|
||||||
|
SimpleWeightedGraph<String, DefaultEdge> simpleGraph;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void createGraphWithEulerianCircuit() {
|
||||||
|
simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class);
|
||||||
|
IntStream.range(1, 6).forEach(i -> {
|
||||||
|
simpleGraph.addVertex("v" + i);
|
||||||
|
});
|
||||||
|
IntStream.range(1, 6).forEach(i -> {
|
||||||
|
int endVertexNo = (i + 1) > 5 ? 1 : i + 1;
|
||||||
|
simpleGraph.addEdge("v" + i, "v" + endVertexNo);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGraph_whenCheckEluerianCycle_thenGetResult() {
|
||||||
|
HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>();
|
||||||
|
assertTrue(eulerianCycle.isEulerian(simpleGraph));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenGraphWithEulerianCircuit_whenGetEulerianCycle_thenGetGraphPath() {
|
||||||
|
HierholzerEulerianCycle eulerianCycle = new HierholzerEulerianCycle<>();
|
||||||
|
GraphPath path = eulerianCycle.getEulerianCycle(simpleGraph);
|
||||||
|
assertTrue(path.getEdgeList().containsAll(simpleGraph.edgeSet()));
|
||||||
|
}
|
||||||
|
}
|
@ -1,11 +1,11 @@
|
|||||||
<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/maven-v4_0_0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>animal-sniffer-mvn-plugin</artifactId>
|
<artifactId>animal-sniffer-mvn-plugin</artifactId>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<version>1.0-SNAPSHOT</version>
|
<version>1.0-SNAPSHOT</version>
|
||||||
<name>example-animal-sniffer-mvn-plugin</name>
|
<name>animal-sniffer-mvn-plugin</name>
|
||||||
<url>http://maven.apache.org</url>
|
<url>http://maven.apache.org</url>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
@ -14,15 +14,6 @@
|
|||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>junit</groupId>
|
|
||||||
<artifactId>junit</artifactId>
|
|
||||||
<version>${junit.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
13
animal-sniffer-mvn-plugin/src/main/resources/logback.xml
Normal file
13
animal-sniffer-mvn-plugin/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -1,7 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
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>
|
||||||
<artifactId>annotation-processing</artifactId>
|
<artifactId>annotation-processing</artifactId>
|
||||||
|
|
||||||
|
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<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>
|
||||||
<artifactId>annotation-user</artifactId>
|
<artifactId>annotation-user</artifactId>
|
||||||
|
|
||||||
|
13
annotations/annotation-user/src/main/resources/logback.xml
Normal file
13
annotations/annotation-user/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<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>
|
||||||
<artifactId>annotations</artifactId>
|
<artifactId>annotations</artifactId>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
3
antlr/README.md
Normal file
3
antlr/README.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Java with ANTLR](http://www.baeldung.com/java-antlr)
|
58
antlr/pom.xml
Normal file
58
antlr/pom.xml
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
<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/maven-v4_0_0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>antlr</artifactId>
|
||||||
|
<name>antlr</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.antlr</groupId>
|
||||||
|
<artifactId>antlr4-maven-plugin</artifactId>
|
||||||
|
<version>${antlr.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>antlr4</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>build-helper-maven-plugin</artifactId>
|
||||||
|
<version>${mojo.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>generate-sources</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>add-source</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<sources>
|
||||||
|
<source>${basedir}/target/generated-sources/antlr4</source>
|
||||||
|
</sources>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.antlr</groupId>
|
||||||
|
<artifactId>antlr4-runtime</artifactId>
|
||||||
|
<version>${antlr.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<properties>
|
||||||
|
<antlr.version>4.7.1</antlr.version>
|
||||||
|
<mojo.version>3.0.0</mojo.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
1775
antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4
Normal file
1775
antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4
Normal file
File diff suppressed because it is too large
Load Diff
16
antlr/src/main/antlr4/com/baeldung/antlr/Log.g4
Normal file
16
antlr/src/main/antlr4/com/baeldung/antlr/Log.g4
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
grammar Log;
|
||||||
|
|
||||||
|
log : entry+;
|
||||||
|
entry : timestamp ' ' level ' ' message CRLF;
|
||||||
|
timestamp : DATE ' ' TIME;
|
||||||
|
level : 'ERROR' | 'INFO' | 'DEBUG';
|
||||||
|
message : (TEXT | ' ')+;
|
||||||
|
|
||||||
|
fragment DIGIT : [0-9];
|
||||||
|
fragment TWODIGIT : DIGIT DIGIT;
|
||||||
|
fragment LETTER : [A-Za-z];
|
||||||
|
|
||||||
|
DATE : TWODIGIT TWODIGIT '-' LETTER LETTER LETTER '-' TWODIGIT;
|
||||||
|
TIME : TWODIGIT ':' TWODIGIT ':' TWODIGIT;
|
||||||
|
TEXT : LETTER+;
|
||||||
|
CRLF : '\r'? '\n' | '\r';
|
@ -0,0 +1,28 @@
|
|||||||
|
package com.baeldung.antlr.java;
|
||||||
|
|
||||||
|
import com.baeldung.antlr.Java8BaseListener;
|
||||||
|
import com.baeldung.antlr.Java8Parser;
|
||||||
|
import org.antlr.v4.runtime.tree.TerminalNode;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class UppercaseMethodListener extends Java8BaseListener {
|
||||||
|
|
||||||
|
private List<String> errors = new ArrayList<String>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enterMethodDeclarator(Java8Parser.MethodDeclaratorContext ctx) {
|
||||||
|
TerminalNode node = ctx.Identifier();
|
||||||
|
String methodName = node.getText();
|
||||||
|
|
||||||
|
if (Character.isUpperCase(methodName.charAt(0))){
|
||||||
|
errors.add(String.format("Method %s is uppercased!", methodName));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> getErrors(){
|
||||||
|
return Collections.unmodifiableList(errors);
|
||||||
|
}
|
||||||
|
}
|
51
antlr/src/main/java/com/baeldung/antlr/log/LogListener.java
Normal file
51
antlr/src/main/java/com/baeldung/antlr/log/LogListener.java
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.antlr.log;
|
||||||
|
|
||||||
|
import com.baeldung.antlr.LogBaseListener;
|
||||||
|
import com.baeldung.antlr.LogParser;
|
||||||
|
import com.baeldung.antlr.log.model.LogLevel;
|
||||||
|
import com.baeldung.antlr.log.model.LogEntry;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
public class LogListener extends LogBaseListener {
|
||||||
|
|
||||||
|
private static final DateTimeFormatter DEFAULT_DATETIME_FORMATTER
|
||||||
|
= DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss", Locale.ENGLISH);
|
||||||
|
|
||||||
|
private List<LogEntry> entries = new ArrayList<>();
|
||||||
|
private LogEntry currentLogEntry;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enterEntry(LogParser.EntryContext ctx) {
|
||||||
|
this.currentLogEntry = new LogEntry();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void exitEntry(LogParser.EntryContext ctx) {
|
||||||
|
entries.add(currentLogEntry);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enterTimestamp(LogParser.TimestampContext ctx) {
|
||||||
|
currentLogEntry.setTimestamp(LocalDateTime.parse(ctx.getText(), DEFAULT_DATETIME_FORMATTER));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enterMessage(LogParser.MessageContext ctx) {
|
||||||
|
currentLogEntry.setMessage(ctx.getText());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void enterLevel(LogParser.LevelContext ctx) {
|
||||||
|
currentLogEntry.setLevel(LogLevel.valueOf(ctx.getText()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<LogEntry> getEntries() {
|
||||||
|
return Collections.unmodifiableList(entries);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.antlr.log.model;
|
||||||
|
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
public class LogEntry {
|
||||||
|
|
||||||
|
private LogLevel level;
|
||||||
|
private String message;
|
||||||
|
private LocalDateTime timestamp;
|
||||||
|
|
||||||
|
public LogLevel getLevel() {
|
||||||
|
return level;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLevel(LogLevel level) {
|
||||||
|
this.level = level;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMessage(String message) {
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getTimestamp() {
|
||||||
|
return timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTimestamp(LocalDateTime timestamp) {
|
||||||
|
this.timestamp = timestamp;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
package com.baeldung.antlr.log.model;
|
||||||
|
|
||||||
|
public enum LogLevel {
|
||||||
|
DEBUG, INFO, ERROR
|
||||||
|
}
|
13
antlr/src/main/resources/logback.xml
Normal file
13
antlr/src/main/resources/logback.xml
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration>
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||||
|
</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="INFO">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.antlr;
|
||||||
|
|
||||||
|
import com.baeldung.antlr.java.UppercaseMethodListener;
|
||||||
|
import org.antlr.v4.runtime.CharStreams;
|
||||||
|
import org.antlr.v4.runtime.CommonTokenStream;
|
||||||
|
import org.antlr.v4.runtime.tree.ParseTree;
|
||||||
|
import org.antlr.v4.runtime.tree.ParseTreeWalker;
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
|
||||||
|
public class JavaParserUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenOneMethodStartsWithUpperCase_thenOneErrorReturned() throws Exception{
|
||||||
|
|
||||||
|
String javaClassContent = "public class SampleClass { void DoSomething(){} }";
|
||||||
|
Java8Lexer java8Lexer = new Java8Lexer(CharStreams.fromString(javaClassContent));
|
||||||
|
CommonTokenStream tokens = new CommonTokenStream(java8Lexer);
|
||||||
|
Java8Parser java8Parser = new Java8Parser(tokens);
|
||||||
|
ParseTree tree = java8Parser.compilationUnit();
|
||||||
|
ParseTreeWalker walker = new ParseTreeWalker();
|
||||||
|
UppercaseMethodListener uppercaseMethodListener = new UppercaseMethodListener();
|
||||||
|
walker.walk(uppercaseMethodListener, tree);
|
||||||
|
|
||||||
|
assertThat(uppercaseMethodListener.getErrors().size(), is(1));
|
||||||
|
assertThat(uppercaseMethodListener.getErrors().get(0),
|
||||||
|
is("Method DoSomething is uppercased!"));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,36 @@
|
|||||||
|
package com.baeldung.antlr;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
|
||||||
|
import com.baeldung.antlr.log.LogListener;
|
||||||
|
import com.baeldung.antlr.log.model.LogLevel;
|
||||||
|
import com.baeldung.antlr.log.model.LogEntry;
|
||||||
|
import org.antlr.v4.runtime.CharStreams;
|
||||||
|
import org.antlr.v4.runtime.CommonTokenStream;
|
||||||
|
import org.antlr.v4.runtime.tree.ParseTreeWalker;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
|
||||||
|
public class LogParserUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenLogContainsOneErrorLogEntry_thenOneErrorIsReturned() throws Exception {
|
||||||
|
String logLines = "2018-May-05 14:20:21 DEBUG entering awesome method\r\n" +
|
||||||
|
"2018-May-05 14:20:24 ERROR Bad thing happened\r\n";
|
||||||
|
LogLexer serverLogLexer = new LogLexer(CharStreams.fromString(logLines));
|
||||||
|
CommonTokenStream tokens = new CommonTokenStream( serverLogLexer );
|
||||||
|
LogParser logParser = new LogParser(tokens);
|
||||||
|
ParseTreeWalker walker = new ParseTreeWalker();
|
||||||
|
LogListener logWalker = new LogListener();
|
||||||
|
walker.walk(logWalker, logParser.log());
|
||||||
|
|
||||||
|
assertThat(logWalker.getEntries().size(), is(2));
|
||||||
|
LogEntry error = logWalker.getEntries().get(1);
|
||||||
|
assertThat(error.getLevel(), is(LogLevel.ERROR));
|
||||||
|
assertThat(error.getMessage(), is("Bad thing happened"));
|
||||||
|
assertThat(error.getTimestamp(), is(LocalDateTime.of(2018,5,5,14,20,24)));
|
||||||
|
}
|
||||||
|
}
|
2
apache-avro/README.md
Normal file
2
apache-avro/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [Guide to Apache Avro](http://www.baeldung.com/java-apache-avro)
|
89
apache-avro/pom.xml
Normal file
89
apache-avro/pom.xml
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<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>apache-avro</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<name>Apache Avro</version>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<compiler-plugin.version>3.5</compiler-plugin.version>
|
||||||
|
<avro.version>1.8.2</avro.version>
|
||||||
|
<java.version>1.8</java.version>
|
||||||
|
<slf4j.version>1.7.25</slf4j.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.10</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-simple</artifactId>
|
||||||
|
<version>${slf4j.version}</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.avro</groupId>
|
||||||
|
<artifactId>avro</artifactId>
|
||||||
|
<version>${avro.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.avro</groupId>
|
||||||
|
<artifactId>avro-compiler</artifactId>
|
||||||
|
<version>${avro.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.avro</groupId>
|
||||||
|
<artifactId>avro-maven-plugin</artifactId>
|
||||||
|
<version>${avro.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${java.version}</source>
|
||||||
|
<target>${java.version}</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.avro</groupId>
|
||||||
|
<artifactId>avro-maven-plugin</artifactId>
|
||||||
|
<version>${avro.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>schemas</id>
|
||||||
|
<phase>generate-sources</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>schema</goal>
|
||||||
|
<goal>protocol</goal>
|
||||||
|
<goal>idl-protocol</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<sourceDirectory>${project.basedir}/src/main/resources/</sourceDirectory>
|
||||||
|
<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.baeldung.avro.util;
|
||||||
|
|
||||||
|
import org.apache.avro.Schema;
|
||||||
|
import org.apache.avro.compiler.specific.SpecificCompiler;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class AvroClassGenerator {
|
||||||
|
public void generateAvroClasses() throws IOException {
|
||||||
|
SpecificCompiler compiler = new SpecificCompiler(new Schema.Parser().parse(new File("src/main/resources/avroHttpRequest-schema.avsc")));
|
||||||
|
compiler.compileToDestination(new File("src/main/resources"), new File("src/main/java"));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.avro.util;
|
||||||
|
|
||||||
|
|
||||||
|
import org.apache.avro.Schema;
|
||||||
|
import org.apache.avro.SchemaBuilder;
|
||||||
|
|
||||||
|
public class AvroSchemaBuilder {
|
||||||
|
|
||||||
|
public Schema createAvroHttpRequestSchema(){
|
||||||
|
|
||||||
|
Schema clientIdentifier = SchemaBuilder.record("ClientIdentifier").namespace("com.baeldung.avro.model")
|
||||||
|
.fields().requiredString("hostName").requiredString("ipAddress").endRecord();
|
||||||
|
|
||||||
|
Schema avroHttpRequest = SchemaBuilder.record("AvroHttpRequest").namespace("com.baeldung.avro.model").fields()
|
||||||
|
.requiredLong("requestTime")
|
||||||
|
.name("clientIdentifier").type(clientIdentifier).noDefault()
|
||||||
|
.name("employeeNames").type().array().items().stringType().arrayDefault(null)
|
||||||
|
.name("active").type().enumeration("Active").symbols("YES", "NO").noDefault()
|
||||||
|
.endRecord();
|
||||||
|
return avroHttpRequest;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
@ -0,0 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* Autogenerated by Avro
|
||||||
|
*
|
||||||
|
* DO NOT EDIT DIRECTLY
|
||||||
|
*/
|
||||||
|
package com.baeldung.avro.util.model;
|
||||||
|
@SuppressWarnings("all")
|
||||||
|
@org.apache.avro.specific.AvroGenerated
|
||||||
|
public enum Active {
|
||||||
|
YES, NO ;
|
||||||
|
public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"Active\",\"namespace\":\"com.baeldung.avro.model\",\"symbols\":[\"YES\",\"NO\"]}");
|
||||||
|
public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user