Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-14274-8
This commit is contained in:
17
.gitignore
vendored
17
.gitignore
vendored
@@ -1,8 +1,10 @@
|
||||
*/bin/*
|
||||
bin/
|
||||
|
||||
*.class
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
@@ -21,11 +23,14 @@
|
||||
*.iws
|
||||
out/
|
||||
|
||||
# VSCode
|
||||
.vscode/
|
||||
|
||||
# Mac
|
||||
.DS_Store
|
||||
|
||||
# Maven
|
||||
log/
|
||||
log/*
|
||||
target/
|
||||
|
||||
# Gradle
|
||||
@@ -77,4 +82,12 @@ apache-avro/src/main/java/com/baeldung/avro/model/
|
||||
jta/transaction-logs/
|
||||
software-security/sql-injection-samples/derby.log
|
||||
spring-soap/src/main/java/com/baeldung/springsoap/gen/
|
||||
/report-*.json
|
||||
/report-*.json
|
||||
transaction.log
|
||||
*-shell.log
|
||||
|
||||
apache-cxf/cxf-aegis/baeldung.xml
|
||||
apache-fop/src/test/resources/input.xml
|
||||
apache-fop/src/test/resources/output_herold.pdf
|
||||
apache-fop/src/test/resources/output_html2fo.pdf
|
||||
apache-fop/src/test/resources/output_jtidy.pdf
|
||||
24
.travis.yml
24
.travis.yml
@@ -1,24 +0,0 @@
|
||||
language: java
|
||||
|
||||
before_install:
|
||||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
install: skip
|
||||
script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true
|
||||
|
||||
sudo: required
|
||||
|
||||
jdk:
|
||||
- oraclejdk8
|
||||
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- oracle-java8-installer
|
||||
|
||||
cache:
|
||||
directories:
|
||||
- .autoconf
|
||||
- $HOME/.m2
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [A Guide to JGit](http://www.baeldung.com/jgit)
|
||||
25
README.md
25
README.md
@@ -1,12 +1,16 @@
|
||||
|
||||
The "REST with Spring" Classes
|
||||
The Courses
|
||||
==============================
|
||||
|
||||
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)**
|
||||
|
||||
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)**
|
||||
Here's the new "Learn Spring" course: <br/>
|
||||
**[>> LEARN SPRING - THE MASTER CLASS](https://www.baeldung.com/learn-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=ls#master-class)**
|
||||
|
||||
Here's the Master Class of "REST With Spring" (along with the new announced Boot 2 material): <br/>
|
||||
**[>> THE REST WITH SPRING - MASTER CLASS](https://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/>
|
||||
**[>> LEARN SPRING SECURITY - MASTER CLASS](https://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||
|
||||
|
||||
|
||||
@@ -15,7 +19,7 @@ Java and Spring Tutorials
|
||||
|
||||
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
||||
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security.
|
||||
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
||||
In additional to Spring, the modules here are covering a number of aspects in Java.
|
||||
|
||||
|
||||
Building the project
|
||||
@@ -32,8 +36,15 @@ Running a Spring Boot module
|
||||
====================
|
||||
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
|
||||
|
||||
#Running Tests
|
||||
|
||||
Working with the IDE
|
||||
====================
|
||||
This repo contains a large number of modules.
|
||||
When you're working with an individual module, there's no need to import all of them (or build all of them) - you can simply import that particular module in either Eclipse or IntelliJ.
|
||||
|
||||
|
||||
Running Tests
|
||||
=============
|
||||
The command `mvn clean install` will run the unit tests in a module.
|
||||
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
### Relevant articles
|
||||
|
||||
- [Introduction to Twitter4J](http://www.baeldung.com/twitter4j)
|
||||
@@ -1,3 +1,7 @@
|
||||
## Relevant articles:
|
||||
## Akka HTTP
|
||||
|
||||
This module contains articles about Akka HTTP.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Introduction to Akka HTTP](https://www.baeldung.com/akka-http)
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
## Akka Streams
|
||||
|
||||
This module contains articles about Akka Streams.
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [Guide to Akka Streams](http://www.baeldung.com/akka-streams)
|
||||
- [Guide to Akka Streams](https://www.baeldung.com/akka-streams)
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
## Relevant articles:
|
||||
## Genetic Algorithms
|
||||
|
||||
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
|
||||
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
|
||||
This module contains articles about genetic algorithms.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Introduction to Jenetics Library](https://www.baeldung.com/jenetics)
|
||||
- [Ant Colony Optimization](https://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
|
||||
- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
||||
|
||||
4
algorithms-miscellaneous-1/.gitignore
vendored
4
algorithms-miscellaneous-1/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
/target/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
||||
@@ -1,18 +1,15 @@
|
||||
## Relevant articles:
|
||||
## Algorithms - Miscellaneous
|
||||
|
||||
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/java-finite-automata)
|
||||
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
- [Binary Search Algorithm in Java](http://www.baeldung.com/java-binary-search)
|
||||
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
|
||||
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
|
||||
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
|
||||
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm)
|
||||
This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](/../algorithms-sorting) and
|
||||
[genetic algorithms](/../algorithms-genetic), have their own dedicated modules.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Validating Input With Finite Automata in Java](https://www.baeldung.com/java-finite-automata)
|
||||
- [Example of Hill Climbing Algorithm](https://www.baeldung.com/java-hill-climbing-algorithm)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
- [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search)
|
||||
- [Introduction to Minimax Algorithm](https://www.baeldung.com/java-minimax-algorithm)
|
||||
- [How to Calculate Levenshtein Distance in Java?](https://www.baeldung.com/java-levenshtein-distance)
|
||||
- [How to Find the Kth Largest Element in Java](https://www.baeldung.com/java-kth-largest-element)
|
||||
- More articles: [[next -->]](/../algorithms-miscellaneous-2)
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
<dependency>
|
||||
<groupId>com.github.dpaukov</groupId>
|
||||
<artifactId>combinatoricslib3</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<version>${combinatoricslib3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<guava.version>27.0.1-jre</guava.version>
|
||||
<combinatoricslib3.version>3.3.0</combinatoricslib3.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
4
algorithms-miscellaneous-2/.gitignore
vendored
4
algorithms-miscellaneous-2/.gitignore
vendored
@@ -1,4 +0,0 @@
|
||||
/target/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
||||
@@ -1,19 +1,16 @@
|
||||
## Relevant articles:
|
||||
## Algorithms - Miscellaneous
|
||||
|
||||
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
|
||||
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
|
||||
- [Test a Linked List for Cyclicity](http://www.baeldung.com/java-linked-list-cyclicity)
|
||||
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
|
||||
- [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze)
|
||||
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
|
||||
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
|
||||
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
|
||||
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
||||
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
||||
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
|
||||
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
|
||||
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
|
||||
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
|
||||
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
||||
This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](/../algorithms-sorting) and
|
||||
[genetic algorithms](/../algorithms-genetic), have their own dedicated modules.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Dijkstra Shortest Path Algorithm in Java](https://www.baeldung.com/java-dijkstra)
|
||||
- [Introduction to Cobertura](https://www.baeldung.com/cobertura)
|
||||
- [Test a Linked List for Cyclicity](https://www.baeldung.com/java-linked-list-cyclicity)
|
||||
- [Introduction to JGraphT](https://www.baeldung.com/jgrapht)
|
||||
- [A Maze Solver in Java](https://www.baeldung.com/java-solve-maze)
|
||||
- [Create a Sudoku Solver in Java](https://www.baeldung.com/java-sudoku)
|
||||
- [Displaying Money Amounts in Words](https://www.baeldung.com/java-money-into-words)
|
||||
- [A Collaborative Filtering Recommendation System in Java](https://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-1) [[next -->]](/../algorithms-miscellaneous-3)
|
||||
|
||||
@@ -1,6 +1,19 @@
|
||||
## Relevant articles:
|
||||
## Algorithms - Miscellaneous
|
||||
|
||||
This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](/algorithms-sorting) and
|
||||
[genetic algorithms](/algorithms-genetic), have their own dedicated modules.
|
||||
|
||||
## Relevant Articles:
|
||||
|
||||
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
|
||||
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
|
||||
- [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)
|
||||
- [Converting Between Roman and Arabic Numerals in Java](https://www.baeldung.com/java-convert-roman-arabic)
|
||||
- [Practical Java Examples of the Big O Notation](https://www.baeldung.com/java-algorithm-complexity)
|
||||
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
|
||||
- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
|
||||
- [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)
|
||||
- [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle)
|
||||
- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency)
|
||||
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
|
||||
- [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>algorithms-miscellaneous-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
@@ -18,6 +18,57 @@
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>retrofit</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.retrofit2</groupId>
|
||||
<artifactId>converter-jackson</artifactId>
|
||||
<version>${retrofit.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.8.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>pl.pragmatists</groupId>
|
||||
<artifactId>JUnitParams</artifactId>
|
||||
<version>1.1.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-bytecode</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -34,6 +85,10 @@
|
||||
|
||||
<properties>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-collections4.version>4.3</commons-collections4.version>
|
||||
<guava.version>28.0-jre</guava.version>
|
||||
<retrofit.version>2.6.0</retrofit.version>
|
||||
<jmh-core.version>1.19</jmh-core.version>
|
||||
<jmh-generator.version>1.19</jmh-generator.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.algorithms.breadthfirstsearch;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class BreadthFirstSearchAlgorithm {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(BreadthFirstSearchAlgorithm.class);
|
||||
|
||||
public static <T> Optional<Tree<T>> search(T value, Tree<T> root) {
|
||||
Queue<Tree<T>> queue = new ArrayDeque<>();
|
||||
queue.add(root);
|
||||
|
||||
Tree<T> currentNode;
|
||||
while (!queue.isEmpty()) {
|
||||
currentNode = queue.remove();
|
||||
LOGGER.info("Visited node with value: {}", currentNode.getValue());
|
||||
|
||||
if (currentNode.getValue().equals(value)) {
|
||||
return Optional.of(currentNode);
|
||||
} else {
|
||||
queue.addAll(currentNode.getChildren());
|
||||
}
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public static <T> Optional<Node<T>> search(T value, Node<T> start) {
|
||||
Queue<Node<T>> queue = new ArrayDeque<>();
|
||||
queue.add(start);
|
||||
|
||||
Node<T> currentNode;
|
||||
Set<Node<T>> alreadyVisited = new HashSet<>();
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
currentNode = queue.remove();
|
||||
LOGGER.info("Visited node with value: {}", currentNode.getValue());
|
||||
|
||||
if (currentNode.getValue().equals(value)) {
|
||||
return Optional.of(currentNode);
|
||||
} else {
|
||||
alreadyVisited.add(currentNode);
|
||||
queue.addAll(currentNode.getNeighbors());
|
||||
queue.removeAll(alreadyVisited);
|
||||
}
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.algorithms.breadthfirstsearch;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class Node<T> {
|
||||
|
||||
private T value;
|
||||
private Set<Node<T>> neighbors;
|
||||
|
||||
public Node(T value) {
|
||||
this.value = value;
|
||||
this.neighbors = new HashSet<>();
|
||||
}
|
||||
|
||||
public T getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public Set<Node<T>> getNeighbors() {
|
||||
return Collections.unmodifiableSet(neighbors);
|
||||
}
|
||||
|
||||
public void connect(Node<T> node) {
|
||||
if (this == node) throw new IllegalArgumentException("Can't connect node to itself");
|
||||
this.neighbors.add(node);
|
||||
node.neighbors.add(this);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.algorithms.breadthfirstsearch;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class Tree<T> {
|
||||
|
||||
private T value;
|
||||
private List<Tree<T>> children;
|
||||
|
||||
private Tree(T value) {
|
||||
this.value = value;
|
||||
this.children = new ArrayList<>();
|
||||
}
|
||||
|
||||
public static <T> Tree<T> of(T value) {
|
||||
return new Tree<>(value);
|
||||
}
|
||||
|
||||
public T getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public List<Tree<T>> getChildren() {
|
||||
return Collections.unmodifiableList(children);
|
||||
}
|
||||
|
||||
public Tree<T> addChild(T value) {
|
||||
Tree<T> newChild = new Tree<>(value);
|
||||
children.add(newChild);
|
||||
return newChild;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.algorithms.checksortedlist;
|
||||
|
||||
public class Employee {
|
||||
|
||||
long id;
|
||||
|
||||
String name;
|
||||
|
||||
public Employee() {
|
||||
}
|
||||
|
||||
public Employee(long id, String name) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.algorithms.checksortedlist;
|
||||
|
||||
import static org.apache.commons.collections4.CollectionUtils.isEmpty;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Comparators;
|
||||
import com.google.common.collect.Ordering;;
|
||||
|
||||
public class SortedListChecker {
|
||||
|
||||
private SortedListChecker() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingIterativeApproach(List<String> listOfStrings) {
|
||||
if (isEmpty(listOfStrings) || listOfStrings.size() == 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Iterator<String> iter = listOfStrings.iterator();
|
||||
String current, previous = iter.next();
|
||||
while (iter.hasNext()) {
|
||||
current = iter.next();
|
||||
if (previous.compareTo(current) > 0) {
|
||||
return false;
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingIterativeApproach(List<Employee> employees, Comparator<Employee> employeeComparator) {
|
||||
if (isEmpty(employees) || employees.size() == 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Iterator<Employee> iter = employees.iterator();
|
||||
Employee current, previous = iter.next();
|
||||
while (iter.hasNext()) {
|
||||
current = iter.next();
|
||||
if (employeeComparator.compare(previous, current) > 0) {
|
||||
return false;
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingRecursion(List<String> listOfStrings) {
|
||||
return isSortedRecursive(listOfStrings, listOfStrings.size());
|
||||
}
|
||||
|
||||
public static boolean isSortedRecursive(List<String> listOfStrings, int index) {
|
||||
if (index < 2) {
|
||||
return true;
|
||||
} else if (listOfStrings.get(index - 2)
|
||||
.compareTo(listOfStrings.get(index - 1)) > 0) {
|
||||
return false;
|
||||
} else {
|
||||
return isSortedRecursive(listOfStrings, index - 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingOrderingClass(List<String> listOfStrings) {
|
||||
return Ordering.<String> natural()
|
||||
.isOrdered(listOfStrings);
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingOrderingClass(List<Employee> employees, Comparator<Employee> employeeComparator) {
|
||||
return Ordering.from(employeeComparator)
|
||||
.isOrdered(employees);
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingOrderingClassHandlingNull(List<String> listOfStrings) {
|
||||
return Ordering.<String> natural()
|
||||
.nullsLast()
|
||||
.isOrdered(listOfStrings);
|
||||
}
|
||||
|
||||
public static boolean checkIfSortedUsingComparators(List<String> listOfStrings) {
|
||||
return Comparators.isInOrder(listOfStrings, Comparator.<String> naturalOrder());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.algorithms.interpolationsearch;
|
||||
|
||||
public class InterpolationSearch {
|
||||
|
||||
public static int interpolationSearch(int[] data, int item) {
|
||||
|
||||
int highEnd = (data.length - 1);
|
||||
int lowEnd = 0;
|
||||
|
||||
while (item >= data[lowEnd] && item <= data[highEnd] && lowEnd <= highEnd) {
|
||||
|
||||
int probe = lowEnd + (highEnd - lowEnd) * (item - data[lowEnd]) / (data[highEnd] - data[lowEnd]);
|
||||
|
||||
if (highEnd == lowEnd) {
|
||||
if (data[lowEnd] == item) {
|
||||
return lowEnd;
|
||||
} else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (data[probe] == item) {
|
||||
return probe;
|
||||
}
|
||||
|
||||
if (data[probe] < item) {
|
||||
lowEnd = probe + 1;
|
||||
} else {
|
||||
highEnd = probe - 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Encapsulates all coordinates for a particular cluster centroid.
|
||||
*/
|
||||
public class Centroid {
|
||||
|
||||
/**
|
||||
* The centroid coordinates.
|
||||
*/
|
||||
private final Map<String, Double> coordinates;
|
||||
|
||||
public Centroid(Map<String, Double> coordinates) {
|
||||
this.coordinates = coordinates;
|
||||
}
|
||||
|
||||
public Map<String, Double> getCoordinates() {
|
||||
return coordinates;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Centroid centroid = (Centroid) o;
|
||||
return Objects.equals(getCoordinates(), centroid.getCoordinates());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getCoordinates());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Centroid " + coordinates;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Defines a contract to calculate distance between two feature vectors. The less the
|
||||
* calculated distance, the more two items are similar to each other.
|
||||
*/
|
||||
public interface Distance {
|
||||
|
||||
/**
|
||||
* Calculates the distance between two feature vectors.
|
||||
*
|
||||
* @param f1 The first set of features.
|
||||
* @param f2 The second set of features.
|
||||
* @return Calculated distance.
|
||||
* @throws IllegalArgumentException If the given feature vectors are invalid.
|
||||
*/
|
||||
double calculate(Map<String, Double> f1, Map<String, Double> f2);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Encapsulates methods to calculates errors between centroid and the cluster members.
|
||||
*/
|
||||
public class Errors {
|
||||
|
||||
public static double sse(Map<Centroid, List<Record>> clustered, Distance distance) {
|
||||
double sum = 0;
|
||||
for (Map.Entry<Centroid, List<Record>> entry : clustered.entrySet()) {
|
||||
Centroid centroid = entry.getKey();
|
||||
for (Record record : entry.getValue()) {
|
||||
double d = distance.calculate(centroid.getCoordinates(), record.getFeatures());
|
||||
sum += Math.pow(d, 2);
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Calculates the distance between two items using the Euclidean formula.
|
||||
*/
|
||||
public class EuclideanDistance implements Distance {
|
||||
|
||||
@Override
|
||||
public double calculate(Map<String, Double> f1, Map<String, Double> f2) {
|
||||
if (f1 == null || f2 == null) {
|
||||
throw new IllegalArgumentException("Feature vectors can't be null");
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
for (String key : f1.keySet()) {
|
||||
Double v1 = f1.get(key);
|
||||
Double v2 = f2.get(key);
|
||||
|
||||
if (v1 != null && v2 != null) sum += Math.pow(v1 - v2, 2);
|
||||
}
|
||||
|
||||
return Math.sqrt(sum);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
|
||||
/**
|
||||
* Encapsulates an implementation of KMeans clustering algorithm.
|
||||
*
|
||||
* @author Ali Dehghani
|
||||
*/
|
||||
public class KMeans {
|
||||
|
||||
private KMeans() {
|
||||
throw new IllegalAccessError("You shouldn't call this constructor");
|
||||
}
|
||||
|
||||
/**
|
||||
* Will be used to generate random numbers.
|
||||
*/
|
||||
private static final Random random = new Random();
|
||||
|
||||
/**
|
||||
* Performs the K-Means clustering algorithm on the given dataset.
|
||||
*
|
||||
* @param records The dataset.
|
||||
* @param k Number of Clusters.
|
||||
* @param distance To calculate the distance between two items.
|
||||
* @param maxIterations Upper bound for the number of iterations.
|
||||
* @return K clusters along with their features.
|
||||
*/
|
||||
public static Map<Centroid, List<Record>> fit(List<Record> records, int k, Distance distance, int maxIterations) {
|
||||
applyPreconditions(records, k, distance, maxIterations);
|
||||
|
||||
List<Centroid> centroids = randomCentroids(records, k);
|
||||
Map<Centroid, List<Record>> clusters = new HashMap<>();
|
||||
Map<Centroid, List<Record>> lastState = new HashMap<>();
|
||||
|
||||
// iterate for a pre-defined number of times
|
||||
for (int i = 0; i < maxIterations; i++) {
|
||||
boolean isLastIteration = i == maxIterations - 1;
|
||||
|
||||
// in each iteration we should find the nearest centroid for each record
|
||||
for (Record record : records) {
|
||||
Centroid centroid = nearestCentroid(record, centroids, distance);
|
||||
assignToCluster(clusters, record, centroid);
|
||||
}
|
||||
|
||||
// if the assignment does not change, then the algorithm terminates
|
||||
boolean shouldTerminate = isLastIteration || clusters.equals(lastState);
|
||||
lastState = clusters;
|
||||
if (shouldTerminate) {
|
||||
break;
|
||||
}
|
||||
|
||||
// at the end of each iteration we should relocate the centroids
|
||||
centroids = relocateCentroids(clusters);
|
||||
clusters = new HashMap<>();
|
||||
}
|
||||
|
||||
return lastState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move all cluster centroids to the average of all assigned features.
|
||||
*
|
||||
* @param clusters The current cluster configuration.
|
||||
* @return Collection of new and relocated centroids.
|
||||
*/
|
||||
private static List<Centroid> relocateCentroids(Map<Centroid, List<Record>> clusters) {
|
||||
return clusters
|
||||
.entrySet()
|
||||
.stream()
|
||||
.map(e -> average(e.getKey(), e.getValue()))
|
||||
.collect(toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the given centroid to the average position of all assigned features. If
|
||||
* the centroid has no feature in its cluster, then there would be no need for a
|
||||
* relocation. Otherwise, for each entry we calculate the average of all records
|
||||
* first by summing all the entries and then dividing the final summation value by
|
||||
* the number of records.
|
||||
*
|
||||
* @param centroid The centroid to move.
|
||||
* @param records The assigned features.
|
||||
* @return The moved centroid.
|
||||
*/
|
||||
private static Centroid average(Centroid centroid, List<Record> records) {
|
||||
// if this cluster is empty, then we shouldn't move the centroid
|
||||
if (records == null || records.isEmpty()) {
|
||||
return centroid;
|
||||
}
|
||||
|
||||
// Since some records don't have all possible attributes, we initialize
|
||||
// average coordinates equal to current centroid coordinates
|
||||
Map<String, Double> average = centroid.getCoordinates();
|
||||
|
||||
// The average function works correctly if we clear all coordinates corresponding
|
||||
// to present record attributes
|
||||
records
|
||||
.stream()
|
||||
.flatMap(e -> e
|
||||
.getFeatures()
|
||||
.keySet()
|
||||
.stream())
|
||||
.forEach(k -> average.put(k, 0.0));
|
||||
|
||||
for (Record record : records) {
|
||||
record
|
||||
.getFeatures()
|
||||
.forEach((k, v) -> average.compute(k, (k1, currentValue) -> v + currentValue));
|
||||
}
|
||||
|
||||
average.forEach((k, v) -> average.put(k, v / records.size()));
|
||||
|
||||
return new Centroid(average);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns a feature vector to the given centroid. If this is the first assignment for this centroid,
|
||||
* first we should create the list.
|
||||
*
|
||||
* @param clusters The current cluster configuration.
|
||||
* @param record The feature vector.
|
||||
* @param centroid The centroid.
|
||||
*/
|
||||
private static void assignToCluster(Map<Centroid, List<Record>> clusters, Record record, Centroid centroid) {
|
||||
clusters.compute(centroid, (key, list) -> {
|
||||
if (list == null) {
|
||||
list = new ArrayList<>();
|
||||
}
|
||||
|
||||
list.add(record);
|
||||
return list;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* With the help of the given distance calculator, iterates through centroids and finds the
|
||||
* nearest one to the given record.
|
||||
*
|
||||
* @param record The feature vector to find a centroid for.
|
||||
* @param centroids Collection of all centroids.
|
||||
* @param distance To calculate the distance between two items.
|
||||
* @return The nearest centroid to the given feature vector.
|
||||
*/
|
||||
private static Centroid nearestCentroid(Record record, List<Centroid> centroids, Distance distance) {
|
||||
double minimumDistance = Double.MAX_VALUE;
|
||||
Centroid nearest = null;
|
||||
|
||||
for (Centroid centroid : centroids) {
|
||||
double currentDistance = distance.calculate(record.getFeatures(), centroid.getCoordinates());
|
||||
|
||||
if (currentDistance < minimumDistance) {
|
||||
minimumDistance = currentDistance;
|
||||
nearest = centroid;
|
||||
}
|
||||
}
|
||||
|
||||
return nearest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates k random centroids. Before kicking-off the centroid generation process,
|
||||
* first we calculate the possible value range for each attribute. Then when
|
||||
* we're going to generate the centroids, we generate random coordinates in
|
||||
* the [min, max] range for each attribute.
|
||||
*
|
||||
* @param records The dataset which helps to calculate the [min, max] range for
|
||||
* each attribute.
|
||||
* @param k Number of clusters.
|
||||
* @return Collections of randomly generated centroids.
|
||||
*/
|
||||
private static List<Centroid> randomCentroids(List<Record> records, int k) {
|
||||
List<Centroid> centroids = new ArrayList<>();
|
||||
Map<String, Double> maxs = new HashMap<>();
|
||||
Map<String, Double> mins = new HashMap<>();
|
||||
|
||||
for (Record record : records) {
|
||||
record
|
||||
.getFeatures()
|
||||
.forEach((key, value) -> {
|
||||
// compares the value with the current max and choose the bigger value between them
|
||||
maxs.compute(key, (k1, max) -> max == null || value > max ? value : max);
|
||||
|
||||
// compare the value with the current min and choose the smaller value between them
|
||||
mins.compute(key, (k1, min) -> min == null || value < min ? value : min);
|
||||
});
|
||||
}
|
||||
|
||||
Set<String> attributes = records
|
||||
.stream()
|
||||
.flatMap(e -> e
|
||||
.getFeatures()
|
||||
.keySet()
|
||||
.stream())
|
||||
.collect(toSet());
|
||||
for (int i = 0; i < k; i++) {
|
||||
Map<String, Double> coordinates = new HashMap<>();
|
||||
for (String attribute : attributes) {
|
||||
double max = maxs.get(attribute);
|
||||
double min = mins.get(attribute);
|
||||
coordinates.put(attribute, random.nextDouble() * (max - min) + min);
|
||||
}
|
||||
|
||||
centroids.add(new Centroid(coordinates));
|
||||
}
|
||||
|
||||
return centroids;
|
||||
}
|
||||
|
||||
private static void applyPreconditions(List<Record> records, int k, Distance distance, int maxIterations) {
|
||||
if (records == null || records.isEmpty()) {
|
||||
throw new IllegalArgumentException("The dataset can't be empty");
|
||||
}
|
||||
|
||||
if (k <= 1) {
|
||||
throw new IllegalArgumentException("It doesn't make sense to have less than or equal to 1 cluster");
|
||||
}
|
||||
|
||||
if (distance == null) {
|
||||
throw new IllegalArgumentException("The distance calculator is required");
|
||||
}
|
||||
|
||||
if (maxIterations <= 0) {
|
||||
throw new IllegalArgumentException("Max iterations should be a positive number");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import okhttp3.OkHttpClient;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.jackson.JacksonConverterFactory;
|
||||
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
|
||||
public class LastFm {
|
||||
|
||||
private static OkHttpClient okHttp = new OkHttpClient.Builder()
|
||||
.addInterceptor(new LastFmService.Authenticator("put your API key here"))
|
||||
.build();
|
||||
|
||||
private static Retrofit retrofit = new Retrofit.Builder()
|
||||
.client(okHttp)
|
||||
.addConverterFactory(JacksonConverterFactory.create())
|
||||
.baseUrl("http://ws.audioscrobbler.com/")
|
||||
.build();
|
||||
|
||||
private static LastFmService lastFm = retrofit.create(LastFmService.class);
|
||||
|
||||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
List<String> artists = getTop100Artists();
|
||||
Set<String> tags = getTop100Tags();
|
||||
List<Record> records = datasetWithTaggedArtists(artists, tags);
|
||||
|
||||
Map<Centroid, List<Record>> clusters = KMeans.fit(records, 7, new EuclideanDistance(), 1000);
|
||||
// Print the cluster configuration
|
||||
clusters.forEach((key, value) -> {
|
||||
System.out.println("------------------------------ CLUSTER -----------------------------------");
|
||||
|
||||
System.out.println(sortedCentroid(key));
|
||||
String members = String.join(", ", value
|
||||
.stream()
|
||||
.map(Record::getDescription)
|
||||
.collect(toSet()));
|
||||
System.out.print(members);
|
||||
|
||||
System.out.println();
|
||||
System.out.println();
|
||||
});
|
||||
|
||||
Map<String, Object> json = convertToD3CompatibleMap(clusters);
|
||||
System.out.println(mapper.writeValueAsString(json));
|
||||
}
|
||||
|
||||
private static Map<String, Object> convertToD3CompatibleMap(Map<Centroid, List<Record>> clusters) {
|
||||
Map<String, Object> json = new HashMap<>();
|
||||
json.put("name", "Musicians");
|
||||
List<Map<String, Object>> children = new ArrayList<>();
|
||||
clusters.forEach((key, value) -> {
|
||||
Map<String, Object> child = new HashMap<>();
|
||||
child.put("name", dominantGenre(sortedCentroid(key)));
|
||||
List<Map<String, String>> nested = new ArrayList<>();
|
||||
for (Record record : value) {
|
||||
nested.add(Collections.singletonMap("name", record.getDescription()));
|
||||
}
|
||||
child.put("children", nested);
|
||||
|
||||
children.add(child);
|
||||
});
|
||||
json.put("children", children);
|
||||
return json;
|
||||
}
|
||||
|
||||
private static String dominantGenre(Centroid centroid) {
|
||||
return centroid
|
||||
.getCoordinates()
|
||||
.keySet()
|
||||
.stream()
|
||||
.limit(2)
|
||||
.collect(Collectors.joining(", "));
|
||||
}
|
||||
|
||||
private static Centroid sortedCentroid(Centroid key) {
|
||||
List<Map.Entry<String, Double>> entries = new ArrayList<>(key
|
||||
.getCoordinates()
|
||||
.entrySet());
|
||||
entries.sort((e1, e2) -> e2
|
||||
.getValue()
|
||||
.compareTo(e1.getValue()));
|
||||
|
||||
Map<String, Double> sorted = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Double> entry : entries) {
|
||||
sorted.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
return new Centroid(sorted);
|
||||
}
|
||||
|
||||
private static List<Record> datasetWithTaggedArtists(List<String> artists, Set<String> topTags) throws IOException {
|
||||
List<Record> records = new ArrayList<>();
|
||||
for (String artist : artists) {
|
||||
Map<String, Double> tags = lastFm
|
||||
.topTagsFor(artist)
|
||||
.execute()
|
||||
.body()
|
||||
.all();
|
||||
|
||||
// Only keep popular tags.
|
||||
tags
|
||||
.entrySet()
|
||||
.removeIf(e -> !topTags.contains(e.getKey()));
|
||||
|
||||
records.add(new Record(artist, tags));
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
private static Set<String> getTop100Tags() throws IOException {
|
||||
return lastFm
|
||||
.topTags()
|
||||
.execute()
|
||||
.body()
|
||||
.all();
|
||||
}
|
||||
|
||||
private static List<String> getTop100Artists() throws IOException {
|
||||
List<String> artists = new ArrayList<>();
|
||||
for (int i = 1; i <= 2; i++) {
|
||||
artists.addAll(lastFm
|
||||
.topArtists(i)
|
||||
.execute()
|
||||
.body()
|
||||
.all());
|
||||
}
|
||||
|
||||
return artists;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import okhttp3.HttpUrl;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.GET;
|
||||
import retrofit2.http.Query;
|
||||
|
||||
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
public interface LastFmService {
|
||||
|
||||
@GET("/2.0/?method=chart.gettopartists&format=json&limit=50")
|
||||
Call<Artists> topArtists(@Query("page") int page);
|
||||
|
||||
@GET("/2.0/?method=artist.gettoptags&format=json&limit=20&autocorrect=1")
|
||||
Call<Tags> topTagsFor(@Query("artist") String artist);
|
||||
|
||||
@GET("/2.0/?method=chart.gettoptags&format=json&limit=100")
|
||||
Call<TopTags> topTags();
|
||||
|
||||
/**
|
||||
* HTTP interceptor to intercept all HTTP requests and add the API key to them.
|
||||
*/
|
||||
class Authenticator implements Interceptor {
|
||||
|
||||
private final String apiKey;
|
||||
|
||||
Authenticator(String apiKey) {
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
HttpUrl url = chain
|
||||
.request()
|
||||
.url()
|
||||
.newBuilder()
|
||||
.addQueryParameter("api_key", apiKey)
|
||||
.build();
|
||||
Request request = chain
|
||||
.request()
|
||||
.newBuilder()
|
||||
.url(url)
|
||||
.build();
|
||||
|
||||
return chain.proceed(request);
|
||||
}
|
||||
}
|
||||
|
||||
@JsonAutoDetect(fieldVisibility = ANY)
|
||||
class TopTags {
|
||||
|
||||
private Map<String, Object> tags;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Set<String> all() {
|
||||
List<Map<String, Object>> topTags = (List<Map<String, Object>>) tags.get("tag");
|
||||
return topTags
|
||||
.stream()
|
||||
.map(e -> ((String) e.get("name")))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
|
||||
@JsonAutoDetect(fieldVisibility = ANY)
|
||||
class Tags {
|
||||
|
||||
@JsonProperty("toptags") private Map<String, Object> topTags;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String, Double> all() {
|
||||
try {
|
||||
Map<String, Double> all = new HashMap<>();
|
||||
List<Map<String, Object>> tags = (List<Map<String, Object>>) topTags.get("tag");
|
||||
for (Map<String, Object> tag : tags) {
|
||||
all.put(((String) tag.get("name")), ((Integer) tag.get("count")).doubleValue());
|
||||
}
|
||||
|
||||
return all;
|
||||
} catch (Exception e) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@JsonAutoDetect(fieldVisibility = ANY)
|
||||
class Artists {
|
||||
|
||||
private Map<String, Object> artists;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public List<String> all() {
|
||||
try {
|
||||
List<Map<String, Object>> artists = (List<Map<String, Object>>) this.artists.get("artist");
|
||||
return artists
|
||||
.stream()
|
||||
.map(e -> ((String) e.get("name")))
|
||||
.collect(toList());
|
||||
} catch (Exception e) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.algorithms.kmeans;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Encapsulates all feature values for a few attributes. Optionally each record
|
||||
* can be described with the {@link #description} field.
|
||||
*/
|
||||
public class Record {
|
||||
|
||||
/**
|
||||
* The record description. For example, this can be the artist name for the famous musician
|
||||
* example.
|
||||
*/
|
||||
private final String description;
|
||||
|
||||
/**
|
||||
* Encapsulates all attributes and their corresponding values, i.e. features.
|
||||
*/
|
||||
private final Map<String, Double> features;
|
||||
|
||||
public Record(String description, Map<String, Double> features) {
|
||||
this.description = description;
|
||||
this.features = features;
|
||||
}
|
||||
|
||||
public Record(Map<String, Double> features) {
|
||||
this("", features);
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public Map<String, Double> getFeatures() {
|
||||
return features;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String prefix = description == null || description
|
||||
.trim()
|
||||
.isEmpty() ? "Record" : description;
|
||||
|
||||
return prefix + ": " + features;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
Record record = (Record) o;
|
||||
return Objects.equals(getDescription(), record.getDescription()) && Objects.equals(getFeatures(), record.getFeatures());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(getDescription(), getFeatures());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.algorithms.printtriangles;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class PrintTriangleExamples {
|
||||
|
||||
public static String printARightTriangle(int N) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int r = 1; r <= N; r++) {
|
||||
for (int j = 1; j <= r; j++) {
|
||||
result.append("*");
|
||||
}
|
||||
result.append(System.lineSeparator());
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String printAnIsoscelesTriangle(int N) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int r = 1; r <= N; r++) {
|
||||
for (int sp = 1; sp <= N - r; sp++) {
|
||||
result.append(" ");
|
||||
}
|
||||
for (int c = 1; c <= (r * 2) - 1; c++) {
|
||||
result.append("*");
|
||||
}
|
||||
result.append(System.lineSeparator());
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String printAnIsoscelesTriangleUsingStringUtils(int N) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (int r = 1; r <= N; r++) {
|
||||
result.append(StringUtils.repeat(' ', N - r));
|
||||
result.append(StringUtils.repeat('*', 2 * r - 1));
|
||||
result.append(System.lineSeparator());
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String printAnIsoscelesTriangleUsingSubstring(int N) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1);
|
||||
|
||||
for (int r = 0; r < N; r++) {
|
||||
result.append(helperString.substring(r, N + 2 * r));
|
||||
result.append(System.lineSeparator());
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(printARightTriangle(5));
|
||||
System.out.println(printAnIsoscelesTriangle(5));
|
||||
System.out.println(printAnIsoscelesTriangleUsingStringUtils(5));
|
||||
System.out.println(printAnIsoscelesTriangleUsingSubstring(5));
|
||||
}
|
||||
|
||||
}
|
||||
3384
algorithms-miscellaneous-3/src/main/resources/kmeans/artists.json
Normal file
3384
algorithms-miscellaneous-3/src/main/resources/kmeans/artists.json
Normal file
File diff suppressed because it is too large
Load Diff
490
algorithms-miscellaneous-3/src/main/resources/kmeans/lastfm.json
Normal file
490
algorithms-miscellaneous-3/src/main/resources/kmeans/lastfm.json
Normal file
@@ -0,0 +1,490 @@
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Radiohead"
|
||||
},
|
||||
{
|
||||
"name": "Red Hot Chili Peppers"
|
||||
},
|
||||
{
|
||||
"name": "Coldplay"
|
||||
},
|
||||
{
|
||||
"name": "Nirvana"
|
||||
},
|
||||
{
|
||||
"name": "Panic! at the Disco"
|
||||
},
|
||||
{
|
||||
"name": "The Cure"
|
||||
},
|
||||
{
|
||||
"name": "Linkin Park"
|
||||
},
|
||||
{
|
||||
"name": "Radiohead"
|
||||
},
|
||||
{
|
||||
"name": "Red Hot Chili Peppers"
|
||||
},
|
||||
{
|
||||
"name": "Coldplay"
|
||||
},
|
||||
{
|
||||
"name": "Nirvana"
|
||||
},
|
||||
{
|
||||
"name": "Panic! at the Disco"
|
||||
},
|
||||
{
|
||||
"name": "The Cure"
|
||||
},
|
||||
{
|
||||
"name": "Linkin Park"
|
||||
},
|
||||
{
|
||||
"name": "Muse"
|
||||
},
|
||||
{
|
||||
"name": "Maroon 5"
|
||||
},
|
||||
{
|
||||
"name": "Foo Fighters"
|
||||
},
|
||||
{
|
||||
"name": "Paramore"
|
||||
},
|
||||
{
|
||||
"name": "Oasis"
|
||||
},
|
||||
{
|
||||
"name": "Fall Out Boy"
|
||||
},
|
||||
{
|
||||
"name": "OneRepublic"
|
||||
},
|
||||
{
|
||||
"name": "Weezer"
|
||||
},
|
||||
{
|
||||
"name": "System of a Down"
|
||||
},
|
||||
{
|
||||
"name": "The White Stripes"
|
||||
}
|
||||
],
|
||||
"name": "rock, alternative"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Lil Nas X"
|
||||
},
|
||||
{
|
||||
"name": "Post Malone"
|
||||
},
|
||||
{
|
||||
"name": "Drake"
|
||||
},
|
||||
{
|
||||
"name": "Kanye West"
|
||||
},
|
||||
{
|
||||
"name": "Kendrick Lamar"
|
||||
},
|
||||
{
|
||||
"name": "Tyler, the Creator"
|
||||
},
|
||||
{
|
||||
"name": "Eminem"
|
||||
},
|
||||
{
|
||||
"name": "Childish Gambino"
|
||||
},
|
||||
{
|
||||
"name": "Frank Ocean"
|
||||
},
|
||||
{
|
||||
"name": "Lil Nas X"
|
||||
},
|
||||
{
|
||||
"name": "Post Malone"
|
||||
},
|
||||
{
|
||||
"name": "Drake"
|
||||
},
|
||||
{
|
||||
"name": "Kanye West"
|
||||
},
|
||||
{
|
||||
"name": "Kendrick Lamar"
|
||||
},
|
||||
{
|
||||
"name": "Tyler, the Creator"
|
||||
},
|
||||
{
|
||||
"name": "Eminem"
|
||||
},
|
||||
{
|
||||
"name": "Childish Gambino"
|
||||
},
|
||||
{
|
||||
"name": "Frank Ocean"
|
||||
},
|
||||
{
|
||||
"name": "Lizzo"
|
||||
},
|
||||
{
|
||||
"name": "Travi$ Scott"
|
||||
},
|
||||
{
|
||||
"name": "A$AP Rocky"
|
||||
},
|
||||
{
|
||||
"name": "Nicki Minaj"
|
||||
},
|
||||
{
|
||||
"name": "xxxtentacion"
|
||||
}
|
||||
],
|
||||
"name": "Hip-Hop, rap"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Arctic Monkeys"
|
||||
},
|
||||
{
|
||||
"name": "Imagine Dragons"
|
||||
},
|
||||
{
|
||||
"name": "The Killers"
|
||||
},
|
||||
{
|
||||
"name": "Gorillaz"
|
||||
},
|
||||
{
|
||||
"name": "The Black Keys"
|
||||
},
|
||||
{
|
||||
"name": "Arctic Monkeys"
|
||||
},
|
||||
{
|
||||
"name": "Imagine Dragons"
|
||||
},
|
||||
{
|
||||
"name": "The Killers"
|
||||
},
|
||||
{
|
||||
"name": "Gorillaz"
|
||||
},
|
||||
{
|
||||
"name": "The Black Keys"
|
||||
},
|
||||
{
|
||||
"name": "Twenty One Pilots"
|
||||
},
|
||||
{
|
||||
"name": "Ellie Goulding"
|
||||
},
|
||||
{
|
||||
"name": "Florence + the Machine"
|
||||
},
|
||||
{
|
||||
"name": "Vampire Weekend"
|
||||
},
|
||||
{
|
||||
"name": "The Smiths"
|
||||
},
|
||||
{
|
||||
"name": "The Strokes"
|
||||
},
|
||||
{
|
||||
"name": "MGMT"
|
||||
},
|
||||
{
|
||||
"name": "Foster the People"
|
||||
},
|
||||
{
|
||||
"name": "Two Door Cinema Club"
|
||||
},
|
||||
{
|
||||
"name": "Cage the Elephant"
|
||||
},
|
||||
{
|
||||
"name": "Arcade Fire"
|
||||
},
|
||||
{
|
||||
"name": "The 1975"
|
||||
}
|
||||
],
|
||||
"name": "indie, alternative"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Ed Sheeran"
|
||||
},
|
||||
{
|
||||
"name": "Tame Impala"
|
||||
},
|
||||
{
|
||||
"name": "Ed Sheeran"
|
||||
},
|
||||
{
|
||||
"name": "Tame Impala"
|
||||
},
|
||||
{
|
||||
"name": "Green Day"
|
||||
},
|
||||
{
|
||||
"name": "Metallica"
|
||||
},
|
||||
{
|
||||
"name": "blink-182"
|
||||
},
|
||||
{
|
||||
"name": "Bon Iver"
|
||||
},
|
||||
{
|
||||
"name": "The Clash"
|
||||
}
|
||||
],
|
||||
"name": "rock, punk rock"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Calvin Harris"
|
||||
},
|
||||
{
|
||||
"name": "The Weeknd"
|
||||
},
|
||||
{
|
||||
"name": "The Chainsmokers"
|
||||
},
|
||||
{
|
||||
"name": "Daft Punk"
|
||||
},
|
||||
{
|
||||
"name": "Marshmello"
|
||||
},
|
||||
{
|
||||
"name": "David Guetta"
|
||||
},
|
||||
{
|
||||
"name": "Calvin Harris"
|
||||
},
|
||||
{
|
||||
"name": "The Weeknd"
|
||||
},
|
||||
{
|
||||
"name": "The Chainsmokers"
|
||||
},
|
||||
{
|
||||
"name": "Daft Punk"
|
||||
},
|
||||
{
|
||||
"name": "Marshmello"
|
||||
},
|
||||
{
|
||||
"name": "David Guetta"
|
||||
},
|
||||
{
|
||||
"name": "Avicii"
|
||||
},
|
||||
{
|
||||
"name": "Kygo"
|
||||
},
|
||||
{
|
||||
"name": "Martin Garrix"
|
||||
},
|
||||
{
|
||||
"name": "Major Lazer"
|
||||
},
|
||||
{
|
||||
"name": "Depeche Mode"
|
||||
}
|
||||
],
|
||||
"name": "electronic, dance"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Queen"
|
||||
},
|
||||
{
|
||||
"name": "The Beatles"
|
||||
},
|
||||
{
|
||||
"name": "David Bowie"
|
||||
},
|
||||
{
|
||||
"name": "Fleetwood Mac"
|
||||
},
|
||||
{
|
||||
"name": "Pink Floyd"
|
||||
},
|
||||
{
|
||||
"name": "The Rolling Stones"
|
||||
},
|
||||
{
|
||||
"name": "Led Zeppelin"
|
||||
},
|
||||
{
|
||||
"name": "Queen"
|
||||
},
|
||||
{
|
||||
"name": "The Beatles"
|
||||
},
|
||||
{
|
||||
"name": "David Bowie"
|
||||
},
|
||||
{
|
||||
"name": "Fleetwood Mac"
|
||||
},
|
||||
{
|
||||
"name": "Pink Floyd"
|
||||
},
|
||||
{
|
||||
"name": "The Rolling Stones"
|
||||
},
|
||||
{
|
||||
"name": "Led Zeppelin"
|
||||
},
|
||||
{
|
||||
"name": "Elton John"
|
||||
}
|
||||
],
|
||||
"name": "classic rock, rock"
|
||||
},
|
||||
{
|
||||
"children": [
|
||||
{
|
||||
"name": "Billie Eilish"
|
||||
},
|
||||
{
|
||||
"name": "Ariana Grande"
|
||||
},
|
||||
{
|
||||
"name": "Taylor Swift"
|
||||
},
|
||||
{
|
||||
"name": "Beyoncé"
|
||||
},
|
||||
{
|
||||
"name": "Shawn Mendes"
|
||||
},
|
||||
{
|
||||
"name": "Rihanna"
|
||||
},
|
||||
{
|
||||
"name": "Lana Del Rey"
|
||||
},
|
||||
{
|
||||
"name": "Katy Perry"
|
||||
},
|
||||
{
|
||||
"name": "Lady Gaga"
|
||||
},
|
||||
{
|
||||
"name": "Miley Cyrus"
|
||||
},
|
||||
{
|
||||
"name": "Mark Ronson"
|
||||
},
|
||||
{
|
||||
"name": "Madonna"
|
||||
},
|
||||
{
|
||||
"name": "Lorde"
|
||||
},
|
||||
{
|
||||
"name": "Khalid"
|
||||
},
|
||||
{
|
||||
"name": "Billie Eilish"
|
||||
},
|
||||
{
|
||||
"name": "Ariana Grande"
|
||||
},
|
||||
{
|
||||
"name": "Taylor Swift"
|
||||
},
|
||||
{
|
||||
"name": "Beyoncé"
|
||||
},
|
||||
{
|
||||
"name": "Shawn Mendes"
|
||||
},
|
||||
{
|
||||
"name": "Rihanna"
|
||||
},
|
||||
{
|
||||
"name": "Lana Del Rey"
|
||||
},
|
||||
{
|
||||
"name": "Katy Perry"
|
||||
},
|
||||
{
|
||||
"name": "Lady Gaga"
|
||||
},
|
||||
{
|
||||
"name": "Miley Cyrus"
|
||||
},
|
||||
{
|
||||
"name": "Mark Ronson"
|
||||
},
|
||||
{
|
||||
"name": "Madonna"
|
||||
},
|
||||
{
|
||||
"name": "Lorde"
|
||||
},
|
||||
{
|
||||
"name": "Khalid"
|
||||
},
|
||||
{
|
||||
"name": "Sia"
|
||||
},
|
||||
{
|
||||
"name": "Sam Smith"
|
||||
},
|
||||
{
|
||||
"name": "Halsey"
|
||||
},
|
||||
{
|
||||
"name": "Michael Jackson"
|
||||
},
|
||||
{
|
||||
"name": "Charli XCX"
|
||||
},
|
||||
{
|
||||
"name": "Britney Spears"
|
||||
},
|
||||
{
|
||||
"name": "Dua Lipa"
|
||||
},
|
||||
{
|
||||
"name": "Jonas Brothers"
|
||||
},
|
||||
{
|
||||
"name": "Bruno Mars"
|
||||
},
|
||||
{
|
||||
"name": "Carly Rae Jepsen"
|
||||
},
|
||||
{
|
||||
"name": "P!nk"
|
||||
},
|
||||
{
|
||||
"name": "Adele"
|
||||
}
|
||||
],
|
||||
"name": "pop, female vocalists"
|
||||
}
|
||||
],
|
||||
"name": "Musicians"
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<!DOCTYPE html>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
.node circle {
|
||||
fill: #fff;
|
||||
stroke: steelblue;
|
||||
stroke-width: 1.5px;
|
||||
}
|
||||
|
||||
.node {
|
||||
font: 10px sans-serif;
|
||||
}
|
||||
|
||||
.link {
|
||||
fill: none;
|
||||
stroke: #ccc;
|
||||
stroke-width: 1.5px;
|
||||
}
|
||||
</style>
|
||||
<body>
|
||||
<script src="http://d3js.org/d3.v3.min.js"></script>
|
||||
<script>
|
||||
var diameter = 1100;
|
||||
var tree = d3.layout.tree()
|
||||
.size([360, diameter / 2 - 300])
|
||||
.separation(function (a, b) {
|
||||
return (a.parent == b.parent ? 1 : 2) / a.depth;
|
||||
});
|
||||
var diagonal = d3.svg.diagonal.radial()
|
||||
.projection(function (d) {
|
||||
return [d.y, d.x / 180 * Math.PI];
|
||||
});
|
||||
var svg = d3.select("body").append("svg")
|
||||
.attr("width", diameter)
|
||||
.attr("height", diameter - 150)
|
||||
.append("g")
|
||||
.attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")");
|
||||
d3.json("lastfm.json", function (error, root) {
|
||||
var nodes = tree.nodes(root),
|
||||
links = tree.links(nodes);
|
||||
var link = svg.selectAll(".link")
|
||||
.data(links)
|
||||
.enter().append("path")
|
||||
.attr("class", "link")
|
||||
.attr("d", diagonal);
|
||||
var node = svg.selectAll(".node")
|
||||
.data(nodes)
|
||||
.enter().append("g")
|
||||
.attr("class", "node")
|
||||
.attr("transform", function (d) {
|
||||
return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
|
||||
})
|
||||
node.append("circle")
|
||||
.attr("r", 4.5);
|
||||
node.append("text")
|
||||
.attr("dy", ".31em")
|
||||
.attr("text-anchor", function (d) {
|
||||
return d.x < 180 ? "start" : "end";
|
||||
})
|
||||
.attr("transform", function (d) {
|
||||
return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)";
|
||||
})
|
||||
.text(function (d) {
|
||||
return d.name;
|
||||
});
|
||||
});
|
||||
d3.select(self.frameElement).style("height", diameter - 150 + "px");
|
||||
</script>
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.baeldung.algorithms.breadthfirstsearch;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class BreadthFirstSearchAlgorithmUnitTest {
|
||||
|
||||
private Tree<Integer> root;
|
||||
private Tree<Integer> rootFirstChild;
|
||||
private Tree<Integer> depthMostChild;
|
||||
private Tree<Integer> rootSecondChild;
|
||||
|
||||
private Node<Integer> start;
|
||||
private Node<Integer> firstNeighbor;
|
||||
private Node<Integer> firstNeighborNeighbor;
|
||||
private Node<Integer> secondNeighbor;
|
||||
|
||||
@Test
|
||||
void givenTree_whenSearchTen_thenRoot() {
|
||||
initTree();
|
||||
assertThat(BreadthFirstSearchAlgorithm.search(10, root)).isPresent().contains(root);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTree_whenSearchThree_thenDepthMostValue() {
|
||||
initTree();
|
||||
assertThat(BreadthFirstSearchAlgorithm.search(3, root)).isPresent().contains(depthMostChild);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTree_whenSearchFour_thenRootSecondChild() {
|
||||
initTree();
|
||||
assertThat(BreadthFirstSearchAlgorithm.search(4, root)).isPresent().contains(rootSecondChild);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenTree_whenSearchFive_thenNotFound() {
|
||||
initTree();
|
||||
assertThat(BreadthFirstSearchAlgorithm.search(5, root)).isEmpty();
|
||||
}
|
||||
|
||||
private void initTree() {
|
||||
root = Tree.of(10);
|
||||
rootFirstChild = root.addChild(2);
|
||||
depthMostChild = rootFirstChild.addChild(3);
|
||||
rootSecondChild = root.addChild(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNode_whenSearchTen_thenStart() {
|
||||
initNode();
|
||||
assertThat(BreadthFirstSearchAlgorithm.search(10, firstNeighborNeighbor)).isPresent().contains(start);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNode_whenSearchThree_thenNeighborNeighbor() {
|
||||
initNode();
|
||||
assertThat(BreadthFirstSearchAlgorithm.search(3, firstNeighborNeighbor)).isPresent().contains(firstNeighborNeighbor);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNode_whenSearchFour_thenSecondNeighbor() {
|
||||
initNode();
|
||||
assertThat(BreadthFirstSearchAlgorithm.search(4, firstNeighborNeighbor)).isPresent().contains(secondNeighbor);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNode_whenSearchFive_thenNotFound() {
|
||||
initNode();
|
||||
assertThat(BreadthFirstSearchAlgorithm.search(5, firstNeighborNeighbor)).isEmpty();
|
||||
}
|
||||
|
||||
private void initNode() {
|
||||
start = new Node<>(10);
|
||||
firstNeighbor = new Node<>(2);
|
||||
start.connect(firstNeighbor);
|
||||
|
||||
firstNeighborNeighbor = new Node<>(3);
|
||||
firstNeighbor.connect(firstNeighborNeighbor);
|
||||
firstNeighborNeighbor.connect(start);
|
||||
|
||||
secondNeighbor = new Node<>(4);
|
||||
start.connect(secondNeighbor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.baeldung.algorithms.checksortedlist;
|
||||
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingComparators;
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingIterativeApproach;
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingOrderingClass;
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingRecursion;
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SortedListCheckerUnitTest {
|
||||
|
||||
private List<String> sortedListOfString;
|
||||
private List<String> unsortedListOfString;
|
||||
private List<String> singletonList;
|
||||
|
||||
private List<Employee> employeesSortedByName;
|
||||
private List<Employee> employeesNotSortedByName;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY");
|
||||
unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada");
|
||||
singletonList = Collections.singletonList("NY");
|
||||
|
||||
employeesSortedByName = asList(new Employee(1L, "John"), new Employee(2L, "Kevin"), new Employee(3L, "Mike"));
|
||||
employeesNotSortedByName = asList(new Employee(1L, "Kevin"), new Employee(2L, "John"), new Employee(3L, "Mike"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingRecursion_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSingleElementList_whenUsingRecursion_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingRecursion_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.algorithms.interpolationsearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class InterpolationSearchUnitTest {
|
||||
|
||||
private int[] myData;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
myData = new int[]{13,21,34,55,69,73,84,101};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedArray_whenLookingFor84_thenReturn6() {
|
||||
int pos = InterpolationSearch.interpolationSearch(myData, 84);
|
||||
assertEquals(6, pos);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedArray_whenLookingFor19_thenReturnMinusOne() {
|
||||
int pos = InterpolationSearch.interpolationSearch(myData, 19);
|
||||
assertEquals(-1, pos);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.baeldung.algorithms.printtriangles;
|
||||
|
||||
import junitparams.JUnitParamsRunner;
|
||||
import junitparams.Parameters;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(JUnitParamsRunner.class)
|
||||
public class PrintTriangleExamplesUnitTest {
|
||||
|
||||
private static Object[][] rightTriangles() {
|
||||
String expected0 = "";
|
||||
|
||||
String expected2 = "*" + System.lineSeparator()
|
||||
+ "**" + System.lineSeparator();
|
||||
|
||||
String expected5 = "*" + System.lineSeparator()
|
||||
+ "**" + System.lineSeparator()
|
||||
+ "***" + System.lineSeparator()
|
||||
+ "****" + System.lineSeparator()
|
||||
+ "*****" + System.lineSeparator();
|
||||
|
||||
String expected7 = "*" + System.lineSeparator()
|
||||
+ "**" + System.lineSeparator()
|
||||
+ "***" + System.lineSeparator()
|
||||
+ "****" + System.lineSeparator()
|
||||
+ "*****" + System.lineSeparator()
|
||||
+ "******" + System.lineSeparator()
|
||||
+ "*******" + System.lineSeparator();
|
||||
|
||||
return new Object[][] {
|
||||
{ 0, expected0 },
|
||||
{ 2, expected2 },
|
||||
{ 5, expected5 },
|
||||
{ 7, expected7 }
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "rightTriangles")
|
||||
public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printARightTriangle(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
private static Object[][] isoscelesTriangles() {
|
||||
String expected0 = "";
|
||||
|
||||
String expected2 = " *" + System.lineSeparator()
|
||||
+ "***" + System.lineSeparator();
|
||||
|
||||
String expected5 = " *" + System.lineSeparator()
|
||||
+ " ***" + System.lineSeparator()
|
||||
+ " *****" + System.lineSeparator()
|
||||
+ " *******" + System.lineSeparator()
|
||||
+ "*********" + System.lineSeparator();
|
||||
|
||||
String expected7 = " *" + System.lineSeparator()
|
||||
+ " ***" + System.lineSeparator()
|
||||
+ " *****" + System.lineSeparator()
|
||||
+ " *******" + System.lineSeparator()
|
||||
+ " *********" + System.lineSeparator()
|
||||
+ " ***********" + System.lineSeparator()
|
||||
+ "*************" + System.lineSeparator();
|
||||
|
||||
return new Object[][] {
|
||||
{ 0, expected0 },
|
||||
{ 2, expected2 },
|
||||
{ 5, expected5 },
|
||||
{ 7, expected7 }
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "isoscelesTriangles")
|
||||
public void whenPrintAnIsoscelesTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printAnIsoscelesTriangle(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "isoscelesTriangles")
|
||||
public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "isoscelesTriangles")
|
||||
public void whenPrintAnIsoscelesTriangleUsingSubstringIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingSubstring(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
}
|
||||
15
algorithms-miscellaneous-4/README.md
Normal file
15
algorithms-miscellaneous-4/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
## Algorithms - Miscellaneous
|
||||
|
||||
This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](/../algorithms-sorting) and
|
||||
[genetic algorithms](/../algorithms-genetic), have their own dedicated modules.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Multi-Swarm Optimization Algorithm in Java](https://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
- [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List](https://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-3) [[next -->]](/../algorithms-miscellaneous-5)
|
||||
51
algorithms-miscellaneous-4/pom.xml
Normal file
51
algorithms-miscellaneous-4/pom.xml
Normal file
@@ -0,0 +1,51 @@
|
||||
<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>algorithms-miscellaneous-4</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-miscellaneous-4</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<guava.version>27.0.1-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
11
algorithms-miscellaneous-5/README.md
Normal file
11
algorithms-miscellaneous-5/README.md
Normal file
@@ -0,0 +1,11 @@
|
||||
## Algorithms - Miscellaneous
|
||||
|
||||
This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](/../algorithms-sorting) and
|
||||
[genetic algorithms](/../algorithms-genetic), have their own dedicated modules.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
|
||||
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)
|
||||
57
algorithms-miscellaneous-5/pom.xml
Normal file
57
algorithms-miscellaneous-5/pom.xml
Normal file
@@ -0,0 +1,57 @@
|
||||
<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>algorithms-miscellaneous-5</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-miscellaneous-5</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>pl.allegro.finance</groupId>
|
||||
<artifactId>tradukisto</artifactId>
|
||||
<version>${tradukisto.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<tradukisto.version>1.0.1</tradukisto.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.algorithms.knapsack;
|
||||
|
||||
public class Knapsack {
|
||||
|
||||
public int knapsackRec(int[] w, int[] v, int n, int W) {
|
||||
if (n <= 0) {
|
||||
return 0;
|
||||
} else if (w[n - 1] > W) {
|
||||
return knapsackRec(w, v, n - 1, W);
|
||||
} else {
|
||||
return Math.max(knapsackRec(w, v, n - 1, W), v[n - 1] + knapsackRec(w, v, n - 1, W - w[n - 1]));
|
||||
}
|
||||
}
|
||||
|
||||
public int knapsackDP(int[] w, int[] v, int n, int W) {
|
||||
if (n <= 0 || W <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int[][] m = new int[n + 1][W + 1];
|
||||
for (int j = 0; j <= W; j++) {
|
||||
m[0][j] = 0;
|
||||
}
|
||||
|
||||
for (int i = 1; i <= n; i++) {
|
||||
for (int j = 1; j <= W; j++) {
|
||||
if (w[i - 1] > j) {
|
||||
m[i][j] = m[i - 1][j];
|
||||
} else {
|
||||
m[i][j] = Math.max(m[i - 1][j], m[i - 1][j - w[i - 1]] + v[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return m[n][W];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.algorithms.knapsack;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class KnapsackUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() {
|
||||
final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 };
|
||||
final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 };
|
||||
final int n = 10;
|
||||
final int W = 67;
|
||||
final Knapsack knapsack = new Knapsack();
|
||||
|
||||
assertEquals(1270, knapsack.knapsackRec(w, v, n, W));
|
||||
assertEquals(1270, knapsack.knapsackDP(w, v, n, W));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZeroItems_whenCalculateMax_thenOutputZero() {
|
||||
final int[] w = new int[] {};
|
||||
final int[] v = new int[] {};
|
||||
final int n = 0;
|
||||
final int W = 67;
|
||||
final Knapsack knapsack = new Knapsack();
|
||||
|
||||
assertEquals(0, knapsack.knapsackRec(w, v, n, W));
|
||||
assertEquals(0, knapsack.knapsackDP(w, v, n, W));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() {
|
||||
final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 };
|
||||
final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 };
|
||||
final int n = 10;
|
||||
final int W = 0;
|
||||
final Knapsack knapsack = new Knapsack();
|
||||
|
||||
assertEquals(0, knapsack.knapsackRec(w, v, n, W));
|
||||
assertEquals(0, knapsack.knapsackDP(w, v, n, W));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,19 @@
|
||||
## Relevant articles:
|
||||
## Algorithms - Sorting
|
||||
|
||||
- [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort)
|
||||
This module contains articles about sorting algorithms.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Bubble Sort in Java](https://www.baeldung.com/java-bubble-sort)
|
||||
- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort)
|
||||
- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort)
|
||||
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
|
||||
- [Heap Sort in Java](https://www.baeldung.com/java-heap-sort)
|
||||
- [Shell Sort in Java](https://www.baeldung.com/java-shell-sort)
|
||||
- [Counting Sort in Java](https://www.baeldung.com/java-counting-sort)
|
||||
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
|
||||
- [How an In-Place Sorting Algorithm Works](https://www.baeldung.com/java-in-place-sorting)
|
||||
- [Selection Sort in Java](https://www.baeldung.com/java-selection-sort)
|
||||
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
|
||||
- [Radix Sort in Java](https://www.baeldung.com/java-radix-sort)
|
||||
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
|
||||
|
||||
@@ -28,6 +28,12 @@
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter-api.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
@@ -52,6 +58,7 @@
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<junit-jupiter-api.version>5.3.1</junit-jupiter-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.bucketsort;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class IntegerBucketSorter implements Sorter<Integer> {
|
||||
|
||||
private final Comparator<Integer> comparator;
|
||||
|
||||
public IntegerBucketSorter(Comparator<Integer> comparator) {
|
||||
this.comparator = comparator;
|
||||
}
|
||||
|
||||
public IntegerBucketSorter() {
|
||||
comparator = Comparator.naturalOrder();
|
||||
}
|
||||
|
||||
public List<Integer> sort(List<Integer> arrayToSort) {
|
||||
|
||||
List<List<Integer>> buckets = splitIntoUnsortedBuckets(arrayToSort);
|
||||
|
||||
for(List<Integer> bucket : buckets){
|
||||
bucket.sort(comparator);
|
||||
}
|
||||
|
||||
return concatenateSortedBuckets(buckets);
|
||||
}
|
||||
|
||||
private List<Integer> concatenateSortedBuckets(List<List<Integer>> buckets){
|
||||
List<Integer> sortedArray = new LinkedList<>();
|
||||
for(List<Integer> bucket : buckets){
|
||||
sortedArray.addAll(bucket);
|
||||
}
|
||||
return sortedArray;
|
||||
}
|
||||
|
||||
private List<List<Integer>> splitIntoUnsortedBuckets(List<Integer> initialList){
|
||||
|
||||
final int max = findMax(initialList);
|
||||
final int numberOfBuckets = (int) Math.sqrt(initialList.size());
|
||||
|
||||
List<List<Integer>> buckets = new ArrayList<>();
|
||||
for(int i = 0; i < numberOfBuckets; i++) buckets.add(new ArrayList<>());
|
||||
|
||||
//distribute the data
|
||||
for (int i : initialList) {
|
||||
buckets.get(hash(i, max, numberOfBuckets)).add(i);
|
||||
}
|
||||
return buckets;
|
||||
|
||||
}
|
||||
|
||||
private int findMax(List<Integer> input){
|
||||
int m = Integer.MIN_VALUE;
|
||||
for (int i : input){
|
||||
m = Math.max(i, m);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
private static int hash(int i, int max, int numberOfBuckets) {
|
||||
return (int) ((double) i / max * (numberOfBuckets - 1));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.bucketsort;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface Sorter<T> {
|
||||
|
||||
List<T> sort(List<T> arrayToSort);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.algorithms.counting;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class CountingSort {
|
||||
|
||||
public static int[] sort(int[] input, int k) {
|
||||
verifyPreconditions(input, k);
|
||||
if (input.length == 0) return input;
|
||||
|
||||
int[] c = countElements(input, k);
|
||||
int[] sorted = new int[input.length];
|
||||
for (int i = input.length - 1; i >= 0; i--) {
|
||||
int current = input[i];
|
||||
sorted[c[current] - 1] = current;
|
||||
c[current] -= 1;
|
||||
}
|
||||
|
||||
return sorted;
|
||||
}
|
||||
|
||||
static int[] countElements(int[] input, int k) {
|
||||
int[] c = new int[k + 1];
|
||||
Arrays.fill(c, 0);
|
||||
for (int i : input) {
|
||||
c[i] += 1;
|
||||
}
|
||||
|
||||
for (int i = 1; i < c.length; i++) {
|
||||
c[i] += c[i - 1];
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
private static void verifyPreconditions(int[] input, int k) {
|
||||
if (input == null) {
|
||||
throw new IllegalArgumentException("Input is required");
|
||||
}
|
||||
|
||||
int min = IntStream.of(input).min().getAsInt();
|
||||
int max = IntStream.of(input).max().getAsInt();
|
||||
|
||||
if (min < 0 || max > k) {
|
||||
throw new IllegalArgumentException("The input numbers should be between zero and " + k);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.algorithms.inoutsort;
|
||||
|
||||
public class InOutSort {
|
||||
|
||||
public static int[] reverseInPlace(int A[]) {
|
||||
int n = A.length;
|
||||
for (int i = 0; i < n / 2; i++) {
|
||||
int temp = A[i];
|
||||
A[i] = A[n - 1 - i];
|
||||
A[n - 1 - i] = temp;
|
||||
}
|
||||
|
||||
return A;
|
||||
}
|
||||
|
||||
public static int[] reverseOutOfPlace(int A[]) {
|
||||
int n = A.length;
|
||||
int[] B = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
B[n - i - 1] = A[i];
|
||||
}
|
||||
|
||||
return B;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.algorithms.radixsort;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class RadixSort {
|
||||
|
||||
public static void sort(int numbers[]) {
|
||||
int maximumNumber = findMaximumNumberIn(numbers);
|
||||
|
||||
int numberOfDigits = calculateNumberOfDigitsIn(maximumNumber);
|
||||
|
||||
int placeValue = 1;
|
||||
|
||||
while (numberOfDigits-- > 0) {
|
||||
applyCountingSortOn(numbers, placeValue);
|
||||
placeValue *= 10;
|
||||
}
|
||||
}
|
||||
|
||||
private static void applyCountingSortOn(int[] numbers, int placeValue) {
|
||||
int range = 10; // radix or the base
|
||||
|
||||
int length = numbers.length;
|
||||
int[] frequency = new int[range];
|
||||
int[] sortedValues = new int[length];
|
||||
|
||||
for (int i = 0; i < length; i++) {
|
||||
int digit = (numbers[i] / placeValue) % range;
|
||||
frequency[digit]++;
|
||||
}
|
||||
|
||||
for (int i = 1; i < range; i++) {
|
||||
frequency[i] += frequency[i - 1];
|
||||
}
|
||||
|
||||
for (int i = length - 1; i >= 0; i--) {
|
||||
int digit = (numbers[i] / placeValue) % range;
|
||||
sortedValues[frequency[digit] - 1] = numbers[i];
|
||||
frequency[digit]--;
|
||||
}
|
||||
|
||||
System.arraycopy(sortedValues, 0, numbers, 0, length);
|
||||
}
|
||||
|
||||
private static int calculateNumberOfDigitsIn(int number) {
|
||||
return (int) Math.log10(number) + 1; // valid only if number > 0
|
||||
}
|
||||
|
||||
private static int findMaximumNumberIn(int[] arr) {
|
||||
return Arrays.stream(arr).max().getAsInt();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.algorithms.selectionsort;
|
||||
|
||||
public class SelectionSort {
|
||||
|
||||
public static void sortAscending(final int[] arr) {
|
||||
for (int i = 0; i < arr.length - 1; i++) {
|
||||
int minElementIndex = i;
|
||||
for (int j = i + 1; j < arr.length; j++) {
|
||||
if (arr[minElementIndex] > arr[j]) {
|
||||
minElementIndex = j;
|
||||
}
|
||||
}
|
||||
|
||||
if (minElementIndex != i) {
|
||||
int temp = arr[i];
|
||||
arr[i] = arr[minElementIndex];
|
||||
arr[minElementIndex] = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void sortDescending(final int[] arr) {
|
||||
for (int i = 0; i < arr.length - 1; i++) {
|
||||
int maxElementIndex = i;
|
||||
for (int j = i + 1; j < arr.length; j++) {
|
||||
if (arr[maxElementIndex] < arr[j]) {
|
||||
maxElementIndex = j;
|
||||
}
|
||||
}
|
||||
|
||||
if (maxElementIndex != i) {
|
||||
int temp = arr[i];
|
||||
arr[i] = arr[maxElementIndex];
|
||||
arr[maxElementIndex] = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.algorithms.shellsort;
|
||||
|
||||
public class ShellSort {
|
||||
|
||||
public static void sort(int arrayToSort[]) {
|
||||
int n = arrayToSort.length;
|
||||
|
||||
for (int gap = n / 2; gap > 0; gap /= 2) {
|
||||
for (int i = gap; i < n; i++) {
|
||||
int key = arrayToSort[i];
|
||||
int j = i;
|
||||
while (j >= gap && arrayToSort[j - gap] > key) {
|
||||
arrayToSort[j] = arrayToSort[j - gap];
|
||||
j -= gap;
|
||||
}
|
||||
arrayToSort[j] = key;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.algorithms.sort.bynumber;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
public final class NaturalOrderComparators {
|
||||
|
||||
private static final String DIGIT_AND_DECIMAL_REGEX = "[^\\d.]";
|
||||
|
||||
private NaturalOrderComparators() {
|
||||
throw new AssertionError("Let's keep this static");
|
||||
}
|
||||
|
||||
public static Comparator<String> createNaturalOrderRegexComparator() {
|
||||
return Comparator.comparingDouble(NaturalOrderComparators::parseStringToNumber);
|
||||
}
|
||||
|
||||
private static double parseStringToNumber(String input){
|
||||
|
||||
final String digitsOnly = input.replaceAll(DIGIT_AND_DECIMAL_REGEX, "");
|
||||
|
||||
if("".equals(digitsOnly)) return 0;
|
||||
|
||||
try{
|
||||
return Double.parseDouble(digitsOnly);
|
||||
}catch (NumberFormatException nfe){
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.string.sorting;
|
||||
package com.baeldung.algorithms.stringsort;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.bucketsort;
|
||||
|
||||
import com.baeldung.bucketsort.IntegerBucketSorter;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class IntegerBucketSorterUnitTest {
|
||||
|
||||
private IntegerBucketSorter sorter;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
sorter = new IntegerBucketSorter();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() {
|
||||
|
||||
List<Integer> unsorted = Arrays.asList(80,50,60,30,20,10,70,0,40,500,600,602,200,15);
|
||||
List<Integer> expected = Arrays.asList(0,10,15,20,30,40,50,60,70,80,200,500,600,602);
|
||||
|
||||
List<Integer> actual = sorter.sort(unsorted);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.algorithms.counting;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CountingSortUnitTest {
|
||||
|
||||
@Test
|
||||
void countElements_GivenAnArray_ShouldCalculateTheFrequencyArrayAsExpected() {
|
||||
int k = 5;
|
||||
int[] input = { 4, 3, 2, 5, 4, 3, 5, 1, 0, 2, 5 };
|
||||
|
||||
int[] c = CountingSort.countElements(input, k);
|
||||
int[] expected = { 1, 2, 4, 6, 8, 11 };
|
||||
assertArrayEquals(expected, c);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sort_GivenAnArray_ShouldSortTheInputAsExpected() {
|
||||
int k = 5;
|
||||
int[] input = { 4, 3, 2, 5, 4, 3, 5, 1, 0, 2, 5 };
|
||||
|
||||
int[] sorted = CountingSort.sort(input, k);
|
||||
|
||||
// Our sorting algorithm and Java's should return the same result
|
||||
Arrays.sort(input);
|
||||
assertArrayEquals(input, sorted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.algorithms.inoutsort;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class InOutSortUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenArray_whenInPlaceSort_thenReversed() {
|
||||
int[] input = {1, 2, 3, 4, 5, 6, 7};
|
||||
int[] expected = {7, 6, 5, 4, 3, 2, 1};
|
||||
assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseInPlace(input));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArray_whenOutOfPlaceSort_thenReversed() {
|
||||
int[] input = {1, 2, 3, 4, 5, 6, 7};
|
||||
int[] expected = {7, 6, 5, 4, 3, 2, 1};
|
||||
assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseOutOfPlace(input));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.algorithms.radixsort;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RadixSortUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUnsortedArray_whenRadixSort_thenArraySorted() {
|
||||
int[] numbers = { 387, 468, 134, 123, 68, 221, 769, 37, 7 };
|
||||
RadixSort.sort(numbers);
|
||||
int[] numbersSorted = { 7, 37, 68, 123, 134, 221, 387, 468, 769 };
|
||||
assertArrayEquals(numbersSorted, numbers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.algorithms.selectionsort;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class SelectionSortUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() {
|
||||
int[] input = { 5, 4, 1, 6, 2 };
|
||||
SelectionSort.sortAscending(input);
|
||||
int[] expected = {1, 2, 4, 5, 6};
|
||||
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() {
|
||||
int[] input = { 5, 4, 1, 6, 2 };
|
||||
SelectionSort.sortDescending(input);
|
||||
int[] expected = {6, 5, 4, 2, 1};
|
||||
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.algorithms.shellsort;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ShellSortUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUnsortedArray_whenShellSort_thenSortedAsc() {
|
||||
int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8};
|
||||
ShellSort.sort(input);
|
||||
int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82};
|
||||
assertArrayEquals("the two arrays are not equal", expected, input);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.algorithms.sort.bynumber;
|
||||
|
||||
import com.baeldung.algorithms.sort.bynumber.NaturalOrderComparators;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class NaturalOrderComparatorsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d");
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
List<String> expected = Arrays.asList("a1", "d2.2", "d2.3d", "d2.4", "b3", "c4");
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d");
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.4", "b3", "c4");
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d");
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
List<String> expected = Arrays.asList("d2.3.3d", "a1", "d2.2", "d2.f4", "b3", "c4");
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5
|
||||
|
||||
List<String> expected = Arrays.asList("b3ght3.2", "something65.thensomething5", "a1b2c5" );
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() {
|
||||
|
||||
List<String> testStrings = Arrays.asList("a", "c", "d", "e");
|
||||
List<String> expected = new ArrayList<>(testStrings);
|
||||
|
||||
testStrings.sort(NaturalOrderComparators.createNaturalOrderRegexComparator());
|
||||
|
||||
assertEquals(expected, testStrings);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
package com.baeldung.string.sorting;
|
||||
package com.baeldung.algorithms.stringsort;
|
||||
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.string.sorting.AnagramValidator;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class AnagramValidatorUnitTest {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package com.baeldung.string.sorting;
|
||||
|
||||
import java.util.Arrays;
|
||||
package com.baeldung.algorithms.stringsort;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class SortStringUnitTest {
|
||||
@@ -1,3 +1,7 @@
|
||||
## Relevant articles:
|
||||
## Animal Sniffer Maven Plugin
|
||||
|
||||
[Introduction to Animal Sniffer Maven Plugin](http://www.baeldung.com/maven-animal-sniffer)
|
||||
This module contains articles about the Animal Sniffer Maven Plugin
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
[Introduction to Animal Sniffer Maven Plugin](https://www.baeldung.com/maven-animal-sniffer)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>animal-sniffer-mvn-plugin</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>animal-sniffer-mvn-plugin</name>
|
||||
|
||||
7
annotations/README.md
Normal file
7
annotations/README.md
Normal file
@@ -0,0 +1,7 @@
|
||||
## Annotations
|
||||
|
||||
This module contains articles about Java annotations
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Java Annotation Processing and Creating a Builder](https://www.baeldung.com/java-annotation-processing-builder)
|
||||
@@ -1,2 +0,0 @@
|
||||
### Relevant Articles:
|
||||
- [Java Annotation Processing and Creating a Builder](http://www.baeldung.com/java-annotation-processing-builder)
|
||||
@@ -1,3 +1,7 @@
|
||||
## ANTLR
|
||||
|
||||
This module contains articles about ANTLR
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Java with ANTLR](http://www.baeldung.com/java-antlr)
|
||||
- [Java with ANTLR](https://www.baeldung.com/java-antlr)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user