Merge branch 'master' of https://github.com/eugenp/tutorials into zuul_throttling
This commit is contained in:
commit
2bca6e0c83
25
.gitignore
vendored
25
.gitignore
vendored
@ -34,8 +34,6 @@ spring-security-openid/src/main/resources/application.properties
|
|||||||
|
|
||||||
spring-all/*.log
|
spring-all/*.log
|
||||||
|
|
||||||
*.jar
|
|
||||||
|
|
||||||
SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
|
SpringDataInjectionDemo/.mvn/wrapper/maven-wrapper.properties
|
||||||
|
|
||||||
spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
|
spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
|
||||||
@ -43,3 +41,26 @@ spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
|
|||||||
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
|
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
|
||||||
*.springBeans
|
*.springBeans
|
||||||
|
|
||||||
|
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
|
||||||
|
**/nbproject/
|
||||||
|
**/nb-configuration.xml
|
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 test -fae
|
script: travis_wait 60 mvn -q install -Pdefault-first,default-second
|
||||||
|
|
||||||
sudo: required
|
sudo: required
|
||||||
|
|
||||||
|
24
JGit/pom.xml
24
JGit/pom.xml
@ -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>
|
||||||
@ -13,11 +15,6 @@
|
|||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<maven.compiler.source>1.8</maven.compiler.source>
|
|
||||||
<maven.compiler.target>1.8</maven.compiler.target>
|
|
||||||
</properties>
|
|
||||||
<repositories>
|
<repositories>
|
||||||
<repository>
|
<repository>
|
||||||
<id>jgit-repository</id>
|
<id>jgit-repository</id>
|
||||||
@ -30,22 +27,27 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.eclipse.jgit</groupId>
|
<groupId>org.eclipse.jgit</groupId>
|
||||||
<artifactId>org.eclipse.jgit</artifactId>
|
<artifactId>org.eclipse.jgit</artifactId>
|
||||||
<version>4.5.0.201609210915-r</version>
|
<version>${org.eclipse.jgit.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.eclipse.jgit</groupId>
|
<groupId>org.eclipse.jgit</groupId>
|
||||||
<artifactId>org.eclipse.jgit.archive</artifactId>
|
<artifactId>org.eclipse.jgit.archive</artifactId>
|
||||||
<version>4.5.0.201609210915-r</version>
|
<version>${org.eclipse.jgit.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>commons-io</groupId>
|
<groupId>commons-io</groupId>
|
||||||
<artifactId>commons-io</artifactId>
|
<artifactId>commons-io</artifactId>
|
||||||
<version>2.5</version>
|
<version>${commons-io.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.slf4j</groupId>
|
<groupId>org.slf4j</groupId>
|
||||||
<artifactId>slf4j-simple</artifactId>
|
<artifactId>slf4j-simple</artifactId>
|
||||||
<version>1.7.21</version>
|
<version>${org.slf4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<org.eclipse.jgit.version>4.5.0.201609210915-r</org.eclipse.jgit.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
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>
|
37
README.md
37
README.md
@ -2,30 +2,37 @@
|
|||||||
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 (along with the newly announced Boot 2 material): <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/>
|
||||||
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Spring Tutorials
|
Java and Spring Tutorials
|
||||||
================
|
================
|
||||||
|
|
||||||
This project is **a collection of small and focused tutorials** each covering a single and well defined area of development.
|
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
||||||
Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`).
|
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Securiyt.
|
||||||
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
||||||
|
|
||||||
|
|
||||||
Working with the code in Eclipse
|
Building the project
|
||||||
================================
|
====================
|
||||||
Any IDE can be used to work with the projects, but if you're using Eclipse, consider the following.
|
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
||||||
|
|
||||||
- import the included **formatter** in Eclipse:
|
|
||||||
`https://github.com/eugenp/tutorials/tree/master/eclipse`
|
Building a single module
|
||||||
|
====================
|
||||||
|
To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory
|
||||||
|
|
||||||
|
|
||||||
|
Running a Spring Boot module
|
||||||
|
====================
|
||||||
|
To run a Spring Boot module run the command: `mvn spring-boot:run -Dgib.enabled=false` in the module directory
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
CI - Jenkins
|
|
||||||
================================
|
|
||||||
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
|
|
||||||
|
@ -1,12 +1,9 @@
|
|||||||
<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>
|
|
||||||
<artifactId>Twitter4J</artifactId>
|
<artifactId>Twitter4J</artifactId>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
<version>1.0-SNAPSHOT</version>
|
|
||||||
<name>Twitter4J</name>
|
<name>Twitter4J</name>
|
||||||
<url>http://maven.apache.org</url>
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
@ -14,39 +11,16 @@
|
|||||||
<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>
|
||||||
|
|
||||||
<build>
|
<properties>
|
||||||
<finalName>${project.artifactId}</finalName>
|
<twitter4j-stream.version>4.0.6</twitter4j-stream.version>
|
||||||
<resources>
|
</properties>
|
||||||
<resource>
|
|
||||||
<directory>src/main/resources</directory>
|
|
||||||
</resource>
|
|
||||||
</resources>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/ApplicationTest.java</exclude>
|
|
||||||
</excludes>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
</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>
|
2
activejdbc/README.md
Normal file
2
activejdbc/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
### Relevant Articles:
|
||||||
|
- [Introduction to ActiveJDBC](http://www.baeldung.com/active-jdbc)
|
90
activejdbc/pom.xml
Normal file
90
activejdbc/pom.xml
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
<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>
|
||||||
|
<artifactId>activejdbc</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>activejdbc</name>
|
||||||
|
<url>http://maven.apache.org</url>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.javalite</groupId>
|
||||||
|
<artifactId>activejdbc</artifactId>
|
||||||
|
<version>${activejdbc.version}</version>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>opensymphony</groupId>
|
||||||
|
<artifactId>oscache</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>mysql</groupId>
|
||||||
|
<artifactId>mysql-connector-java</artifactId>
|
||||||
|
<version>${mysql.connector.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-simple</artifactId>
|
||||||
|
<version>${org.slf4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${java.version}</source>
|
||||||
|
<target>${java.version}</target>
|
||||||
|
<encoding>UTF-8</encoding>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.javalite</groupId>
|
||||||
|
<artifactId>activejdbc-instrumentation</artifactId>
|
||||||
|
<version>${activejdbc.version}</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>process-classes</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>instrument</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.javalite</groupId>
|
||||||
|
<artifactId>db-migrator-maven-plugin</artifactId>
|
||||||
|
<version>${activejdbc.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<configFile>${project.basedir}/src/main/resources/database.properties</configFile>
|
||||||
|
<environments>${environments}</environments>
|
||||||
|
</configuration>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>mysql</groupId>
|
||||||
|
<artifactId>mysql-connector-java</artifactId>
|
||||||
|
<version>${mysql.connector.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<activejdbc.version>2.0</activejdbc.version>
|
||||||
|
<environments>development.test,development</environments>
|
||||||
|
<mysql.connector.version>5.1.34</mysql.connector.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
61
activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java
Normal file
61
activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
|
||||||
|
import com.baeldung.model.Employee;
|
||||||
|
import com.baeldung.model.Role;
|
||||||
|
import org.javalite.activejdbc.Base;
|
||||||
|
import org.javalite.activejdbc.LazyList;
|
||||||
|
import org.javalite.activejdbc.Model;
|
||||||
|
|
||||||
|
public class ActiveJDBCApp
|
||||||
|
{
|
||||||
|
public static void main( String[] args )
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
Base.open();
|
||||||
|
ActiveJDBCApp app = new ActiveJDBCApp();
|
||||||
|
app.create();
|
||||||
|
app.update();
|
||||||
|
app.delete();
|
||||||
|
app.deleteCascade();
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} finally {
|
||||||
|
Base.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void create() {
|
||||||
|
Employee employee = new Employee("Hugo","C","M","BN");
|
||||||
|
employee.saveIt();
|
||||||
|
employee.add(new Role("Java Developer","BN"));
|
||||||
|
LazyList<Model> all = Employee.findAll();
|
||||||
|
System.out.println(all.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void update() {
|
||||||
|
Employee employee = Employee.findFirst("first_name = ?","Hugo");
|
||||||
|
employee.set("last_namea","Choi").saveIt();
|
||||||
|
employee = Employee.findFirst("last_name = ?","Choi");
|
||||||
|
System.out.println(employee.getString("first_name") + " " + employee.getString("last_name"));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void delete() {
|
||||||
|
Employee employee = Employee.findFirst("first_name = ?","Hugo");
|
||||||
|
employee.delete();
|
||||||
|
employee = Employee.findFirst("last_name = ?","Choi");
|
||||||
|
if(null == employee){
|
||||||
|
System.out.println("No such Employee found!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void deleteCascade() {
|
||||||
|
create();
|
||||||
|
Employee employee = Employee.findFirst("first_name = ?","Hugo");
|
||||||
|
employee.deleteCascade();
|
||||||
|
employee = Employee.findFirst("last_name = ?","C");
|
||||||
|
if(null == employee){
|
||||||
|
System.out.println("No such Employee found!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
23
activejdbc/src/main/java/com/baeldung/model/Employee.java
Normal file
23
activejdbc/src/main/java/com/baeldung/model/Employee.java
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.model;
|
||||||
|
|
||||||
|
|
||||||
|
import org.javalite.activejdbc.Model;
|
||||||
|
|
||||||
|
public class Employee extends Model {
|
||||||
|
|
||||||
|
public Employee(){
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public Employee(String firstName, String lastName, String gender, String createdBy) {
|
||||||
|
set("first_name1",firstName);
|
||||||
|
set("last_name",lastName);
|
||||||
|
set("gender",gender);
|
||||||
|
set("created_by",createdBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLastName() {
|
||||||
|
return getString("last_name");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
22
activejdbc/src/main/java/com/baeldung/model/Role.java
Normal file
22
activejdbc/src/main/java/com/baeldung/model/Role.java
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.model;
|
||||||
|
|
||||||
|
|
||||||
|
import org.javalite.activejdbc.Model;
|
||||||
|
import org.javalite.activejdbc.annotations.Table;
|
||||||
|
|
||||||
|
@Table("EMP_ROLES")
|
||||||
|
public class Role extends Model {
|
||||||
|
|
||||||
|
public Role(){
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public Role(String role,String createdBy){
|
||||||
|
set("role_name",role);
|
||||||
|
set("created_by",createdBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRoleName() {
|
||||||
|
return getString("role_name");
|
||||||
|
}
|
||||||
|
}
|
25
activejdbc/src/main/migration/_create_tables.sql
Normal file
25
activejdbc/src/main/migration/_create_tables.sql
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# noinspection SqlNoDataSourceInspectionForFile
|
||||||
|
|
||||||
|
create table organisation.employees
|
||||||
|
(
|
||||||
|
id int not null auto_increment
|
||||||
|
primary key,
|
||||||
|
first_name varchar(100) not null,
|
||||||
|
last_name varchar(100) not null,
|
||||||
|
gender varchar(1) not null,
|
||||||
|
created_at datetime not null,
|
||||||
|
updated_at datetime null,
|
||||||
|
created_by varchar(100) not null,
|
||||||
|
updated_by varchar(100) null
|
||||||
|
)ENGINE = InnoDB DEFAULT CHARSET = utf8;
|
||||||
|
|
||||||
|
create table organisation.emp_roles
|
||||||
|
(
|
||||||
|
id int not null auto_increment primary key,
|
||||||
|
employee_id int not null,
|
||||||
|
role_name varchar(100) not null,
|
||||||
|
created_at datetime not null,
|
||||||
|
updated_at datetime null,
|
||||||
|
created_by varchar(100) not null,
|
||||||
|
updated_by varchar(100) null
|
||||||
|
)ENGINE = InnoDB DEFAULT CHARSET = utf8;
|
10
activejdbc/src/main/resources/database.properties
Normal file
10
activejdbc/src/main/resources/database.properties
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
development.driver=com.mysql.jdbc.Driver
|
||||||
|
development.username=root
|
||||||
|
development.password=123456
|
||||||
|
development.url=jdbc:mysql://localhost/organisation
|
||||||
|
|
||||||
|
|
||||||
|
development.test.driver=com.mysql.jdbc.Driver
|
||||||
|
development.test.username=root
|
||||||
|
development.test.password=123456
|
||||||
|
development.test.url=jdbc:mysql://localhost/organisation_test
|
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>
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung;
|
||||||
|
|
||||||
|
import com.baeldung.model.Employee;
|
||||||
|
import com.baeldung.model.Role;
|
||||||
|
import org.javalite.activejdbc.test.DBSpec;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class ActiveJDBCAppManualTest extends DBSpec
|
||||||
|
{
|
||||||
|
@Test
|
||||||
|
public void ifEmployeeCreated_thenIsValid() {
|
||||||
|
Employee employee = new Employee("B", "N", "M", "BN");
|
||||||
|
the(employee).shouldBe("valid");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ifEmployeeCreatedWithRoles_thenShouldPersist() {
|
||||||
|
Employee employee = new Employee("B", "N", "M", "BN");
|
||||||
|
employee.saveIt();
|
||||||
|
employee.add(new Role("Java Developer","BN"));
|
||||||
|
employee.add(new Role("Lead Java Developer","BN"));
|
||||||
|
a(Role.count()).shouldBeEqual(2);
|
||||||
|
List<Role> roles = employee.getAll(Role.class).orderBy("created_at");
|
||||||
|
the(roles.get(0).getRoleName()).shouldBeEqual("Java Developer");
|
||||||
|
the(roles.get(1).getRoleName()).shouldBeEqual("Lead Java Developer");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ifEmployeeCreatedWithRoles_whenNameUpdated_thenShouldShowNewName() {
|
||||||
|
Employee employee = new Employee("Binesh", "N", "M", "BN");
|
||||||
|
employee.saveIt();
|
||||||
|
employee.add(new Role("Java Developer","BN"));
|
||||||
|
employee.add(new Role("Lead Java Developer","BN"));
|
||||||
|
employee = Employee.findFirst("first_name = ?", "Binesh");
|
||||||
|
employee.set("last_name","Narayanan").saveIt();
|
||||||
|
Employee updated = Employee.findFirst("first_name = ?", "Binesh");
|
||||||
|
the(updated.getLastName()).shouldBeEqual("Narayanan");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ifEmployeeCreatedWithRoles_whenDeleted_thenShouldNotBeFound() {
|
||||||
|
Employee employee = new Employee("Binesh", "N", "M", "BN");
|
||||||
|
employee.saveIt();
|
||||||
|
employee.add(new Role("Java Developer","BN"));
|
||||||
|
employee.delete();
|
||||||
|
employee = Employee.findFirst("first_name = ?", "Binesh");
|
||||||
|
the(employee).shouldBeNull();
|
||||||
|
}
|
||||||
|
}
|
@ -1,15 +1,15 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
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>
|
||||||
|
<artifactId>akka-streams</artifactId>
|
||||||
|
<name>akka-streams</name>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>parent-modules</artifactId>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<artifactId>akka-streams</artifactId>
|
|
||||||
<name>akka-streams</name>
|
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -23,6 +23,7 @@
|
|||||||
<version>${akkastreams.version}</version>
|
<version>${akkastreams.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<akkastreams.version>2.5.2</akkastreams.version>
|
<akkastreams.version>2.5.2</akkastreams.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
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)
|
||||||
@ -15,3 +14,20 @@
|
|||||||
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
|
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
|
||||||
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
|
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
|
||||||
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
|
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
|
||||||
|
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
|
||||||
|
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
|
||||||
|
- [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze)
|
||||||
|
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
|
||||||
|
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
|
||||||
|
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||||
|
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
|
||||||
|
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
|
||||||
|
- [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)
|
||||||
|
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
|
||||||
|
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
||||||
|
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
||||||
|
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||||
|
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
|
||||||
|
- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort)
|
||||||
|
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
|
||||||
|
@ -5,12 +5,6 @@
|
|||||||
<artifactId>algorithms</artifactId>
|
<artifactId>algorithms</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
<properties>
|
|
||||||
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
|
|
||||||
<lombok.version>1.16.12</lombok.version>
|
|
||||||
<commons-math3.version>3.6.1</commons-math3.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>parent-modules</artifactId>
|
||||||
@ -23,6 +17,11 @@
|
|||||||
<artifactId>commons-math3</artifactId>
|
<artifactId>commons-math3</artifactId>
|
||||||
<version>${commons-math3.version}</version>
|
<version>${commons-math3.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-codec</groupId>
|
||||||
|
<artifactId>commons-codec</artifactId>
|
||||||
|
<version>${commons-codec.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
@ -32,17 +31,22 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.jenetics</groupId>
|
<groupId>io.jenetics</groupId>
|
||||||
<artifactId>jenetics</artifactId>
|
<artifactId>jenetics</artifactId>
|
||||||
<version>3.7.0</version>
|
<version>${io.jenetics.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jgrapht</groupId>
|
<groupId>org.jgrapht</groupId>
|
||||||
<artifactId>jgrapht-core</artifactId>
|
<artifactId>jgrapht-core</artifactId>
|
||||||
<version>1.0.1</version>
|
<version>${org.jgrapht.core.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>pl.allegro.finance</groupId>
|
||||||
|
<artifactId>tradukisto</artifactId>
|
||||||
|
<version>${tradukisto.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
<artifactId>assertj-core</artifactId>
|
<artifactId>assertj-core</artifactId>
|
||||||
<version>3.9.0</version>
|
<version>${org.assertj.core.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
@ -58,6 +62,7 @@
|
|||||||
</plugins>
|
</plugins>
|
||||||
</pluginManagement>
|
</pluginManagement>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<reporting>
|
<reporting>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
@ -77,4 +82,15 @@
|
|||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</reporting>
|
</reporting>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<lombok.version>1.16.12</lombok.version>
|
||||||
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
|
<tradukisto.version>1.0.1</tradukisto.version>
|
||||||
|
<io.jenetics.version>3.7.0</io.jenetics.version>
|
||||||
|
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
|
||||||
|
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||||
|
<commons-codec.version>1.11</commons-codec.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
1
algorithms/roundUpToHundred/.gitignore
vendored
Normal file
1
algorithms/roundUpToHundred/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
/bin/
|
@ -0,0 +1,20 @@
|
|||||||
|
package com.java.src;
|
||||||
|
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
public class RoundUpToHundred {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Scanner scanner = new Scanner(System.in);
|
||||||
|
double input = scanner.nextDouble();
|
||||||
|
scanner.close();
|
||||||
|
|
||||||
|
RoundUpToHundred.round(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
static long round(double input) {
|
||||||
|
long i = (long) Math.ceil(input);
|
||||||
|
return ((i + 99) / 100) * 100;
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,14 @@
|
|||||||
|
package com.java.src;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class RoundUpToHundredTest {
|
||||||
|
@Test
|
||||||
|
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
|
||||||
|
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
|
||||||
|
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
|
||||||
|
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
|
||||||
|
}
|
||||||
|
}
|
@ -17,6 +17,7 @@ public class RunAlgorithm {
|
|||||||
System.out.println("3 - Simple Genetic Algorithm");
|
System.out.println("3 - Simple Genetic Algorithm");
|
||||||
System.out.println("4 - Ant Colony");
|
System.out.println("4 - Ant Colony");
|
||||||
System.out.println("5 - Dijkstra");
|
System.out.println("5 - Dijkstra");
|
||||||
|
System.out.println("6 - All pairs in an array that add up to a given sum");
|
||||||
int decision = in.nextInt();
|
int decision = in.nextInt();
|
||||||
switch (decision) {
|
switch (decision) {
|
||||||
case 1:
|
case 1:
|
||||||
|
@ -0,0 +1,110 @@
|
|||||||
|
package com.baeldung.algorithms.conversion;
|
||||||
|
|
||||||
|
import java.math.BigInteger;
|
||||||
|
|
||||||
|
import javax.xml.bind.DatatypeConverter;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.DecoderException;
|
||||||
|
import org.apache.commons.codec.binary.Hex;
|
||||||
|
|
||||||
|
import com.google.common.io.BaseEncoding;
|
||||||
|
|
||||||
|
public class HexStringConverter {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a byte Array from String of hexadecimal digits using Character conversion
|
||||||
|
* @param hexString - Hexadecimal digits as String
|
||||||
|
* @return Desired byte Array
|
||||||
|
*/
|
||||||
|
public byte[] decodeHexString(String hexString) {
|
||||||
|
if (hexString.length() % 2 == 1) {
|
||||||
|
throw new IllegalArgumentException("Invalid hexadecimal String supplied.");
|
||||||
|
}
|
||||||
|
byte[] bytes = new byte[hexString.length() / 2];
|
||||||
|
|
||||||
|
for (int i = 0; i < hexString.length(); i += 2) {
|
||||||
|
bytes[i / 2] = hexToByte(hexString.substring(i, i + 2));
|
||||||
|
}
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a String of hexadecimal digits from a byte Array using Character conversion
|
||||||
|
* @param byteArray - The byte Array
|
||||||
|
* @return Desired String of hexadecimal digits in lower case
|
||||||
|
*/
|
||||||
|
public String encodeHexString(byte[] byteArray) {
|
||||||
|
StringBuffer hexStringBuffer = new StringBuffer();
|
||||||
|
for (int i = 0; i < byteArray.length; i++) {
|
||||||
|
hexStringBuffer.append(byteToHex(byteArray[i]));
|
||||||
|
}
|
||||||
|
return hexStringBuffer.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String byteToHex(byte num) {
|
||||||
|
char[] hexDigits = new char[2];
|
||||||
|
hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16);
|
||||||
|
hexDigits[1] = Character.forDigit((num & 0xF), 16);
|
||||||
|
return new String(hexDigits);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte hexToByte(String hexString) {
|
||||||
|
int firstDigit = toDigit(hexString.charAt(0));
|
||||||
|
int secondDigit = toDigit(hexString.charAt(1));
|
||||||
|
return (byte) ((firstDigit << 4) + secondDigit);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int toDigit(char hexChar) {
|
||||||
|
int digit = Character.digit(hexChar, 16);
|
||||||
|
if(digit == -1) {
|
||||||
|
throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar);
|
||||||
|
}
|
||||||
|
return digit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encodeUsingBigIntegerToString(byte[] bytes) {
|
||||||
|
BigInteger bigInteger = new BigInteger(1, bytes);
|
||||||
|
return bigInteger.toString(16);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encodeUsingBigIntegerStringFormat(byte[] bytes) {
|
||||||
|
BigInteger bigInteger = new BigInteger(1, bytes);
|
||||||
|
return String.format("%0" + (bytes.length << 1) + "x", bigInteger);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decodeUsingBigInteger(String hexString) {
|
||||||
|
byte[] byteArray = new BigInteger(hexString, 16).toByteArray();
|
||||||
|
if (byteArray[0] == 0) {
|
||||||
|
byte[] output = new byte[byteArray.length - 1];
|
||||||
|
System.arraycopy(byteArray, 1, output, 0, output.length);
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
return byteArray;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encodeUsingDataTypeConverter(byte[] bytes) {
|
||||||
|
return DatatypeConverter.printHexBinary(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decodeUsingDataTypeConverter(String hexString) {
|
||||||
|
return DatatypeConverter.parseHexBinary(hexString);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException {
|
||||||
|
return Hex.encodeHexString(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException {
|
||||||
|
return Hex.decodeHex(hexString);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String encodeUsingGuava(byte[] bytes) {
|
||||||
|
return BaseEncoding.base16()
|
||||||
|
.encode(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decodeUsingGuava(String hexString) {
|
||||||
|
return BaseEncoding.base16()
|
||||||
|
.decode(hexString.toUpperCase());
|
||||||
|
}
|
||||||
|
}
|
@ -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,136 @@
|
|||||||
|
package com.baeldung.algorithms.heapsort;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Heap<E extends Comparable<E>> {
|
||||||
|
|
||||||
|
private List<E> elements = new ArrayList<>();
|
||||||
|
|
||||||
|
public static <E extends Comparable<E>> List<E> sort(Iterable<E> elements) {
|
||||||
|
Heap<E> heap = of(elements);
|
||||||
|
|
||||||
|
List<E> result = new ArrayList<>();
|
||||||
|
|
||||||
|
while (!heap.isEmpty()) {
|
||||||
|
result.add(heap.pop());
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <E extends Comparable<E>> Heap<E> of(E... elements) {
|
||||||
|
return of(Arrays.asList(elements));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <E extends Comparable<E>> Heap<E> of(Iterable<E> elements) {
|
||||||
|
Heap<E> result = new Heap<>();
|
||||||
|
for (E element : elements) {
|
||||||
|
result.add(element);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void add(E e) {
|
||||||
|
elements.add(e);
|
||||||
|
int elementIndex = elements.size() - 1;
|
||||||
|
while (!isRoot(elementIndex) && !isCorrectChild(elementIndex)) {
|
||||||
|
int parentIndex = parentIndex(elementIndex);
|
||||||
|
swap(elementIndex, parentIndex);
|
||||||
|
elementIndex = parentIndex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public E pop() {
|
||||||
|
if (isEmpty()) {
|
||||||
|
throw new IllegalStateException("You cannot pop from an empty heap");
|
||||||
|
}
|
||||||
|
|
||||||
|
E result = elementAt(0);
|
||||||
|
|
||||||
|
int lasElementIndex = elements.size() - 1;
|
||||||
|
swap(0, lasElementIndex);
|
||||||
|
elements.remove(lasElementIndex);
|
||||||
|
|
||||||
|
int elementIndex = 0;
|
||||||
|
while (!isLeaf(elementIndex) && !isCorrectParent(elementIndex)) {
|
||||||
|
int smallerChildIndex = smallerChildIndex(elementIndex);
|
||||||
|
swap(elementIndex, smallerChildIndex);
|
||||||
|
elementIndex = smallerChildIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return elements.isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isRoot(int index) {
|
||||||
|
return index == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int smallerChildIndex(int index) {
|
||||||
|
int leftChildIndex = leftChildIndex(index);
|
||||||
|
int rightChildIndex = rightChildIndex(index);
|
||||||
|
|
||||||
|
if (!isValidIndex(rightChildIndex)) {
|
||||||
|
return leftChildIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (elementAt(leftChildIndex).compareTo(elementAt(rightChildIndex)) < 0) {
|
||||||
|
return leftChildIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
return rightChildIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isLeaf(int index) {
|
||||||
|
return !isValidIndex(leftChildIndex(index));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isCorrectParent(int index) {
|
||||||
|
return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isCorrectChild(int index) {
|
||||||
|
return isCorrect(parentIndex(index), index);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isCorrect(int parentIndex, int childIndex) {
|
||||||
|
if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isValidIndex(int index) {
|
||||||
|
return index < elements.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void swap(int index1, int index2) {
|
||||||
|
E element1 = elementAt(index1);
|
||||||
|
E element2 = elementAt(index2);
|
||||||
|
elements.set(index1, element2);
|
||||||
|
elements.set(index2, element1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private E elementAt(int index) {
|
||||||
|
return elements.get(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int parentIndex(int index) {
|
||||||
|
return (index - 1) / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int leftChildIndex(int index) {
|
||||||
|
return 2 * index + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int rightChildIndex(int index) {
|
||||||
|
return 2 * index + 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.algorithms.insertionsort;
|
||||||
|
|
||||||
|
public class InsertionSort {
|
||||||
|
|
||||||
|
public static void insertionSortImperative(int[] input) {
|
||||||
|
for (int i = 1; i < input.length; i++) {
|
||||||
|
int key = input[i];
|
||||||
|
int j = i - 1;
|
||||||
|
while (j >= 0 && input[j] > key) {
|
||||||
|
input[j + 1] = input[j];
|
||||||
|
j = j - 1;
|
||||||
|
}
|
||||||
|
input[j + 1] = key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void insertionSortRecursive(int[] input) {
|
||||||
|
insertionSortRecursive(input, input.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void insertionSortRecursive(int[] input, int i) {
|
||||||
|
// base case
|
||||||
|
if (i <= 1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// sort the first i - 1 elements of the array
|
||||||
|
insertionSortRecursive(input, i - 1);
|
||||||
|
|
||||||
|
// then find the correct position of the element at position i
|
||||||
|
int key = input[i - 1];
|
||||||
|
int j = i - 2;
|
||||||
|
// shifting the elements from their position by 1
|
||||||
|
while (j >= 0 && input[j] > key) {
|
||||||
|
input[j + 1] = input[j];
|
||||||
|
j = j - 1;
|
||||||
|
}
|
||||||
|
// inserting the key at the appropriate position
|
||||||
|
input[j + 1] = key;
|
||||||
|
}
|
||||||
|
}
|
@ -98,7 +98,7 @@ public class FindKthLargest {
|
|||||||
|
|
||||||
private int randomPartition(Integer arr[], int left, int right) {
|
private int randomPartition(Integer arr[], int left, int right) {
|
||||||
int n = right - left + 1;
|
int n = right - left + 1;
|
||||||
int pivot = (int) (Math.random()) % n;
|
int pivot = (int) (Math.random() * n);
|
||||||
swap(arr, left + pivot, right);
|
swap(arr, left + pivot, right);
|
||||||
return partition(arr, left, right);
|
return partition(arr, left, right);
|
||||||
}
|
}
|
||||||
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,52 @@
|
|||||||
|
package com.baeldung.algorithms.maze.solver;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class BFSMazeSolver {
|
||||||
|
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
|
||||||
|
|
||||||
|
public List<Coordinate> solve(Maze maze) {
|
||||||
|
LinkedList<Coordinate> nextToVisit = new LinkedList<>();
|
||||||
|
Coordinate start = maze.getEntry();
|
||||||
|
nextToVisit.add(start);
|
||||||
|
|
||||||
|
while (!nextToVisit.isEmpty()) {
|
||||||
|
Coordinate cur = nextToVisit.remove();
|
||||||
|
|
||||||
|
if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maze.isWall(cur.getX(), cur.getY())) {
|
||||||
|
maze.setVisited(cur.getX(), cur.getY(), true);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maze.isExit(cur.getX(), cur.getY())) {
|
||||||
|
return backtrackPath(cur);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int[] direction : DIRECTIONS) {
|
||||||
|
Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur);
|
||||||
|
nextToVisit.add(coordinate);
|
||||||
|
maze.setVisited(cur.getX(), cur.getY(), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Coordinate> backtrackPath(Coordinate cur) {
|
||||||
|
List<Coordinate> path = new ArrayList<>();
|
||||||
|
Coordinate iter = cur;
|
||||||
|
|
||||||
|
while (iter != null) {
|
||||||
|
path.add(iter);
|
||||||
|
iter = iter.parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,31 @@
|
|||||||
|
package com.baeldung.algorithms.maze.solver;
|
||||||
|
|
||||||
|
public class Coordinate {
|
||||||
|
int x;
|
||||||
|
int y;
|
||||||
|
Coordinate parent;
|
||||||
|
|
||||||
|
public Coordinate(int x, int y) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
this.parent = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Coordinate(int x, int y, Coordinate parent) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
this.parent = parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
int getX() {
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
int getY() {
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
|
||||||
|
Coordinate getParent() {
|
||||||
|
return parent;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.algorithms.maze.solver;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class DFSMazeSolver {
|
||||||
|
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
|
||||||
|
|
||||||
|
public List<Coordinate> solve(Maze maze) {
|
||||||
|
List<Coordinate> path = new ArrayList<>();
|
||||||
|
if (explore(maze, maze.getEntry()
|
||||||
|
.getX(),
|
||||||
|
maze.getEntry()
|
||||||
|
.getY(),
|
||||||
|
path)) {
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean explore(Maze maze, int row, int col, List<Coordinate> path) {
|
||||||
|
if (!maze.isValidLocation(row, col) || maze.isWall(row, col) || maze.isExplored(row, col)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
path.add(new Coordinate(row, col));
|
||||||
|
maze.setVisited(row, col, true);
|
||||||
|
|
||||||
|
if (maze.isExit(row, col)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int[] direction : DIRECTIONS) {
|
||||||
|
Coordinate coordinate = getNextCoordinate(row, col, direction[0], direction[1]);
|
||||||
|
if (explore(maze, coordinate.getX(), coordinate.getY(), path)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
path.remove(path.size() - 1);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Coordinate getNextCoordinate(int row, int col, int i, int j) {
|
||||||
|
return new Coordinate(row + i, col + j);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,141 @@
|
|||||||
|
package com.baeldung.algorithms.maze.solver;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
public class Maze {
|
||||||
|
private static final int ROAD = 0;
|
||||||
|
private static final int WALL = 1;
|
||||||
|
private static final int START = 2;
|
||||||
|
private static final int EXIT = 3;
|
||||||
|
private static final int PATH = 4;
|
||||||
|
|
||||||
|
private int[][] maze;
|
||||||
|
private boolean[][] visited;
|
||||||
|
private Coordinate start;
|
||||||
|
private Coordinate end;
|
||||||
|
|
||||||
|
public Maze(File maze) throws FileNotFoundException {
|
||||||
|
String fileText = "";
|
||||||
|
try (Scanner input = new Scanner(maze)) {
|
||||||
|
while (input.hasNextLine()) {
|
||||||
|
fileText += input.nextLine() + "\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
initializeMaze(fileText);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void initializeMaze(String text) {
|
||||||
|
if (text == null || (text = text.trim()).length() == 0) {
|
||||||
|
throw new IllegalArgumentException("empty lines data");
|
||||||
|
}
|
||||||
|
|
||||||
|
String[] lines = text.split("[\r]?\n");
|
||||||
|
maze = new int[lines.length][lines[0].length()];
|
||||||
|
visited = new boolean[lines.length][lines[0].length()];
|
||||||
|
|
||||||
|
for (int row = 0; row < getHeight(); row++) {
|
||||||
|
if (lines[row].length() != getWidth()) {
|
||||||
|
throw new IllegalArgumentException("line " + (row + 1) + " wrong length (was " + lines[row].length() + " but should be " + getWidth() + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int col = 0; col < getWidth(); col++) {
|
||||||
|
if (lines[row].charAt(col) == '#')
|
||||||
|
maze[row][col] = WALL;
|
||||||
|
else if (lines[row].charAt(col) == 'S') {
|
||||||
|
maze[row][col] = START;
|
||||||
|
start = new Coordinate(row, col);
|
||||||
|
} else if (lines[row].charAt(col) == 'E') {
|
||||||
|
maze[row][col] = EXIT;
|
||||||
|
end = new Coordinate(row, col);
|
||||||
|
} else
|
||||||
|
maze[row][col] = ROAD;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getHeight() {
|
||||||
|
return maze.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getWidth() {
|
||||||
|
return maze[0].length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Coordinate getEntry() {
|
||||||
|
return start;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Coordinate getExit() {
|
||||||
|
return end;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isExit(int x, int y) {
|
||||||
|
return x == end.getX() && y == end.getY();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isStart(int x, int y) {
|
||||||
|
return x == start.getX() && y == start.getY();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isExplored(int row, int col) {
|
||||||
|
return visited[row][col];
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isWall(int row, int col) {
|
||||||
|
return maze[row][col] == WALL;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setVisited(int row, int col, boolean value) {
|
||||||
|
visited[row][col] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isValidLocation(int row, int col) {
|
||||||
|
if (row < 0 || row >= getHeight() || col < 0 || col >= getWidth()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void printPath(List<Coordinate> path) {
|
||||||
|
int[][] tempMaze = Arrays.stream(maze)
|
||||||
|
.map(int[]::clone)
|
||||||
|
.toArray(int[][]::new);
|
||||||
|
for (Coordinate coordinate : path) {
|
||||||
|
if (isStart(coordinate.getX(), coordinate.getY()) || isExit(coordinate.getX(), coordinate.getY())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
tempMaze[coordinate.getX()][coordinate.getY()] = PATH;
|
||||||
|
}
|
||||||
|
System.out.println(toString(tempMaze));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String toString(int[][] maze) {
|
||||||
|
StringBuilder result = new StringBuilder(getWidth() * (getHeight() + 1));
|
||||||
|
for (int row = 0; row < getHeight(); row++) {
|
||||||
|
for (int col = 0; col < getWidth(); col++) {
|
||||||
|
if (maze[row][col] == ROAD) {
|
||||||
|
result.append(' ');
|
||||||
|
} else if (maze[row][col] == WALL) {
|
||||||
|
result.append('#');
|
||||||
|
} else if (maze[row][col] == START) {
|
||||||
|
result.append('S');
|
||||||
|
} else if (maze[row][col] == EXIT) {
|
||||||
|
result.append('E');
|
||||||
|
} else {
|
||||||
|
result.append('.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.append('\n');
|
||||||
|
}
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void reset() {
|
||||||
|
for (int i = 0; i < visited.length; i++)
|
||||||
|
Arrays.fill(visited[i], false);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package com.baeldung.algorithms.maze.solver;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class MazeDriver {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
File maze1 = new File("src/main/resources/maze/maze1.txt");
|
||||||
|
File maze2 = new File("src/main/resources/maze/maze2.txt");
|
||||||
|
|
||||||
|
execute(maze1);
|
||||||
|
execute(maze2);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void execute(File file) throws Exception {
|
||||||
|
Maze maze = new Maze(file);
|
||||||
|
dfs(maze);
|
||||||
|
bfs(maze);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void bfs(Maze maze) {
|
||||||
|
BFSMazeSolver bfs = new BFSMazeSolver();
|
||||||
|
List<Coordinate> path = bfs.solve(maze);
|
||||||
|
maze.printPath(path);
|
||||||
|
maze.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void dfs(Maze maze) {
|
||||||
|
DFSMazeSolver dfs = new DFSMazeSolver();
|
||||||
|
List<Coordinate> path = dfs.solve(maze);
|
||||||
|
maze.printPath(path);
|
||||||
|
maze.reset();
|
||||||
|
}
|
||||||
|
}
|
@ -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,50 @@
|
|||||||
|
package com.baeldung.algorithms.mergesort;
|
||||||
|
|
||||||
|
public class MergeSort {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int[] a = { 5, 1, 6, 2, 3, 4 };
|
||||||
|
mergeSort(a, a.length);
|
||||||
|
for (int i = 0; i < a.length; i++)
|
||||||
|
System.out.println(a[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void mergeSort(int[] a, int n) {
|
||||||
|
if (n < 2)
|
||||||
|
return;
|
||||||
|
int mid = n / 2;
|
||||||
|
int[] l = new int[mid];
|
||||||
|
int[] r = new int[n - mid];
|
||||||
|
|
||||||
|
for (int i = 0; i < mid; i++) {
|
||||||
|
l[i] = a[i];
|
||||||
|
}
|
||||||
|
for (int i = mid; i < n; i++) {
|
||||||
|
r[i - mid] = a[i];
|
||||||
|
}
|
||||||
|
mergeSort(l, mid);
|
||||||
|
mergeSort(r, n - mid);
|
||||||
|
|
||||||
|
merge(a, l, r, mid, n - mid);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
|
||||||
|
|
||||||
|
int i = 0, j = 0, k = 0;
|
||||||
|
|
||||||
|
while (i < left && j < right) {
|
||||||
|
|
||||||
|
if (l[i] < r[j])
|
||||||
|
a[k++] = l[i++];
|
||||||
|
else
|
||||||
|
a[k++] = r[j++];
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
while (i < left)
|
||||||
|
a[k++] = l[i++];
|
||||||
|
|
||||||
|
while (j < right)
|
||||||
|
a[k++] = r[j++];
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
package com.baeldung.algorithms.multiswarm;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constants used by the Multi-swarm optimization algorithms.
|
||||||
|
*
|
||||||
|
* @author Donato Rimenti
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class Constants {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The inertia factor encourages a particle to continue moving in its
|
||||||
|
* current direction.
|
||||||
|
*/
|
||||||
|
public static final double INERTIA_FACTOR = 0.729;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The cognitive weight encourages a particle to move toward its historical
|
||||||
|
* best-known position.
|
||||||
|
*/
|
||||||
|
public static final double COGNITIVE_WEIGHT = 1.49445;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The social weight encourages a particle to move toward the best-known
|
||||||
|
* position found by any of the particle’s swarm-mates.
|
||||||
|
*/
|
||||||
|
public static final double SOCIAL_WEIGHT = 1.49445;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The global weight encourages a particle to move toward the best-known
|
||||||
|
* position found by any particle in any swarm.
|
||||||
|
*/
|
||||||
|
public static final double GLOBAL_WEIGHT = 0.3645;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upper bound for the random generation. We use it to reduce the
|
||||||
|
* computation time since we can rawly estimate it.
|
||||||
|
*/
|
||||||
|
public static final int PARTICLE_UPPER_BOUND = 10000000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Private constructor for utility class.
|
||||||
|
*/
|
||||||
|
private Constants() {
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.algorithms.multiswarm;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface for a fitness function, used to decouple the main algorithm logic
|
||||||
|
* from the specific problem solution.
|
||||||
|
*
|
||||||
|
* @author Donato Rimenti
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public interface FitnessFunction {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the fitness of a particle given its position.
|
||||||
|
*
|
||||||
|
* @param particlePosition
|
||||||
|
* the position of the particle
|
||||||
|
* @return the fitness of the particle
|
||||||
|
*/
|
||||||
|
public double getFitness(long[] particlePosition);
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,227 @@
|
|||||||
|
package com.baeldung.algorithms.multiswarm;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a collection of {@link Swarm}.
|
||||||
|
*
|
||||||
|
* @author Donato Rimenti
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class Multiswarm {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The swarms managed by this multiswarm.
|
||||||
|
*/
|
||||||
|
private Swarm[] swarms;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The best position found within all the {@link #swarms}.
|
||||||
|
*/
|
||||||
|
private long[] bestPosition;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The best fitness score found within all the {@link #swarms}.
|
||||||
|
*/
|
||||||
|
private double bestFitness = Double.NEGATIVE_INFINITY;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A random generator.
|
||||||
|
*/
|
||||||
|
private Random random = new Random();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The fitness function used to determine how good is a particle.
|
||||||
|
*/
|
||||||
|
private FitnessFunction fitnessFunction;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Instantiates a new Multiswarm.
|
||||||
|
*
|
||||||
|
* @param numSwarms
|
||||||
|
* the number of {@link #swarms}
|
||||||
|
* @param particlesPerSwarm
|
||||||
|
* the number of particle for each {@link #swarms}
|
||||||
|
* @param fitnessFunction
|
||||||
|
* the {@link #fitnessFunction}
|
||||||
|
*/
|
||||||
|
public Multiswarm(int numSwarms, int particlesPerSwarm, FitnessFunction fitnessFunction) {
|
||||||
|
this.fitnessFunction = fitnessFunction;
|
||||||
|
this.swarms = new Swarm[numSwarms];
|
||||||
|
for (int i = 0; i < numSwarms; i++) {
|
||||||
|
swarms[i] = new Swarm(particlesPerSwarm);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main loop of the algorithm. Iterates all particles of all
|
||||||
|
* {@link #swarms}. For each particle, computes the new fitness and checks
|
||||||
|
* if a new best position has been found among itself, the swarm and all the
|
||||||
|
* swarms and finally updates the particle position and speed.
|
||||||
|
*/
|
||||||
|
public void mainLoop() {
|
||||||
|
for (Swarm swarm : swarms) {
|
||||||
|
for (Particle particle : swarm.getParticles()) {
|
||||||
|
|
||||||
|
long[] particleOldPosition = particle.getPosition().clone();
|
||||||
|
|
||||||
|
// Calculate the particle fitness.
|
||||||
|
particle.setFitness(fitnessFunction.getFitness(particleOldPosition));
|
||||||
|
|
||||||
|
// Check if a new best position has been found for the particle
|
||||||
|
// itself, within the swarm and the multiswarm.
|
||||||
|
if (particle.getFitness() > particle.getBestFitness()) {
|
||||||
|
particle.setBestFitness(particle.getFitness());
|
||||||
|
particle.setBestPosition(particleOldPosition);
|
||||||
|
|
||||||
|
if (particle.getFitness() > swarm.getBestFitness()) {
|
||||||
|
swarm.setBestFitness(particle.getFitness());
|
||||||
|
swarm.setBestPosition(particleOldPosition);
|
||||||
|
|
||||||
|
if (swarm.getBestFitness() > bestFitness) {
|
||||||
|
bestFitness = swarm.getBestFitness();
|
||||||
|
bestPosition = swarm.getBestPosition().clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Updates the particle position by adding the speed to the
|
||||||
|
// actual position.
|
||||||
|
long[] position = particle.getPosition();
|
||||||
|
long[] speed = particle.getSpeed();
|
||||||
|
|
||||||
|
position[0] += speed[0];
|
||||||
|
position[1] += speed[1];
|
||||||
|
|
||||||
|
// Updates the particle speed.
|
||||||
|
speed[0] = getNewParticleSpeedForIndex(particle, swarm, 0);
|
||||||
|
speed[1] = getNewParticleSpeedForIndex(particle, swarm, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes a new speed for a given particle of a given swarm on a given
|
||||||
|
* axis. The new speed is computed using the formula:
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* ({@link Constants#INERTIA_FACTOR} * {@link Particle#getSpeed()}) +
|
||||||
|
* (({@link Constants#COGNITIVE_WEIGHT} * random(0,1)) * ({@link Particle#getBestPosition()} - {@link Particle#getPosition()})) +
|
||||||
|
* (({@link Constants#SOCIAL_WEIGHT} * random(0,1)) * ({@link Swarm#getBestPosition()} - {@link Particle#getPosition()})) +
|
||||||
|
* (({@link Constants#GLOBAL_WEIGHT} * random(0,1)) * ({@link #bestPosition} - {@link Particle#getPosition()}))
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @param particle
|
||||||
|
* the particle whose new speed needs to be computed
|
||||||
|
* @param swarm
|
||||||
|
* the swarm which contains the particle
|
||||||
|
* @param index
|
||||||
|
* the index of the particle axis whose speeds needs to be
|
||||||
|
* computed
|
||||||
|
* @return the new speed of the particle passed on the given axis
|
||||||
|
*/
|
||||||
|
private int getNewParticleSpeedForIndex(Particle particle, Swarm swarm, int index) {
|
||||||
|
return (int) ((Constants.INERTIA_FACTOR * particle.getSpeed()[index])
|
||||||
|
+ (randomizePercentage(Constants.COGNITIVE_WEIGHT)
|
||||||
|
* (particle.getBestPosition()[index] - particle.getPosition()[index]))
|
||||||
|
+ (randomizePercentage(Constants.SOCIAL_WEIGHT)
|
||||||
|
* (swarm.getBestPosition()[index] - particle.getPosition()[index]))
|
||||||
|
+ (randomizePercentage(Constants.GLOBAL_WEIGHT)
|
||||||
|
* (bestPosition[index] - particle.getPosition()[index])));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a random number between 0 and the value passed as argument.
|
||||||
|
*
|
||||||
|
* @param value
|
||||||
|
* the value to randomize
|
||||||
|
* @return a random value between 0 and the one passed as argument
|
||||||
|
*/
|
||||||
|
private double randomizePercentage(double value) {
|
||||||
|
return random.nextDouble() * value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link #bestPosition}.
|
||||||
|
*
|
||||||
|
* @return the {@link #bestPosition}
|
||||||
|
*/
|
||||||
|
public long[] getBestPosition() {
|
||||||
|
return bestPosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link #bestFitness}.
|
||||||
|
*
|
||||||
|
* @return the {@link #bestFitness}
|
||||||
|
*/
|
||||||
|
public double getBestFitness() {
|
||||||
|
return bestFitness;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* (non-Javadoc)
|
||||||
|
*
|
||||||
|
* @see java.lang.Object#hashCode()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
long temp;
|
||||||
|
temp = Double.doubleToLongBits(bestFitness);
|
||||||
|
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||||
|
result = prime * result + Arrays.hashCode(bestPosition);
|
||||||
|
result = prime * result + ((fitnessFunction == null) ? 0 : fitnessFunction.hashCode());
|
||||||
|
result = prime * result + ((random == null) ? 0 : random.hashCode());
|
||||||
|
result = prime * result + Arrays.hashCode(swarms);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* (non-Javadoc)
|
||||||
|
*
|
||||||
|
* @see java.lang.Object#equals(java.lang.Object)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
Multiswarm other = (Multiswarm) obj;
|
||||||
|
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
|
||||||
|
return false;
|
||||||
|
if (!Arrays.equals(bestPosition, other.bestPosition))
|
||||||
|
return false;
|
||||||
|
if (fitnessFunction == null) {
|
||||||
|
if (other.fitnessFunction != null)
|
||||||
|
return false;
|
||||||
|
} else if (!fitnessFunction.equals(other.fitnessFunction))
|
||||||
|
return false;
|
||||||
|
if (random == null) {
|
||||||
|
if (other.random != null)
|
||||||
|
return false;
|
||||||
|
} else if (!random.equals(other.random))
|
||||||
|
return false;
|
||||||
|
if (!Arrays.equals(swarms, other.swarms))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* (non-Javadoc)
|
||||||
|
*
|
||||||
|
* @see java.lang.Object#toString()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Multiswarm [swarms=" + Arrays.toString(swarms) + ", bestPosition=" + Arrays.toString(bestPosition)
|
||||||
|
+ ", bestFitness=" + bestFitness + ", random=" + random + ", fitnessFunction=" + fitnessFunction + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,204 @@
|
|||||||
|
package com.baeldung.algorithms.multiswarm;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a particle, the basic component of a {@link Swarm}.
|
||||||
|
*
|
||||||
|
* @author Donato Rimenti
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class Particle {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The current position of this particle.
|
||||||
|
*/
|
||||||
|
private long[] position;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The speed of this particle.
|
||||||
|
*/
|
||||||
|
private long[] speed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The fitness of this particle for the current position.
|
||||||
|
*/
|
||||||
|
private double fitness;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The best position found by this particle.
|
||||||
|
*/
|
||||||
|
private long[] bestPosition;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The best fitness found by this particle.
|
||||||
|
*/
|
||||||
|
private double bestFitness = Double.NEGATIVE_INFINITY;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Instantiates a new Particle.
|
||||||
|
*
|
||||||
|
* @param initialPosition
|
||||||
|
* the initial {@link #position}
|
||||||
|
* @param initialSpeed
|
||||||
|
* the initial {@link #speed}
|
||||||
|
*/
|
||||||
|
public Particle(long[] initialPosition, long[] initialSpeed) {
|
||||||
|
this.position = initialPosition;
|
||||||
|
this.speed = initialSpeed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link #position}.
|
||||||
|
*
|
||||||
|
* @return the {@link #position}
|
||||||
|
*/
|
||||||
|
public long[] getPosition() {
|
||||||
|
return position;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link #speed}.
|
||||||
|
*
|
||||||
|
* @return the {@link #speed}
|
||||||
|
*/
|
||||||
|
public long[] getSpeed() {
|
||||||
|
return speed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link #fitness}.
|
||||||
|
*
|
||||||
|
* @return the {@link #fitness}
|
||||||
|
*/
|
||||||
|
public double getFitness() {
|
||||||
|
return fitness;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link #bestPosition}.
|
||||||
|
*
|
||||||
|
* @return the {@link #bestPosition}
|
||||||
|
*/
|
||||||
|
public long[] getBestPosition() {
|
||||||
|
return bestPosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link #bestFitness}.
|
||||||
|
*
|
||||||
|
* @return the {@link #bestFitness}
|
||||||
|
*/
|
||||||
|
public double getBestFitness() {
|
||||||
|
return bestFitness;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the {@link #position}.
|
||||||
|
*
|
||||||
|
* @param position
|
||||||
|
* the new {@link #position}
|
||||||
|
*/
|
||||||
|
public void setPosition(long[] position) {
|
||||||
|
this.position = position;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the {@link #speed}.
|
||||||
|
*
|
||||||
|
* @param speed
|
||||||
|
* the new {@link #speed}
|
||||||
|
*/
|
||||||
|
public void setSpeed(long[] speed) {
|
||||||
|
this.speed = speed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the {@link #fitness}.
|
||||||
|
*
|
||||||
|
* @param fitness
|
||||||
|
* the new {@link #fitness}
|
||||||
|
*/
|
||||||
|
public void setFitness(double fitness) {
|
||||||
|
this.fitness = fitness;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the {@link #bestPosition}.
|
||||||
|
*
|
||||||
|
* @param bestPosition
|
||||||
|
* the new {@link #bestPosition}
|
||||||
|
*/
|
||||||
|
public void setBestPosition(long[] bestPosition) {
|
||||||
|
this.bestPosition = bestPosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the {@link #bestFitness}.
|
||||||
|
*
|
||||||
|
* @param bestFitness
|
||||||
|
* the new {@link #bestFitness}
|
||||||
|
*/
|
||||||
|
public void setBestFitness(double bestFitness) {
|
||||||
|
this.bestFitness = bestFitness;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* (non-Javadoc)
|
||||||
|
*
|
||||||
|
* @see java.lang.Object#hashCode()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
long temp;
|
||||||
|
temp = Double.doubleToLongBits(bestFitness);
|
||||||
|
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||||
|
result = prime * result + Arrays.hashCode(bestPosition);
|
||||||
|
temp = Double.doubleToLongBits(fitness);
|
||||||
|
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||||
|
result = prime * result + Arrays.hashCode(position);
|
||||||
|
result = prime * result + Arrays.hashCode(speed);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* (non-Javadoc)
|
||||||
|
*
|
||||||
|
* @see java.lang.Object#equals(java.lang.Object)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
Particle other = (Particle) obj;
|
||||||
|
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
|
||||||
|
return false;
|
||||||
|
if (!Arrays.equals(bestPosition, other.bestPosition))
|
||||||
|
return false;
|
||||||
|
if (Double.doubleToLongBits(fitness) != Double.doubleToLongBits(other.fitness))
|
||||||
|
return false;
|
||||||
|
if (!Arrays.equals(position, other.position))
|
||||||
|
return false;
|
||||||
|
if (!Arrays.equals(speed, other.speed))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* (non-Javadoc)
|
||||||
|
*
|
||||||
|
* @see java.lang.Object#toString()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Particle [position=" + Arrays.toString(position) + ", speed=" + Arrays.toString(speed) + ", fitness="
|
||||||
|
+ fitness + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,155 @@
|
|||||||
|
package com.baeldung.algorithms.multiswarm;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a collection of {@link Particle}.
|
||||||
|
*
|
||||||
|
* @author Donato Rimenti
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public class Swarm {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The particles of this swarm.
|
||||||
|
*/
|
||||||
|
private Particle[] particles;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The best position found within the particles of this swarm.
|
||||||
|
*/
|
||||||
|
private long[] bestPosition;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The best fitness score found within the particles of this swarm.
|
||||||
|
*/
|
||||||
|
private double bestFitness = Double.NEGATIVE_INFINITY;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A random generator.
|
||||||
|
*/
|
||||||
|
private Random random = new Random();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Instantiates a new Swarm.
|
||||||
|
*
|
||||||
|
* @param numParticles
|
||||||
|
* the number of particles of the swarm
|
||||||
|
*/
|
||||||
|
public Swarm(int numParticles) {
|
||||||
|
particles = new Particle[numParticles];
|
||||||
|
for (int i = 0; i < numParticles; i++) {
|
||||||
|
long[] initialParticlePosition = { random.nextInt(Constants.PARTICLE_UPPER_BOUND),
|
||||||
|
random.nextInt(Constants.PARTICLE_UPPER_BOUND) };
|
||||||
|
long[] initialParticleSpeed = { random.nextInt(Constants.PARTICLE_UPPER_BOUND),
|
||||||
|
random.nextInt(Constants.PARTICLE_UPPER_BOUND) };
|
||||||
|
particles[i] = new Particle(initialParticlePosition, initialParticleSpeed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link #particles}.
|
||||||
|
*
|
||||||
|
* @return the {@link #particles}
|
||||||
|
*/
|
||||||
|
public Particle[] getParticles() {
|
||||||
|
return particles;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link #bestPosition}.
|
||||||
|
*
|
||||||
|
* @return the {@link #bestPosition}
|
||||||
|
*/
|
||||||
|
public long[] getBestPosition() {
|
||||||
|
return bestPosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the {@link #bestFitness}.
|
||||||
|
*
|
||||||
|
* @return the {@link #bestFitness}
|
||||||
|
*/
|
||||||
|
public double getBestFitness() {
|
||||||
|
return bestFitness;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the {@link #bestPosition}.
|
||||||
|
*
|
||||||
|
* @param bestPosition
|
||||||
|
* the new {@link #bestPosition}
|
||||||
|
*/
|
||||||
|
public void setBestPosition(long[] bestPosition) {
|
||||||
|
this.bestPosition = bestPosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the {@link #bestFitness}.
|
||||||
|
*
|
||||||
|
* @param bestFitness
|
||||||
|
* the new {@link #bestFitness}
|
||||||
|
*/
|
||||||
|
public void setBestFitness(double bestFitness) {
|
||||||
|
this.bestFitness = bestFitness;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* (non-Javadoc)
|
||||||
|
*
|
||||||
|
* @see java.lang.Object#hashCode()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
final int prime = 31;
|
||||||
|
int result = 1;
|
||||||
|
long temp;
|
||||||
|
temp = Double.doubleToLongBits(bestFitness);
|
||||||
|
result = prime * result + (int) (temp ^ (temp >>> 32));
|
||||||
|
result = prime * result + Arrays.hashCode(bestPosition);
|
||||||
|
result = prime * result + Arrays.hashCode(particles);
|
||||||
|
result = prime * result + ((random == null) ? 0 : random.hashCode());
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* (non-Javadoc)
|
||||||
|
*
|
||||||
|
* @see java.lang.Object#equals(java.lang.Object)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
if (this == obj)
|
||||||
|
return true;
|
||||||
|
if (obj == null)
|
||||||
|
return false;
|
||||||
|
if (getClass() != obj.getClass())
|
||||||
|
return false;
|
||||||
|
Swarm other = (Swarm) obj;
|
||||||
|
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
|
||||||
|
return false;
|
||||||
|
if (!Arrays.equals(bestPosition, other.bestPosition))
|
||||||
|
return false;
|
||||||
|
if (!Arrays.equals(particles, other.particles))
|
||||||
|
return false;
|
||||||
|
if (random == null) {
|
||||||
|
if (other.random != null)
|
||||||
|
return false;
|
||||||
|
} else if (!random.equals(other.random))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* (non-Javadoc)
|
||||||
|
*
|
||||||
|
* @see java.lang.Object#toString()
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Swarm [particles=" + Arrays.toString(particles) + ", bestPosition=" + Arrays.toString(bestPosition)
|
||||||
|
+ ", bestFitness=" + bestFitness + ", random=" + random + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,75 @@
|
|||||||
|
package com.baeldung.algorithms.numberwordconverter;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
import pl.allegro.finance.tradukisto.MoneyConverters;
|
||||||
|
|
||||||
|
public class NumberWordConverter {
|
||||||
|
|
||||||
|
public static final String INVALID_INPUT_GIVEN = "Invalid input given";
|
||||||
|
|
||||||
|
public static final String[] ones = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
|
||||||
|
|
||||||
|
public static final String[] tens = {
|
||||||
|
"", // 0
|
||||||
|
"", // 1
|
||||||
|
"twenty", // 2
|
||||||
|
"thirty", // 3
|
||||||
|
"forty", // 4
|
||||||
|
"fifty", // 5
|
||||||
|
"sixty", // 6
|
||||||
|
"seventy", // 7
|
||||||
|
"eighty", // 8
|
||||||
|
"ninety" // 9
|
||||||
|
};
|
||||||
|
|
||||||
|
public static String getMoneyIntoWords(String input) {
|
||||||
|
MoneyConverters converter = MoneyConverters.ENGLISH_BANKING_MONEY_VALUE;
|
||||||
|
return converter.asWords(new BigDecimal(input));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getMoneyIntoWords(final double money) {
|
||||||
|
long dollar = (long) money;
|
||||||
|
long cents = Math.round((money - dollar) * 100);
|
||||||
|
if (money == 0D) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if (money < 0) {
|
||||||
|
return INVALID_INPUT_GIVEN;
|
||||||
|
}
|
||||||
|
String dollarPart = "";
|
||||||
|
if (dollar > 0) {
|
||||||
|
dollarPart = convert(dollar) + " dollar" + (dollar == 1 ? "" : "s");
|
||||||
|
}
|
||||||
|
String centsPart = "";
|
||||||
|
if (cents > 0) {
|
||||||
|
if (dollarPart.length() > 0) {
|
||||||
|
centsPart = " and ";
|
||||||
|
}
|
||||||
|
centsPart += convert(cents) + " cent" + (cents == 1 ? "" : "s");
|
||||||
|
}
|
||||||
|
return dollarPart + centsPart;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String convert(final long n) {
|
||||||
|
if (n < 0) {
|
||||||
|
return INVALID_INPUT_GIVEN;
|
||||||
|
}
|
||||||
|
if (n < 20) {
|
||||||
|
return ones[(int) n];
|
||||||
|
}
|
||||||
|
if (n < 100) {
|
||||||
|
return tens[(int) n / 10] + ((n % 10 != 0) ? " " : "") + ones[(int) n % 10];
|
||||||
|
}
|
||||||
|
if (n < 1000) {
|
||||||
|
return ones[(int) n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
|
||||||
|
}
|
||||||
|
if (n < 1_000_000) {
|
||||||
|
return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000);
|
||||||
|
}
|
||||||
|
if (n < 1_000_000_000) {
|
||||||
|
return convert(n / 1_000_000) + " million" + ((n % 1_000_000 != 0) ? " " : "") + convert(n % 1_000_000);
|
||||||
|
}
|
||||||
|
return convert(n / 1_000_000_000) + " billion" + ((n % 1_000_000_000 != 0) ? " " : "") + convert(n % 1_000_000_000);
|
||||||
|
}
|
||||||
|
}
|
@ -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,39 @@
|
|||||||
|
package com.baeldung.algorithms.quicksort;
|
||||||
|
|
||||||
|
public class QuickSort {
|
||||||
|
|
||||||
|
public static void quickSort(int arr[], int begin, int end)
|
||||||
|
{
|
||||||
|
if (begin < end) {
|
||||||
|
int partitionIndex = partition(arr, begin, end);
|
||||||
|
|
||||||
|
// Recursively sort elements of the 2 sub-arrays
|
||||||
|
quickSort(arr, begin, partitionIndex-1);
|
||||||
|
quickSort(arr, partitionIndex+1, end);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int partition(int arr[], int begin, int end)
|
||||||
|
{
|
||||||
|
int pivot = arr[end];
|
||||||
|
int i = (begin-1);
|
||||||
|
|
||||||
|
for (int j=begin; j<end; j++)
|
||||||
|
{
|
||||||
|
if (arr[j] <= pivot) {
|
||||||
|
i++;
|
||||||
|
|
||||||
|
int swapTemp = arr[i];
|
||||||
|
arr[i] = arr[j];
|
||||||
|
arr[j] = swapTemp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int swapTemp = arr[i+1];
|
||||||
|
arr[i+1] = arr[end];
|
||||||
|
arr[end] = swapTemp;
|
||||||
|
|
||||||
|
return i+1;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.algorithms.quicksort;
|
||||||
|
|
||||||
|
public class ThreeWayQuickSort {
|
||||||
|
|
||||||
|
public static void threeWayQuickSort(int[] a, int begin, int end)
|
||||||
|
{
|
||||||
|
if (end <= begin) return;
|
||||||
|
|
||||||
|
// partition
|
||||||
|
int i = begin;
|
||||||
|
int less = begin;
|
||||||
|
int greater = end;
|
||||||
|
|
||||||
|
while (i <= greater){
|
||||||
|
if (a[i] < a[less]) {
|
||||||
|
int tmp = a[i];
|
||||||
|
a[i] = a[less];
|
||||||
|
a[less] = tmp;
|
||||||
|
|
||||||
|
i++;
|
||||||
|
less++;
|
||||||
|
}
|
||||||
|
else if (a[less] < a[i]) {
|
||||||
|
int tmp = a[i];
|
||||||
|
a[i] = a[greater];
|
||||||
|
a[greater] = tmp;
|
||||||
|
|
||||||
|
greater--;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
threeWayQuickSort(a, begin, less - 1);
|
||||||
|
threeWayQuickSort(a, greater + 1, end);
|
||||||
|
}
|
||||||
|
}
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,104 @@
|
|||||||
|
package com.baeldung.algorithms.sudoku;
|
||||||
|
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
public class BacktrackingAlgorithm {
|
||||||
|
|
||||||
|
private static final int BOARD_SIZE = 9;
|
||||||
|
private static final int SUBSECTION_SIZE = 3;
|
||||||
|
private static final int BOARD_START_INDEX = 0;
|
||||||
|
|
||||||
|
private static final int NO_VALUE = 0;
|
||||||
|
private static final int MIN_VALUE = 1;
|
||||||
|
private static final int MAX_VALUE = 9;
|
||||||
|
|
||||||
|
private static int[][] board = {
|
||||||
|
{8, 0, 0, 0, 0, 0, 0, 0, 0},
|
||||||
|
{0, 0, 3, 6, 0, 0, 0, 0, 0},
|
||||||
|
{0, 7, 0, 0, 9, 0, 2, 0, 0},
|
||||||
|
{0, 5, 0, 0, 0, 7, 0, 0, 0},
|
||||||
|
{0, 0, 0, 0, 4, 5, 7, 0, 0},
|
||||||
|
{0, 0, 0, 1, 0, 0, 0, 3, 0},
|
||||||
|
{0, 0, 1, 0, 0, 0, 0, 6, 8},
|
||||||
|
{0, 0, 8, 5, 0, 0, 0, 1, 0},
|
||||||
|
{0, 9, 0, 0, 0, 0, 4, 0, 0}
|
||||||
|
};
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
BacktrackingAlgorithm solver = new BacktrackingAlgorithm();
|
||||||
|
solver.solve(board);
|
||||||
|
solver.printBoard();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void printBoard() {
|
||||||
|
for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
|
||||||
|
for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
|
||||||
|
System.out.print(board[row][column] + " ");
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean solve(int[][] board) {
|
||||||
|
for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
|
||||||
|
for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
|
||||||
|
if (board[row][column] == NO_VALUE) {
|
||||||
|
for (int k = MIN_VALUE; k <= MAX_VALUE; k++) {
|
||||||
|
board[row][column] = k;
|
||||||
|
if (isValid(board, row, column) && solve(board)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
board[row][column] = NO_VALUE;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isValid(int[][] board, int row, int column) {
|
||||||
|
return rowConstraint(board, row) &&
|
||||||
|
columnConstraint(board, column) &&
|
||||||
|
subsectionConstraint(board, row, column);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean subsectionConstraint(int[][] board, int row, int column) {
|
||||||
|
boolean[] constraint = new boolean[BOARD_SIZE];
|
||||||
|
int subsectionRowStart = (row / SUBSECTION_SIZE) * SUBSECTION_SIZE;
|
||||||
|
int subsectionRowEnd = subsectionRowStart + SUBSECTION_SIZE;
|
||||||
|
|
||||||
|
int subsectionColumnStart = (column / SUBSECTION_SIZE) * SUBSECTION_SIZE;
|
||||||
|
int subsectionColumnEnd = subsectionColumnStart + SUBSECTION_SIZE;
|
||||||
|
|
||||||
|
for (int r = subsectionRowStart; r < subsectionRowEnd; r++) {
|
||||||
|
for (int c = subsectionColumnStart; c < subsectionColumnEnd; c++) {
|
||||||
|
if (!checkConstraint(board, r, constraint, c)) return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean columnConstraint(int[][] board, int column) {
|
||||||
|
boolean[] constraint = new boolean[BOARD_SIZE];
|
||||||
|
return IntStream.range(BOARD_START_INDEX, BOARD_SIZE)
|
||||||
|
.allMatch(row -> checkConstraint(board, row, constraint, column));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean rowConstraint(int[][] board, int row) {
|
||||||
|
boolean[] constraint = new boolean[BOARD_SIZE];
|
||||||
|
return IntStream.range(BOARD_START_INDEX, BOARD_SIZE)
|
||||||
|
.allMatch(column -> checkConstraint(board, row, constraint, column));
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean checkConstraint(int[][] board, int row, boolean[] constraint, int column) {
|
||||||
|
if (board[row][column] != NO_VALUE) {
|
||||||
|
if (!constraint[board[row][column] - 1]) {
|
||||||
|
constraint[board[row][column] - 1] = true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.algorithms.sudoku;
|
||||||
|
|
||||||
|
class ColumnNode extends DancingNode {
|
||||||
|
int size;
|
||||||
|
String name;
|
||||||
|
|
||||||
|
ColumnNode(String n) {
|
||||||
|
super();
|
||||||
|
size = 0;
|
||||||
|
name = n;
|
||||||
|
C = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
void cover() {
|
||||||
|
unlinkLR();
|
||||||
|
for (DancingNode i = this.D; i != this; i = i.D) {
|
||||||
|
for (DancingNode j = i.R; j != i; j = j.R) {
|
||||||
|
j.unlinkUD();
|
||||||
|
j.C.size--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void uncover() {
|
||||||
|
for (DancingNode i = this.U; i != this; i = i.U) {
|
||||||
|
for (DancingNode j = i.L; j != i; j = j.L) {
|
||||||
|
j.C.size++;
|
||||||
|
j.relinkUD();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
relinkLR();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,133 @@
|
|||||||
|
package com.baeldung.algorithms.sudoku;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class DancingLinks {
|
||||||
|
|
||||||
|
private ColumnNode header;
|
||||||
|
private List<DancingNode> answer;
|
||||||
|
|
||||||
|
private void search(int k) {
|
||||||
|
if (header.R == header) {
|
||||||
|
handleSolution(answer);
|
||||||
|
} else {
|
||||||
|
ColumnNode c = selectColumnNodeHeuristic();
|
||||||
|
c.cover();
|
||||||
|
|
||||||
|
for (DancingNode r = c.D; r != c; r = r.D) {
|
||||||
|
answer.add(r);
|
||||||
|
|
||||||
|
for (DancingNode j = r.R; j != r; j = j.R) {
|
||||||
|
j.C.cover();
|
||||||
|
}
|
||||||
|
|
||||||
|
search(k + 1);
|
||||||
|
|
||||||
|
r = answer.remove(answer.size() - 1);
|
||||||
|
c = r.C;
|
||||||
|
|
||||||
|
for (DancingNode j = r.L; j != r; j = j.L) {
|
||||||
|
j.C.uncover();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.uncover();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ColumnNode selectColumnNodeHeuristic() {
|
||||||
|
int min = Integer.MAX_VALUE;
|
||||||
|
ColumnNode ret = null;
|
||||||
|
for (ColumnNode c = (ColumnNode) header.R; c != header; c = (ColumnNode) c.R) {
|
||||||
|
if (c.size < min) {
|
||||||
|
min = c.size;
|
||||||
|
ret = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ColumnNode makeDLXBoard(boolean[][] grid) {
|
||||||
|
final int COLS = grid[0].length;
|
||||||
|
|
||||||
|
ColumnNode headerNode = new ColumnNode("header");
|
||||||
|
List<ColumnNode> columnNodes = new ArrayList<>();
|
||||||
|
|
||||||
|
for (int i = 0; i < COLS; i++) {
|
||||||
|
ColumnNode n = new ColumnNode(Integer.toString(i));
|
||||||
|
columnNodes.add(n);
|
||||||
|
headerNode = (ColumnNode) headerNode.hookRight(n);
|
||||||
|
}
|
||||||
|
headerNode = headerNode.R.C;
|
||||||
|
|
||||||
|
for (boolean[] aGrid : grid) {
|
||||||
|
DancingNode prev = null;
|
||||||
|
for (int j = 0; j < COLS; j++) {
|
||||||
|
if (aGrid[j]) {
|
||||||
|
ColumnNode col = columnNodes.get(j);
|
||||||
|
DancingNode newNode = new DancingNode(col);
|
||||||
|
if (prev == null)
|
||||||
|
prev = newNode;
|
||||||
|
col.U.hookDown(newNode);
|
||||||
|
prev = prev.hookRight(newNode);
|
||||||
|
col.size++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
headerNode.size = COLS;
|
||||||
|
|
||||||
|
return headerNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
DancingLinks(boolean[][] cover) {
|
||||||
|
header = makeDLXBoard(cover);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void runSolver() {
|
||||||
|
answer = new LinkedList<>();
|
||||||
|
search(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleSolution(List<DancingNode> answer) {
|
||||||
|
int[][] result = parseBoard(answer);
|
||||||
|
printSolution(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int size = 9;
|
||||||
|
|
||||||
|
private int[][] parseBoard(List<DancingNode> answer) {
|
||||||
|
int[][] result = new int[size][size];
|
||||||
|
for (DancingNode n : answer) {
|
||||||
|
DancingNode rcNode = n;
|
||||||
|
int min = Integer.parseInt(rcNode.C.name);
|
||||||
|
for (DancingNode tmp = n.R; tmp != n; tmp = tmp.R) {
|
||||||
|
int val = Integer.parseInt(tmp.C.name);
|
||||||
|
if (val < min) {
|
||||||
|
min = val;
|
||||||
|
rcNode = tmp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int ans1 = Integer.parseInt(rcNode.C.name);
|
||||||
|
int ans2 = Integer.parseInt(rcNode.R.C.name);
|
||||||
|
int r = ans1 / size;
|
||||||
|
int c = ans1 % size;
|
||||||
|
int num = (ans2 % size) + 1;
|
||||||
|
result[r][c] = num;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void printSolution(int[][] result) {
|
||||||
|
int size = result.length;
|
||||||
|
for (int[] aResult : result) {
|
||||||
|
StringBuilder ret = new StringBuilder();
|
||||||
|
for (int j = 0; j < size; j++) {
|
||||||
|
ret.append(aResult[j]).append(" ");
|
||||||
|
}
|
||||||
|
System.out.println(ret);
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,121 @@
|
|||||||
|
package com.baeldung.algorithms.sudoku;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class DancingLinksAlgorithm {
|
||||||
|
private static final int BOARD_SIZE = 9;
|
||||||
|
private static final int SUBSECTION_SIZE = 3;
|
||||||
|
private static final int NO_VALUE = 0;
|
||||||
|
private static final int CONSTRAINTS = 4;
|
||||||
|
private static final int MIN_VALUE = 1;
|
||||||
|
private static final int MAX_VALUE = 9;
|
||||||
|
private static final int COVER_START_INDEX = 1;
|
||||||
|
|
||||||
|
private static int[][] board = {
|
||||||
|
{8, 0, 0, 0, 0, 0, 0, 0, 0},
|
||||||
|
{0, 0, 3, 6, 0, 0, 0, 0, 0},
|
||||||
|
{0, 7, 0, 0, 9, 0, 2, 0, 0},
|
||||||
|
{0, 5, 0, 0, 0, 7, 0, 0, 0},
|
||||||
|
{0, 0, 0, 0, 4, 5, 7, 0, 0},
|
||||||
|
{0, 0, 0, 1, 0, 0, 0, 3, 0},
|
||||||
|
{0, 0, 1, 0, 0, 0, 0, 6, 8},
|
||||||
|
{0, 0, 8, 5, 0, 0, 0, 1, 0},
|
||||||
|
{0, 9, 0, 0, 0, 0, 4, 0, 0}
|
||||||
|
};
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
DancingLinksAlgorithm solver = new DancingLinksAlgorithm();
|
||||||
|
solver.solve(board);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void solve(int[][] board) {
|
||||||
|
boolean[][] cover = initializeExactCoverBoard(board);
|
||||||
|
DancingLinks dlx = new DancingLinks(cover);
|
||||||
|
dlx.runSolver();
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getIndex(int row, int column, int num) {
|
||||||
|
return (row - 1) * BOARD_SIZE * BOARD_SIZE + (column - 1) * BOARD_SIZE + (num - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean[][] createExactCoverBoard() {
|
||||||
|
boolean[][] coverBoard = new boolean[BOARD_SIZE * BOARD_SIZE * MAX_VALUE][BOARD_SIZE * BOARD_SIZE * CONSTRAINTS];
|
||||||
|
|
||||||
|
int hBase = 0;
|
||||||
|
hBase = checkCellConstraint(coverBoard, hBase);
|
||||||
|
hBase = checkRowConstraint(coverBoard, hBase);
|
||||||
|
hBase = checkColumnConstraint(coverBoard, hBase);
|
||||||
|
checkSubsectionConstraint(coverBoard, hBase);
|
||||||
|
|
||||||
|
return coverBoard;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int checkSubsectionConstraint(boolean[][] coverBoard, int hBase) {
|
||||||
|
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row += SUBSECTION_SIZE) {
|
||||||
|
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column += SUBSECTION_SIZE) {
|
||||||
|
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
|
||||||
|
for (int rowDelta = 0; rowDelta < SUBSECTION_SIZE; rowDelta++) {
|
||||||
|
for (int columnDelta = 0; columnDelta < SUBSECTION_SIZE; columnDelta++) {
|
||||||
|
int index = getIndex(row + rowDelta, column + columnDelta, n);
|
||||||
|
coverBoard[index][hBase] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hBase;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int checkColumnConstraint(boolean[][] coverBoard, int hBase) {
|
||||||
|
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
|
||||||
|
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
|
||||||
|
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
|
||||||
|
int index = getIndex(row, column, n);
|
||||||
|
coverBoard[index][hBase] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hBase;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int checkRowConstraint(boolean[][] coverBoard, int hBase) {
|
||||||
|
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
|
||||||
|
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
|
||||||
|
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
|
||||||
|
int index = getIndex(row, column, n);
|
||||||
|
coverBoard[index][hBase] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hBase;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int checkCellConstraint(boolean[][] coverBoard, int hBase) {
|
||||||
|
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
|
||||||
|
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++, hBase++) {
|
||||||
|
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++) {
|
||||||
|
int index = getIndex(row, column, n);
|
||||||
|
coverBoard[index][hBase] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hBase;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean[][] initializeExactCoverBoard(int[][] board) {
|
||||||
|
boolean[][] coverBoard = createExactCoverBoard();
|
||||||
|
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
|
||||||
|
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
|
||||||
|
int n = board[row - 1][column - 1];
|
||||||
|
if (n != NO_VALUE) {
|
||||||
|
for (int num = MIN_VALUE; num <= MAX_VALUE; num++) {
|
||||||
|
if (num != n) {
|
||||||
|
Arrays.fill(coverBoard[getIndex(row, column, num)], false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return coverBoard;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,50 @@
|
|||||||
|
package com.baeldung.algorithms.sudoku;
|
||||||
|
|
||||||
|
class DancingNode {
|
||||||
|
DancingNode L, R, U, D;
|
||||||
|
ColumnNode C;
|
||||||
|
|
||||||
|
DancingNode hookDown(DancingNode node) {
|
||||||
|
assert (this.C == node.C);
|
||||||
|
node.D = this.D;
|
||||||
|
node.D.U = node;
|
||||||
|
node.U = this;
|
||||||
|
this.D = node;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
DancingNode hookRight(DancingNode node) {
|
||||||
|
node.R = this.R;
|
||||||
|
node.R.L = node;
|
||||||
|
node.L = this;
|
||||||
|
this.R = node;
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
void unlinkLR() {
|
||||||
|
this.L.R = this.R;
|
||||||
|
this.R.L = this.L;
|
||||||
|
}
|
||||||
|
|
||||||
|
void relinkLR() {
|
||||||
|
this.L.R = this.R.L = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
void unlinkUD() {
|
||||||
|
this.U.D = this.D;
|
||||||
|
this.D.U = this.U;
|
||||||
|
}
|
||||||
|
|
||||||
|
void relinkUD() {
|
||||||
|
this.U.D = this.D.U = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
DancingNode() {
|
||||||
|
L = R = U = D = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
DancingNode(ColumnNode c) {
|
||||||
|
this();
|
||||||
|
C = c;
|
||||||
|
}
|
||||||
|
}
|
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>
|
12
algorithms/src/main/resources/maze/maze1.txt
Normal file
12
algorithms/src/main/resources/maze/maze1.txt
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
S ########
|
||||||
|
# #
|
||||||
|
# ### ## #
|
||||||
|
# # # #
|
||||||
|
# # # # #
|
||||||
|
# ## #####
|
||||||
|
# # #
|
||||||
|
# # # # #
|
||||||
|
##### ####
|
||||||
|
# # E
|
||||||
|
# # # #
|
||||||
|
##########
|
22
algorithms/src/main/resources/maze/maze2.txt
Normal file
22
algorithms/src/main/resources/maze/maze2.txt
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
S ##########################
|
||||||
|
# # # #
|
||||||
|
# # #### ############### #
|
||||||
|
# # # # # #
|
||||||
|
# # #### # # ###############
|
||||||
|
# # # # # # #
|
||||||
|
# # # #### ### ########### #
|
||||||
|
# # # # # #
|
||||||
|
# ################## #
|
||||||
|
######### # # # # #
|
||||||
|
# # #### # ####### # #
|
||||||
|
# # ### ### # # # # #
|
||||||
|
# # ## # ##### # #
|
||||||
|
##### ####### # # # # #
|
||||||
|
# # ## ## #### # #
|
||||||
|
# ##### ####### # #
|
||||||
|
# # ############
|
||||||
|
####### ######### # #
|
||||||
|
# # ######## #
|
||||||
|
# ####### ###### ## # E
|
||||||
|
# # # ## #
|
||||||
|
############################
|
@ -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,127 @@
|
|||||||
|
package com.baeldung.algorithms.conversion;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.DecoderException;
|
||||||
|
import org.hamcrest.text.IsEqualIgnoringCase;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.conversion.HexStringConverter;
|
||||||
|
|
||||||
|
public class ByteArrayConverterUnitTest {
|
||||||
|
|
||||||
|
private HexStringConverter hexStringConverter;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() {
|
||||||
|
hexStringConverter = new HexStringConverter();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
if(hexString.charAt(0) == '0') {
|
||||||
|
hexString = hexString.substring(1);
|
||||||
|
}
|
||||||
|
String output = hexStringConverter.encodeUsingBigIntegerToString(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDecodeHexStringToByteArrayUsingBigInteger() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeHexString(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeHexString(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected=IllegalArgumentException.class)
|
||||||
|
public void shouldDecodeHexToByteWithInvalidHexCharacter() {
|
||||||
|
hexStringConverter.hexToByte("fg");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringDataTypeConverter() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeUsingDataTypeConverter(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringUsingGuava() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeUsingGuava(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDecodeHexStringToByteArrayUsingGuava() {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeUsingGuava(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
String output = hexStringConverter.encodeUsingApacheCommons(bytes);
|
||||||
|
assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException {
|
||||||
|
byte[] bytes = getSampleBytes();
|
||||||
|
String hexString = getSampleHexString();
|
||||||
|
byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString);
|
||||||
|
assertArrayEquals(bytes, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getSampleHexString() {
|
||||||
|
return "0af50c0e2d10";
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] getSampleBytes() {
|
||||||
|
return new byte[] { 10, -11, 12, 14, 45, 16 };
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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,36 @@
|
|||||||
|
package com.baeldung.algorithms.heapsort;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class HeapUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() {
|
||||||
|
// given
|
||||||
|
Heap<Integer> heap = Heap.of(3, 5, 1, 4, 2);
|
||||||
|
|
||||||
|
// when
|
||||||
|
int head = heap.pop();
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(head).isEqualTo(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() {
|
||||||
|
// given
|
||||||
|
List<Integer> elements = Arrays.asList(3, 5, 1, 4, 2);
|
||||||
|
|
||||||
|
// when
|
||||||
|
List<Integer> sortedElements = Heap.sort(elements);
|
||||||
|
|
||||||
|
// then
|
||||||
|
assertThat(sortedElements).isEqualTo(Arrays.asList(1, 2, 3, 4, 5));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.algorithms.insertionsort;
|
||||||
|
|
||||||
|
import com.baeldung.algorithms.insertionsort.InsertionSort;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
|
||||||
|
public class InsertionSortUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() {
|
||||||
|
int[] input = {6, 2, 3, 4, 5, 1};
|
||||||
|
InsertionSort.insertionSortImperative(input);
|
||||||
|
int[] expected = {1, 2, 3, 4, 5, 6};
|
||||||
|
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() {
|
||||||
|
int[] input = {6, 4, 5, 2, 3, 1};
|
||||||
|
InsertionSort.insertionSortRecursive(input);
|
||||||
|
int[] expected = {1, 2, 3, 4, 5, 6};
|
||||||
|
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
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