Sync with upstream
This commit is contained in:
commit
ad60d36ef5
1
.gitignore
vendored
1
.gitignore
vendored
@ -39,7 +39,6 @@ target/
|
||||
spring-openid/src/main/resources/application.properties
|
||||
.recommenders/
|
||||
/spring-hibernate4/nbproject/
|
||||
spring-security-openid/src/main/resources/application.properties
|
||||
|
||||
spring-all/*.log
|
||||
|
||||
|
@ -1,3 +1,4 @@
|
||||
**UPDATE**: The price of "Learn Spring Security OAuth" will permanently change on the 11th of December, along with the upcoming OAuth2 material: http://bit.ly/github-lss
|
||||
|
||||
The Courses
|
||||
==============================
|
||||
|
@ -1,47 +1,46 @@
|
||||
<?xml version="1.0"?>
|
||||
<project
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>akka-http</artifactId>
|
||||
<name>akka-http</name>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>akka-http</artifactId>
|
||||
<name>akka-http</name>
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-http_2.12</artifactId>
|
||||
<version>${akka.http.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-stream_2.12</artifactId>
|
||||
<version>${akka.stream.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-http-jackson_2.12</artifactId>
|
||||
<version>${akka.http.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-http-testkit_2.12</artifactId>
|
||||
<version>${akka.http.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-http_2.12</artifactId>
|
||||
<version>${akka.http.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-stream_2.12</artifactId>
|
||||
<version>${akka.stream.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-http-jackson_2.12</artifactId>
|
||||
<version>${akka.http.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-http-testkit_2.12</artifactId>
|
||||
<version>${akka.http.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<akka.http.version>10.0.11</akka.http.version>
|
||||
<akka.stream.version>2.5.11</akka.stream.version>
|
||||
</properties>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<akka.http.version>10.0.11</akka.http.version>
|
||||
<akka.stream.version>2.5.11</akka.stream.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
@ -1,13 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>akka-streams</artifactId>
|
||||
<name>akka-streams</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
|
@ -1,10 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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-genetic</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-genetic</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
@ -60,5 +61,4 @@
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
</properties>
|
||||
|
||||
|
||||
</project>
|
||||
|
@ -7,8 +7,6 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
|
||||
- [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)
|
||||
|
@ -1,10 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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-1</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-miscellaneous-1</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
@ -43,7 +44,7 @@
|
||||
<groupId>com.github.dpaukov</groupId>
|
||||
<artifactId>combinatoricslib3</artifactId>
|
||||
<version>${combinatoricslib3.version}</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
@ -34,9 +35,9 @@
|
||||
<version>${org.jgrapht.core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jgrapht</groupId>
|
||||
<artifactId>jgrapht-ext</artifactId>
|
||||
<version>${org.jgrapht.ext.version}</version>
|
||||
<groupId>org.jgrapht</groupId>
|
||||
<artifactId>jgrapht-ext</artifactId>
|
||||
<version>${org.jgrapht.ext.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>pl.allegro.finance</groupId>
|
||||
|
@ -14,8 +14,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
- [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)
|
||||
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
|
||||
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4)
|
||||
|
@ -1,3 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
@ -91,4 +92,5 @@
|
||||
<jmh-core.version>1.19</jmh-core.version>
|
||||
<jmh-generator.version>1.19</jmh-generator.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -5,10 +5,10 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
### 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)
|
||||
- [Find the Smallest Missing Integer in an Array](https://www.baeldung.com/java-smallest-missing-integer-in-array)
|
||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5)
|
||||
|
@ -1,10 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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>
|
||||
|
@ -1,25 +0,0 @@
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.string.search.StringSearchAlgorithms;
|
||||
|
||||
public class StringSearchAlgorithmsUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void testStringSearchAlgorithms(){
|
||||
String text = "This is some nice text.";
|
||||
String pattern = "some";
|
||||
|
||||
int realPosition = text.indexOf(pattern);
|
||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == StringSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
}
|
||||
|
||||
}
|
@ -85,4 +85,13 @@ class SmallestMissingPositiveIntegerUnitTest {
|
||||
|
||||
assertThat(result).isEqualTo(input.length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenArrayWithoutZero_whenSearchInUnsortedArrayBooleanArray_thenZero() {
|
||||
int[] input = new int[] {11, 13, 14, 15};
|
||||
|
||||
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
|
||||
|
||||
assertThat(result).isEqualTo(0);
|
||||
}
|
||||
}
|
@ -9,4 +9,7 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||
- [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)
|
||||
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
|
||||
- [How to Determine if a Binary Tree is Balanced](https://www.baeldung.com/java-balanced-binary-tree)
|
||||
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
|
||||
- [Overview of Combinatorial Problems in Java](https://www.baeldung.com/java-combinatorial-algorithms)
|
||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)
|
||||
|
@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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>
|
||||
@ -33,6 +34,11 @@
|
||||
<artifactId>tradukisto</artifactId>
|
||||
<version>${tradukisto.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>28.1-jre</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
|
@ -0,0 +1,67 @@
|
||||
package com.baeldung.algorithms.combinatorics;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static java.util.Collections.swap;
|
||||
|
||||
public class Combinatorics {
|
||||
|
||||
public static List<List<Integer>> permutations(List<Integer> sequence) {
|
||||
List<List<Integer>> results = new ArrayList<>();
|
||||
permutationsInternal(sequence, results, 0);
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void permutationsInternal(List<Integer> sequence, List<List<Integer>> results, int index) {
|
||||
if (index == sequence.size() - 1) {
|
||||
results.add(new ArrayList<>(sequence));
|
||||
}
|
||||
|
||||
for (int i = index; i < sequence.size(); i++) {
|
||||
swap(sequence, i, index);
|
||||
permutationsInternal(sequence, results, index + 1);
|
||||
swap(sequence, i, index);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<List<Integer>> combinations(List<Integer> inputSet, int k) {
|
||||
List<List<Integer>> results = new ArrayList<>();
|
||||
combinationsInternal(inputSet, k, results, new ArrayList<>(), 0);
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void combinationsInternal(
|
||||
List<Integer> inputSet, int k, List<List<Integer>> results, ArrayList<Integer> accumulator, int index) {
|
||||
int leftToAccumulate = k - accumulator.size();
|
||||
int possibleToAcculumate = inputSet.size() - index;
|
||||
|
||||
if (accumulator.size() == k) {
|
||||
results.add(new ArrayList<>(accumulator));
|
||||
} else if (leftToAccumulate <= possibleToAcculumate) {
|
||||
combinationsInternal(inputSet, k, results, accumulator, index + 1);
|
||||
|
||||
accumulator.add(inputSet.get(index));
|
||||
combinationsInternal(inputSet, k, results, accumulator, index + 1);
|
||||
accumulator.remove(accumulator.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<List<Character>> powerSet(List<Character> sequence) {
|
||||
List<List<Character>> results = new ArrayList<>();
|
||||
powerSetInternal(sequence, results, new ArrayList<>(), 0);
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void powerSetInternal(
|
||||
List<Character> set, List<List<Character>> powerSet, List<Character> accumulator, int index) {
|
||||
if (index == set.size()) {
|
||||
powerSet.add(new ArrayList<>(accumulator));
|
||||
} else {
|
||||
accumulator.add(set.get(index));
|
||||
|
||||
powerSetInternal(set, powerSet, accumulator, index + 1);
|
||||
accumulator.remove(accumulator.size() - 1);
|
||||
powerSetInternal(set, powerSet, accumulator, index + 1);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.algorithms.greedy;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
public class Follower {
|
||||
|
||||
@Getter String username;
|
||||
@Getter long count;
|
||||
|
||||
public Follower(String username, long count) {
|
||||
super();
|
||||
this.username = username;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User: " + username + ", Followers: " + count + "\n\r" ;
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.baeldung.algorithms.greedy;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class FollowersPath {
|
||||
|
||||
private List<Follower> accounts;
|
||||
private long count;
|
||||
|
||||
public FollowersPath() {
|
||||
super();
|
||||
this.accounts = new ArrayList<>();
|
||||
}
|
||||
|
||||
public List<Follower> getAccounts() {
|
||||
return accounts;
|
||||
}
|
||||
public long getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void addFollower(String username, long count) {
|
||||
accounts.add(new Follower(username, count));
|
||||
}
|
||||
|
||||
public void addCount(long count) {
|
||||
this.count += count;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String details = "";
|
||||
for(Follower a : accounts) {
|
||||
details+=a.toString() + ", ";
|
||||
}
|
||||
|
||||
return "Total: " + count + ", \n\r" +
|
||||
" Details: { " + "\n\r" +
|
||||
details + "\n\r" +
|
||||
" }";
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package com.baeldung.algorithms.greedy;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class GreedyAlgorithm {
|
||||
|
||||
int currentLevel = 0;
|
||||
final int maxLevel = 3;
|
||||
SocialConnector sc;
|
||||
FollowersPath fp;
|
||||
|
||||
public GreedyAlgorithm(SocialConnector sc) {
|
||||
super();
|
||||
this.sc = sc;
|
||||
this.fp = new FollowersPath();
|
||||
}
|
||||
|
||||
public long findMostFollowersPath(String account) {
|
||||
long max = 0;
|
||||
SocialUser toFollow = null;
|
||||
|
||||
List<SocialUser> followers = sc.getFollowers(account);
|
||||
for (SocialUser el : followers) {
|
||||
long followersCount = el.getFollowersCount();
|
||||
if (followersCount > max) {
|
||||
toFollow = el;
|
||||
max = followersCount;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentLevel < maxLevel - 1) {
|
||||
currentLevel++;
|
||||
max += findMostFollowersPath(toFollow.getUsername());
|
||||
return max;
|
||||
} else {
|
||||
return max;
|
||||
}
|
||||
}
|
||||
|
||||
public FollowersPath getFollowers() {
|
||||
return fp;
|
||||
}
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
package com.baeldung.algorithms.greedy;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class NonGreedyAlgorithm {
|
||||
|
||||
int currentLevel = 0;
|
||||
final int maxLevel = 3;
|
||||
SocialConnector tc;
|
||||
|
||||
public NonGreedyAlgorithm(SocialConnector tc, int level) {
|
||||
super();
|
||||
this.tc = tc;
|
||||
this.currentLevel = level;
|
||||
}
|
||||
|
||||
public long findMostFollowersPath(String account) {
|
||||
List<SocialUser> followers = tc.getFollowers(account);
|
||||
long total = currentLevel > 0 ? followers.size() : 0;
|
||||
|
||||
if (currentLevel < maxLevel ) {
|
||||
currentLevel++;
|
||||
|
||||
long[] count = new long[followers.size()];
|
||||
int i = 0;
|
||||
for (SocialUser el : followers) {
|
||||
NonGreedyAlgorithm sub = new NonGreedyAlgorithm(tc, currentLevel);
|
||||
count[i] = sub.findMostFollowersPath(el.getUsername());
|
||||
i++;
|
||||
}
|
||||
|
||||
long max = 0;
|
||||
for (; i > 0; i--) {
|
||||
if (count[i-1] > max )
|
||||
max = count[i-1];
|
||||
}
|
||||
|
||||
return total + max;
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.algorithms.greedy;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
public class SocialConnector {
|
||||
private boolean isCounterEnabled = true;
|
||||
private int counter = 4;
|
||||
@Getter @Setter List<SocialUser> users;
|
||||
|
||||
public SocialConnector() {
|
||||
users = new ArrayList<>();
|
||||
}
|
||||
|
||||
public boolean switchCounter() {
|
||||
this.isCounterEnabled = !this.isCounterEnabled;
|
||||
return this.isCounterEnabled;
|
||||
}
|
||||
|
||||
public List<SocialUser> getFollowers(String account) {
|
||||
if (counter < 0)
|
||||
throw new IllegalStateException ("API limit reached");
|
||||
else {
|
||||
if(this.isCounterEnabled) counter--;
|
||||
for(SocialUser user : users) {
|
||||
if (user.getUsername().equals(account)) {
|
||||
return user.getFollowers();
|
||||
}
|
||||
}
|
||||
}
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
package com.baeldung.algorithms.greedy;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
public class SocialUser {
|
||||
|
||||
@Getter private String username;
|
||||
@Getter private List<SocialUser> followers;
|
||||
|
||||
public SocialUser(String username) {
|
||||
super();
|
||||
this.username = username;
|
||||
this.followers = new ArrayList<>();
|
||||
}
|
||||
|
||||
public SocialUser(String username, List<SocialUser> followers) {
|
||||
super();
|
||||
this.username = username;
|
||||
this.followers = followers;
|
||||
}
|
||||
|
||||
public long getFollowersCount() {
|
||||
return followers.size();
|
||||
}
|
||||
|
||||
public void addFollowers(List<SocialUser> followers) {
|
||||
this.followers.addAll(followers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return ((SocialUser) obj).getUsername().equals(username);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.algorithms.integerstreammedian;
|
||||
|
||||
import java.util.PriorityQueue;
|
||||
import java.util.Queue;
|
||||
|
||||
import static java.util.Comparator.reverseOrder;
|
||||
|
||||
public class MedianOfIntegerStream {
|
||||
|
||||
private Queue<Integer> minHeap, maxHeap;
|
||||
|
||||
MedianOfIntegerStream() {
|
||||
minHeap = new PriorityQueue<>();
|
||||
maxHeap = new PriorityQueue<>(reverseOrder());
|
||||
}
|
||||
|
||||
void add(int num) {
|
||||
if (!minHeap.isEmpty() && num < minHeap.peek()) {
|
||||
maxHeap.offer(num);
|
||||
if (maxHeap.size() > minHeap.size() + 1) {
|
||||
minHeap.offer(maxHeap.poll());
|
||||
}
|
||||
} else {
|
||||
minHeap.offer(num);
|
||||
if (minHeap.size() > maxHeap.size() + 1) {
|
||||
maxHeap.offer(minHeap.poll());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double getMedian() {
|
||||
int median;
|
||||
if (minHeap.size() < maxHeap.size()) {
|
||||
median = maxHeap.peek();
|
||||
} else if (minHeap.size() > maxHeap.size()) {
|
||||
median = minHeap.peek();
|
||||
} else {
|
||||
median = (minHeap.peek() + maxHeap.peek()) / 2;
|
||||
}
|
||||
return median;
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.algorithms.integerstreammedian;
|
||||
|
||||
import java.util.PriorityQueue;
|
||||
import java.util.Queue;
|
||||
|
||||
import static java.util.Comparator.reverseOrder;
|
||||
|
||||
public class MedianOfIntegerStream2 {
|
||||
|
||||
private Queue<Integer> minHeap, maxHeap;
|
||||
|
||||
MedianOfIntegerStream2() {
|
||||
minHeap = new PriorityQueue<>();
|
||||
maxHeap = new PriorityQueue<>(reverseOrder());
|
||||
}
|
||||
|
||||
void add(int num) {
|
||||
if (minHeap.size() == maxHeap.size()) {
|
||||
maxHeap.offer(num);
|
||||
minHeap.offer(maxHeap.poll());
|
||||
} else {
|
||||
minHeap.offer(num);
|
||||
maxHeap.offer(minHeap.poll());
|
||||
}
|
||||
}
|
||||
|
||||
double getMedian() {
|
||||
int median;
|
||||
if (minHeap.size() > maxHeap.size()) {
|
||||
median = minHeap.peek();
|
||||
} else {
|
||||
median = (minHeap.peek() + maxHeap.peek()) / 2;
|
||||
}
|
||||
return median;
|
||||
}
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
package com.baeldung.algorithms.kruskal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CycleDetector {
|
||||
|
||||
List<DisjointSetInfo> nodes;
|
||||
|
||||
public CycleDetector(int totalNodes) {
|
||||
initDisjointSets(totalNodes);
|
||||
}
|
||||
|
||||
public boolean detectCycle(Integer u, Integer v) {
|
||||
Integer rootU = pathCompressionFind(u);
|
||||
Integer rootV = pathCompressionFind(v);
|
||||
if (rootU.equals(rootV)) {
|
||||
return true;
|
||||
}
|
||||
unionByRank(rootU, rootV);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void initDisjointSets(int totalNodes) {
|
||||
nodes = new ArrayList<>(totalNodes);
|
||||
for (int i = 0; i < totalNodes; i++) {
|
||||
nodes.add(new DisjointSetInfo(i));
|
||||
}
|
||||
}
|
||||
|
||||
private Integer find(Integer node) {
|
||||
Integer parent = nodes.get(node).getParentNode();
|
||||
if (parent.equals(node)) {
|
||||
return node;
|
||||
} else {
|
||||
return find(parent);
|
||||
}
|
||||
}
|
||||
|
||||
private Integer pathCompressionFind(Integer node) {
|
||||
DisjointSetInfo setInfo = nodes.get(node);
|
||||
Integer parent = setInfo.getParentNode();
|
||||
if (parent.equals(node)) {
|
||||
return node;
|
||||
} else {
|
||||
Integer parentNode = find(parent);
|
||||
setInfo.setParentNode(parentNode);
|
||||
return parentNode;
|
||||
}
|
||||
}
|
||||
|
||||
private void union(Integer rootU, Integer rootV) {
|
||||
DisjointSetInfo setInfoU = nodes.get(rootU);
|
||||
setInfoU.setParentNode(rootV);
|
||||
}
|
||||
|
||||
private void unionByRank(int rootU, int rootV) {
|
||||
DisjointSetInfo setInfoU = nodes.get(rootU);
|
||||
DisjointSetInfo setInfoV = nodes.get(rootV);
|
||||
int rankU = setInfoU.getRank();
|
||||
int rankV = setInfoV.getRank();
|
||||
if (rankU < rankV) {
|
||||
setInfoU.setParentNode(rootV);
|
||||
} else {
|
||||
setInfoV.setParentNode(rootU);
|
||||
if (rankU == rankV) {
|
||||
setInfoU.setRank(rankU + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.algorithms.kruskal;
|
||||
|
||||
public class DisjointSetInfo {
|
||||
|
||||
private Integer parentNode;
|
||||
private int rank;
|
||||
|
||||
DisjointSetInfo(Integer nodeNumber) {
|
||||
setParentNode(nodeNumber);
|
||||
setRank(1);
|
||||
}
|
||||
|
||||
public Integer getParentNode() {
|
||||
return parentNode;
|
||||
}
|
||||
|
||||
public void setParentNode(Integer parentNode) {
|
||||
this.parentNode = parentNode;
|
||||
}
|
||||
|
||||
public int getRank() {
|
||||
return rank;
|
||||
}
|
||||
|
||||
public void setRank(int rank) {
|
||||
this.rank = rank;
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.baeldung.algorithms.kruskal;
|
||||
|
||||
import com.google.common.graph.EndpointPair;
|
||||
import com.google.common.graph.MutableValueGraph;
|
||||
import com.google.common.graph.ValueGraph;
|
||||
import com.google.common.graph.ValueGraphBuilder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class Kruskal {
|
||||
|
||||
public ValueGraph<Integer, Double> minSpanningTree(ValueGraph<Integer, Double> graph) {
|
||||
|
||||
return spanningTree(graph, true);
|
||||
}
|
||||
|
||||
public ValueGraph<Integer, Double> maxSpanningTree(ValueGraph<Integer, Double> graph) {
|
||||
return spanningTree(graph, false);
|
||||
}
|
||||
|
||||
private ValueGraph<Integer, Double> spanningTree(ValueGraph<Integer, Double> graph, boolean minSpanningTree) {
|
||||
Set<EndpointPair<Integer>> edges = graph.edges();
|
||||
List<EndpointPair<Integer>> edgeList = new ArrayList<>(edges);
|
||||
|
||||
if (minSpanningTree) {
|
||||
edgeList.sort(Comparator.comparing(e -> graph.edgeValue(e).get()));
|
||||
} else {
|
||||
edgeList.sort(Collections.reverseOrder(Comparator.comparing(e -> graph.edgeValue(e).get())));
|
||||
}
|
||||
|
||||
int totalNodes = graph.nodes().size();
|
||||
CycleDetector cycleDetector = new CycleDetector(totalNodes);
|
||||
int edgeCount = 0;
|
||||
|
||||
MutableValueGraph<Integer, Double> spanningTree = ValueGraphBuilder.undirected().build();
|
||||
for (EndpointPair<Integer> edge : edgeList) {
|
||||
if (cycleDetector.detectCycle(edge.nodeU(), edge.nodeV())) {
|
||||
continue;
|
||||
}
|
||||
spanningTree.putEdgeValue(edge.nodeU(), edge.nodeV(), graph.edgeValue(edge).get());
|
||||
edgeCount++;
|
||||
if (edgeCount == totalNodes - 1) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return spanningTree;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.algorithms.maximumsubarray;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class BruteForceAlgorithm {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(BruteForceAlgorithm.class.getName());
|
||||
|
||||
public int maxSubArray(int[] arr) {
|
||||
|
||||
int size = arr.length;
|
||||
int maximumSubArraySum = Integer.MIN_VALUE;
|
||||
int start = 0;
|
||||
int end = 0;
|
||||
|
||||
for (int left = 0; left < size; left++) {
|
||||
|
||||
int runningWindowSum = 0;
|
||||
|
||||
for (int right = left; right < size; right++) {
|
||||
runningWindowSum += arr[right];
|
||||
|
||||
if (runningWindowSum > maximumSubArraySum) {
|
||||
maximumSubArraySum = runningWindowSum;
|
||||
start = left;
|
||||
end = right;
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.info("Found Maximum Subarray between {} and {}", start, end);
|
||||
return maximumSubArraySum;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.baeldung.algorithms.maximumsubarray;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class KadaneAlgorithm {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(BruteForceAlgorithm.class.getName());
|
||||
|
||||
public int maxSubArraySum(int[] arr) {
|
||||
|
||||
int size = arr.length;
|
||||
int start = 0;
|
||||
int end = 0;
|
||||
|
||||
int maxSoFar = 0, maxEndingHere = 0;
|
||||
|
||||
for (int i = 0; i < size; i++) {
|
||||
|
||||
if (arr[i] > maxEndingHere + arr[i]) {
|
||||
start = i;
|
||||
maxEndingHere = arr[i];
|
||||
} else
|
||||
maxEndingHere = maxEndingHere + arr[i];
|
||||
|
||||
if (maxSoFar < maxEndingHere) {
|
||||
maxSoFar = maxEndingHere;
|
||||
end = i;
|
||||
}
|
||||
}
|
||||
logger.info("Found Maximum Subarray between {} and {}", start, end);
|
||||
return maxSoFar;
|
||||
}
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.baeldung.algorithms.mergesortedarrays;
|
||||
|
||||
public class SortedArrays {
|
||||
|
||||
public static int[] merge(int[] foo, int[] bar) {
|
||||
|
||||
int fooLength = foo.length;
|
||||
int barLength = bar.length;
|
||||
|
||||
int[] merged = new int[fooLength + barLength];
|
||||
|
||||
int fooPosition, barPosition, mergedPosition;
|
||||
fooPosition = barPosition = mergedPosition = 0;
|
||||
|
||||
while (fooPosition < fooLength && barPosition < barLength) {
|
||||
if (foo[fooPosition] < bar[barPosition]) {
|
||||
merged[mergedPosition++] = foo[fooPosition++];
|
||||
} else {
|
||||
merged[mergedPosition++] = bar[barPosition++];
|
||||
}
|
||||
}
|
||||
|
||||
while (fooPosition < fooLength) {
|
||||
merged[mergedPosition++] = foo[fooPosition++];
|
||||
}
|
||||
|
||||
while (barPosition < barLength) {
|
||||
merged[mergedPosition++] = bar[barPosition++];
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.baeldung.algorithms.prim;
|
||||
|
||||
public class Edge {
|
||||
|
||||
private int weight;
|
||||
private boolean isIncluded = false;
|
||||
private boolean isPrinted = false;
|
||||
|
||||
public Edge(int weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public int getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public void setWeight(int weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public boolean isIncluded() {
|
||||
return isIncluded;
|
||||
}
|
||||
|
||||
public void setIncluded(boolean included) {
|
||||
isIncluded = included;
|
||||
}
|
||||
|
||||
public boolean isPrinted() {
|
||||
return isPrinted;
|
||||
}
|
||||
|
||||
public void setPrinted(boolean printed) {
|
||||
isPrinted = printed;
|
||||
}
|
||||
}
|
@ -0,0 +1,73 @@
|
||||
package com.baeldung.algorithms.prim;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.math3.util.Pair;
|
||||
|
||||
public class Prim {
|
||||
|
||||
private List<Vertex> graph;
|
||||
|
||||
public Prim(List<Vertex> graph){
|
||||
this.graph = graph;
|
||||
}
|
||||
|
||||
public void run(){
|
||||
if (graph.size() > 0){
|
||||
graph.get(0).setVisited(true);
|
||||
}
|
||||
while (isDisconnected()){
|
||||
Edge nextMinimum = new Edge(Integer.MAX_VALUE);
|
||||
Vertex nextVertex = graph.get(0);
|
||||
for (Vertex vertex : graph){
|
||||
if (vertex.isVisited()){
|
||||
Pair<Vertex, Edge> candidate = vertex.nextMinimum();
|
||||
if (candidate.getValue().getWeight() < nextMinimum.getWeight()){
|
||||
nextMinimum = candidate.getValue();
|
||||
nextVertex = candidate.getKey();
|
||||
}
|
||||
}
|
||||
}
|
||||
nextMinimum.setIncluded(true);
|
||||
nextVertex.setVisited(true);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isDisconnected(){
|
||||
for (Vertex vertex : graph){
|
||||
if (!vertex.isVisited()){
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public String originalGraphToString(){
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Vertex vertex : graph){
|
||||
sb.append(vertex.originalToString());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void resetPrintHistory(){
|
||||
for (Vertex vertex : graph){
|
||||
Iterator<Map.Entry<Vertex,Edge>> it = vertex.getEdges().entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<Vertex,Edge> pair = it.next();
|
||||
pair.getValue().setPrinted(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String minimumSpanningTreeToString(){
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Vertex vertex : graph){
|
||||
sb.append(vertex.includedToString());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,106 @@
|
||||
package com.baeldung.algorithms.prim;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.math3.util.Pair;
|
||||
|
||||
public class Vertex {
|
||||
|
||||
private String label = null;
|
||||
private Map<Vertex, Edge> edges = new HashMap<>();
|
||||
private boolean isVisited = false;
|
||||
|
||||
public Vertex(String label){
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
|
||||
public void setLabel(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public Map<Vertex, Edge> getEdges() {
|
||||
return edges;
|
||||
}
|
||||
|
||||
public void addEdge(Vertex vertex, Edge edge){
|
||||
if (this.edges.containsKey(vertex)){
|
||||
if (edge.getWeight() < this.edges.get(vertex).getWeight()){
|
||||
this.edges.replace(vertex, edge);
|
||||
}
|
||||
} else {
|
||||
this.edges.put(vertex, edge);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isVisited() {
|
||||
return isVisited;
|
||||
}
|
||||
|
||||
public void setVisited(boolean visited) {
|
||||
isVisited = visited;
|
||||
}
|
||||
|
||||
public Pair<Vertex, Edge> nextMinimum(){
|
||||
Edge nextMinimum = new Edge(Integer.MAX_VALUE);
|
||||
Vertex nextVertex = this;
|
||||
Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<Vertex,Edge> pair = it.next();
|
||||
if (!pair.getKey().isVisited()){
|
||||
if (!pair.getValue().isIncluded()) {
|
||||
if (pair.getValue().getWeight() < nextMinimum.getWeight()) {
|
||||
nextMinimum = pair.getValue();
|
||||
nextVertex = pair.getKey();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Pair<>(nextVertex, nextMinimum);
|
||||
}
|
||||
|
||||
public String originalToString(){
|
||||
StringBuilder sb = new StringBuilder();
|
||||
Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<Vertex,Edge> pair = it.next();
|
||||
if (!pair.getValue().isPrinted()) {
|
||||
sb.append(getLabel());
|
||||
sb.append(" --- ");
|
||||
sb.append(pair.getValue().getWeight());
|
||||
sb.append(" --- ");
|
||||
sb.append(pair.getKey().getLabel());
|
||||
sb.append("\n");
|
||||
pair.getValue().setPrinted(true);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public String includedToString(){
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (isVisited()) {
|
||||
Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<Vertex,Edge> pair = it.next();
|
||||
if (pair.getValue().isIncluded()) {
|
||||
if (!pair.getValue().isPrinted()) {
|
||||
sb.append(getLabel());
|
||||
sb.append(" --- ");
|
||||
sb.append(pair.getValue().getWeight());
|
||||
sb.append(" --- ");
|
||||
sb.append(pair.getKey().getLabel());
|
||||
sb.append("\n");
|
||||
pair.getValue().setPrinted(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,80 @@
|
||||
package com.baeldung.algorithms.combinatorics;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertSame;
|
||||
|
||||
public class CombinatoricsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEmptySequence_whenCallingPermutations_ShouldReturnEmptyList() {
|
||||
List<Integer> sequence = Arrays.asList();
|
||||
|
||||
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
|
||||
|
||||
assertEquals(0, permutations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOneElementSequence_whenCallingPermutations_ShouldReturnPermutations() {
|
||||
List<Integer> sequence = Arrays.asList(1);
|
||||
|
||||
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
|
||||
|
||||
assertEquals(1, permutations.size());
|
||||
assertEquals(1, permutations.get(0).size());
|
||||
assertSame(1, permutations.get(0).get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFourElementsSequence_whenCallingPermutations_ShouldReturnPermutations() {
|
||||
List<Integer> sequence = Arrays.asList(1, 2, 3, 4);
|
||||
|
||||
List<List<Integer>> permutations = Combinatorics.permutations(sequence);
|
||||
|
||||
assertEquals(24, permutations.size());
|
||||
assertEquals(24, new HashSet<>(permutations).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoElements_whenCalling3Combinations_ShouldReturnEmptyList() {
|
||||
List<Integer> set = Arrays.asList(1, 2);
|
||||
|
||||
List<List<Integer>> combinations = Combinatorics.combinations(set, 3);
|
||||
|
||||
assertEquals(0, combinations.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThreeElements_whenCalling3Combinations_ShouldReturnOneCombination() {
|
||||
List<Integer> set = Arrays.asList(1, 2, 3);
|
||||
|
||||
List<List<Integer>> combinations = Combinatorics.combinations(set, 3);
|
||||
|
||||
assertEquals(1, combinations.size());
|
||||
assertEquals(combinations.get(0), Arrays.asList(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFourElements_whenCalling2Combinations_ShouldReturnCombinations() {
|
||||
List<Integer> set = Arrays.asList(1, 2, 3, 4);
|
||||
|
||||
List<List<Integer>> combinations = Combinatorics.combinations(set, 2);
|
||||
|
||||
assertEquals(6, combinations.size());
|
||||
assertEquals(6, new HashSet<>(combinations).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFourElements_whenCallingPowerSet_ShouldReturn15Sets() {
|
||||
List<Character> sequence = Arrays.asList('a', 'b', 'c', 'd');
|
||||
|
||||
List<List<Character>> combinations = Combinatorics.powerSet(sequence);
|
||||
|
||||
assertEquals(16, combinations.size());
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package com.baeldung.algorithms.greedy;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class GreedyAlgorithmUnitTest {
|
||||
|
||||
private SocialConnector prepareNetwork() {
|
||||
SocialConnector sc = new SocialConnector();
|
||||
SocialUser root = new SocialUser("root");
|
||||
SocialUser child1 = new SocialUser("child1");
|
||||
SocialUser child2 = new SocialUser("child2");
|
||||
SocialUser child3 = new SocialUser("child3");
|
||||
SocialUser child21 = new SocialUser("child21");
|
||||
SocialUser child211 = new SocialUser("child211");
|
||||
SocialUser child2111 = new SocialUser("child2111");
|
||||
SocialUser child31 = new SocialUser("child31");
|
||||
SocialUser child311 = new SocialUser("child311");
|
||||
SocialUser child3111 = new SocialUser("child3111");
|
||||
child211.addFollowers(Arrays.asList(new SocialUser[]{child2111}));
|
||||
child311.addFollowers(Arrays.asList(new SocialUser[]{child3111}));
|
||||
child21.addFollowers(Arrays.asList(new SocialUser[]{child211}));
|
||||
child31.addFollowers(Arrays.asList(new SocialUser[]{child311,
|
||||
new SocialUser("child312"), new SocialUser("child313"), new SocialUser("child314")}));
|
||||
child1.addFollowers(Arrays.asList(new SocialUser[]{new SocialUser("child11"), new SocialUser("child12")}));
|
||||
child2.addFollowers(Arrays.asList(new SocialUser[]{child21, new SocialUser("child22"), new SocialUser("child23")}));
|
||||
child3.addFollowers(Arrays.asList(new SocialUser[]{child31}));
|
||||
root.addFollowers(Arrays.asList(new SocialUser[]{child1, child2, child3}));
|
||||
sc.setUsers(Arrays.asList(new SocialUser[]{root, child1, child2, child3, child21, child31, child311, child211}));
|
||||
return sc;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void greedyAlgorithmTest() {
|
||||
GreedyAlgorithm ga = new GreedyAlgorithm(prepareNetwork());
|
||||
assertEquals(ga.findMostFollowersPath("root"), 5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nongreedyAlgorithmTest() {
|
||||
NonGreedyAlgorithm nga = new NonGreedyAlgorithm(prepareNetwork(), 0);
|
||||
Assertions.assertThrows(IllegalStateException.class, () -> {
|
||||
nga.findMostFollowersPath("root");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nongreedyAlgorithmUnboundedTest() {
|
||||
SocialConnector sc = prepareNetwork();
|
||||
sc.switchCounter();
|
||||
NonGreedyAlgorithm nga = new NonGreedyAlgorithm(sc, 0);
|
||||
assertEquals(nga.findMostFollowersPath("root"), 6);
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.algorithms.integerstreammedian;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MedianOfIntegerStreamUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach1() {
|
||||
MedianOfIntegerStream mis = new MedianOfIntegerStream();
|
||||
for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) {
|
||||
mis.add(e.getKey());
|
||||
assertEquals(e.getValue(), (Double) mis.getMedian());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach2() {
|
||||
MedianOfIntegerStream2 mis = new MedianOfIntegerStream2();
|
||||
for (Map.Entry<Integer, Double> e : testcaseFixture().entrySet()) {
|
||||
mis.add(e.getKey());
|
||||
assertEquals(e.getValue(), (Double) mis.getMedian());
|
||||
}
|
||||
}
|
||||
|
||||
private Map<Integer, Double> testcaseFixture() {
|
||||
return new LinkedHashMap<Integer, Double>() {{
|
||||
put(1, 1d);
|
||||
put(7, 4d);
|
||||
put(5, 5d);
|
||||
put(8, 6d);
|
||||
put(3, 5d);
|
||||
put(9, 6d);
|
||||
put(4, 5d);
|
||||
}};
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
package com.baeldung.algorithms.kruskal;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import com.google.common.graph.MutableValueGraph;
|
||||
import com.google.common.graph.ValueGraph;
|
||||
import com.google.common.graph.ValueGraphBuilder;
|
||||
import com.baeldung.algorithms.kruskal.Kruskal;
|
||||
|
||||
public class KruskalUnitTest {
|
||||
|
||||
private MutableValueGraph<Integer, Double> graph;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
graph = ValueGraphBuilder.undirected().build();
|
||||
graph.putEdgeValue(0, 1, 8.0);
|
||||
graph.putEdgeValue(0, 2, 5.0);
|
||||
graph.putEdgeValue(1, 2, 9.0);
|
||||
graph.putEdgeValue(1, 3, 11.0);
|
||||
graph.putEdgeValue(2, 3, 15.0);
|
||||
graph.putEdgeValue(2, 4, 10.0);
|
||||
graph.putEdgeValue(3, 4, 7.0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGraph_whenMinimumSpanningTree_thenOutputCorrectResult() {
|
||||
final Kruskal kruskal = new Kruskal();
|
||||
ValueGraph<Integer, Double> spanningTree = kruskal.minSpanningTree(graph);
|
||||
|
||||
assertTrue(spanningTree.hasEdgeConnecting(0, 1));
|
||||
assertTrue(spanningTree.hasEdgeConnecting(0, 2));
|
||||
assertTrue(spanningTree.hasEdgeConnecting(2, 4));
|
||||
assertTrue(spanningTree.hasEdgeConnecting(3, 4));
|
||||
assertEquals(graph.edgeValue(0, 1), spanningTree.edgeValue(0, 1));
|
||||
assertEquals(graph.edgeValue(0, 2), spanningTree.edgeValue(0, 2));
|
||||
assertEquals(graph.edgeValue(2, 4), spanningTree.edgeValue(2, 4));
|
||||
assertEquals(graph.edgeValue(3, 4), spanningTree.edgeValue(3, 4));
|
||||
|
||||
assertFalse(spanningTree.hasEdgeConnecting(1, 2));
|
||||
assertFalse(spanningTree.hasEdgeConnecting(1, 3));
|
||||
assertFalse(spanningTree.hasEdgeConnecting(2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGraph_whenMaximumSpanningTree_thenOutputCorrectResult() {
|
||||
final Kruskal kruskal = new Kruskal();
|
||||
ValueGraph<Integer, Double> spanningTree = kruskal.maxSpanningTree(graph);
|
||||
|
||||
assertTrue(spanningTree.hasEdgeConnecting(0, 1));
|
||||
assertTrue(spanningTree.hasEdgeConnecting(1, 3));
|
||||
assertTrue(spanningTree.hasEdgeConnecting(2, 3));
|
||||
assertTrue(spanningTree.hasEdgeConnecting(2, 4));
|
||||
assertEquals(graph.edgeValue(0, 1), spanningTree.edgeValue(0, 1));
|
||||
assertEquals(graph.edgeValue(1, 3), spanningTree.edgeValue(1, 3));
|
||||
assertEquals(graph.edgeValue(2, 3), spanningTree.edgeValue(2, 3));
|
||||
assertEquals(graph.edgeValue(2, 4), spanningTree.edgeValue(2, 4));
|
||||
|
||||
assertFalse(spanningTree.hasEdgeConnecting(0, 2));
|
||||
assertFalse(spanningTree.hasEdgeConnecting(1, 2));
|
||||
assertFalse(spanningTree.hasEdgeConnecting(3, 4));
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung.algorithms.maximumsubarray;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class BruteForceAlgorithmUnitTest {
|
||||
|
||||
@Test
|
||||
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
|
||||
//given
|
||||
int[] arr = new int[]{-3, 1, -8, 4, -1, 2, 1, -5, 5};
|
||||
//when
|
||||
BruteForceAlgorithm algorithm = new BruteForceAlgorithm();
|
||||
int maximumSum = algorithm.maxSubArray(arr);
|
||||
//then
|
||||
assertEquals(6, maximumSum);
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.baeldung.algorithms.maximumsubarray;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class KadaneAlgorithmUnitTest {
|
||||
|
||||
@Test
|
||||
void givenArrayWithNegativeNumberWhenMaximumSubarrayThenReturns6() {
|
||||
//given
|
||||
int[] arr = new int[]{-3, 1, -8, 4, -1, 2, 1, -5, 5};
|
||||
//when
|
||||
KadaneAlgorithm algorithm = new KadaneAlgorithm();
|
||||
int maxSum = algorithm.maxSubArraySum(arr);
|
||||
//then
|
||||
assertEquals(6, maxSum);
|
||||
}
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package com.baeldung.algorithms.mergesortedarrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.algorithms.mergesortedarrays.SortedArrays;
|
||||
|
||||
public class SortedArraysUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoSortedArrays_whenMerged_thenReturnMergedSortedArray() {
|
||||
|
||||
int[] foo = { 3, 7 };
|
||||
int[] bar = { 4, 8, 11 };
|
||||
int[] merged = { 3, 4, 7, 8, 11 };
|
||||
|
||||
assertArrayEquals(merged, SortedArrays.merge(foo, bar));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSortedArraysWithDuplicates_whenMerged_thenReturnMergedSortedArray() {
|
||||
|
||||
int[] foo = { 3, 3, 7 };
|
||||
int[] bar = { 4, 8, 8, 11 };
|
||||
int[] merged = { 3, 3, 4, 7, 8, 8, 11 };
|
||||
|
||||
assertArrayEquals(merged, SortedArrays.merge(foo, bar));
|
||||
}
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package com.baeldung.algorithms.prim;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PrimUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAGraph_whenPrimRuns_thenPrintMST() {
|
||||
Prim prim = new Prim(createGraph());
|
||||
System.out.println(prim.originalGraphToString());
|
||||
System.out.println("----------------");
|
||||
prim.run();
|
||||
System.out.println();
|
||||
prim.resetPrintHistory();
|
||||
System.out.println(prim.minimumSpanningTreeToString());
|
||||
}
|
||||
|
||||
public static List<Vertex> createGraph() {
|
||||
List<Vertex> graph = new ArrayList<>();
|
||||
Vertex a = new Vertex("A");
|
||||
Vertex b = new Vertex("B");
|
||||
Vertex c = new Vertex("C");
|
||||
Vertex d = new Vertex("D");
|
||||
Vertex e = new Vertex("E");
|
||||
Edge ab = new Edge(2);
|
||||
a.addEdge(b, ab);
|
||||
b.addEdge(a, ab);
|
||||
Edge ac = new Edge(3);
|
||||
a.addEdge(c, ac);
|
||||
c.addEdge(a, ac);
|
||||
Edge bc = new Edge(2);
|
||||
b.addEdge(c, bc);
|
||||
c.addEdge(b, bc);
|
||||
Edge be = new Edge(5);
|
||||
b.addEdge(e, be);
|
||||
e.addEdge(b, be);
|
||||
Edge cd = new Edge(1);
|
||||
c.addEdge(d, cd);
|
||||
d.addEdge(c, cd);
|
||||
Edge ce = new Edge(1);
|
||||
c.addEdge(e, ce);
|
||||
e.addEdge(c, ce);
|
||||
graph.add(a);
|
||||
graph.add(b);
|
||||
graph.add(c);
|
||||
graph.add(d);
|
||||
graph.add(e);
|
||||
return graph;
|
||||
}
|
||||
|
||||
}
|
12
algorithms-searching/README.md
Normal file
12
algorithms-searching/README.md
Normal file
@ -0,0 +1,12 @@
|
||||
## Algorithms - Searching
|
||||
|
||||
This module contains articles about searching algorithms.
|
||||
|
||||
### Relevant articles:
|
||||
- [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search)
|
||||
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
|
||||
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
|
||||
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
|
||||
- [String Search Algorithms for Large Texts](https://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
|
38
algorithms-searching/pom.xml
Normal file
38
algorithms-searching/pom.xml
Normal file
@ -0,0 +1,38 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>algorithms-searching</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-searching</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>algorithms-searching</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,55 +1,55 @@
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class BinarySearch {
|
||||
|
||||
public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) {
|
||||
|
||||
int index = Integer.MAX_VALUE;
|
||||
|
||||
while (low <= high) {
|
||||
|
||||
int mid = (low + high) / 2;
|
||||
|
||||
if (sortedArray[mid] < key) {
|
||||
low = mid + 1;
|
||||
} else if (sortedArray[mid] > key) {
|
||||
high = mid - 1;
|
||||
} else if (sortedArray[mid] == key) {
|
||||
index = mid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
|
||||
|
||||
int middle = (low + high) / 2;
|
||||
if (high < low) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (key == sortedArray[middle]) {
|
||||
return middle;
|
||||
} else if (key < sortedArray[middle]) {
|
||||
return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
|
||||
} else {
|
||||
return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
|
||||
}
|
||||
}
|
||||
|
||||
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
|
||||
int index = Arrays.binarySearch(sortedArray, key);
|
||||
return index;
|
||||
}
|
||||
|
||||
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
|
||||
int index = Collections.binarySearch(sortedList, key);
|
||||
return index;
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class BinarySearch {
|
||||
|
||||
public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) {
|
||||
|
||||
int index = Integer.MAX_VALUE;
|
||||
|
||||
while (low <= high) {
|
||||
|
||||
int mid = (low + high) / 2;
|
||||
|
||||
if (sortedArray[mid] < key) {
|
||||
low = mid + 1;
|
||||
} else if (sortedArray[mid] > key) {
|
||||
high = mid - 1;
|
||||
} else if (sortedArray[mid] == key) {
|
||||
index = mid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
|
||||
|
||||
int middle = (low + high) / 2;
|
||||
if (high < low) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (key == sortedArray[middle]) {
|
||||
return middle;
|
||||
} else if (key < sortedArray[middle]) {
|
||||
return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
|
||||
} else {
|
||||
return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
|
||||
}
|
||||
}
|
||||
|
||||
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
|
||||
int index = Arrays.binarySearch(sortedArray, key);
|
||||
return index;
|
||||
}
|
||||
|
||||
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
|
||||
int index = Collections.binarySearch(sortedList, key);
|
||||
return index;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,227 @@
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.Stack;
|
||||
|
||||
public class BinaryTree {
|
||||
|
||||
Node root;
|
||||
|
||||
public void add(int value) {
|
||||
root = addRecursive(root, value);
|
||||
}
|
||||
|
||||
private Node addRecursive(Node current, int value) {
|
||||
|
||||
if (current == null) {
|
||||
return new Node(value);
|
||||
}
|
||||
|
||||
if (value < current.value) {
|
||||
current.left = addRecursive(current.left, value);
|
||||
} else if (value > current.value) {
|
||||
current.right = addRecursive(current.right, value);
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return root == null;
|
||||
}
|
||||
|
||||
public int getSize() {
|
||||
return getSizeRecursive(root);
|
||||
}
|
||||
|
||||
private int getSizeRecursive(Node current) {
|
||||
return current == null ? 0 : getSizeRecursive(current.left) + 1 + getSizeRecursive(current.right);
|
||||
}
|
||||
|
||||
public boolean containsNode(int value) {
|
||||
return containsNodeRecursive(root, value);
|
||||
}
|
||||
|
||||
private boolean containsNodeRecursive(Node current, int value) {
|
||||
if (current == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (value == current.value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return value < current.value
|
||||
? containsNodeRecursive(current.left, value)
|
||||
: containsNodeRecursive(current.right, value);
|
||||
}
|
||||
|
||||
public void delete(int value) {
|
||||
root = deleteRecursive(root, value);
|
||||
}
|
||||
|
||||
private Node deleteRecursive(Node current, int value) {
|
||||
if (current == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value == current.value) {
|
||||
// Case 1: no children
|
||||
if (current.left == null && current.right == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Case 2: only 1 child
|
||||
if (current.right == null) {
|
||||
return current.left;
|
||||
}
|
||||
|
||||
if (current.left == null) {
|
||||
return current.right;
|
||||
}
|
||||
|
||||
// Case 3: 2 children
|
||||
int smallestValue = findSmallestValue(current.right);
|
||||
current.value = smallestValue;
|
||||
current.right = deleteRecursive(current.right, smallestValue);
|
||||
return current;
|
||||
}
|
||||
if (value < current.value) {
|
||||
current.left = deleteRecursive(current.left, value);
|
||||
return current;
|
||||
}
|
||||
|
||||
current.right = deleteRecursive(current.right, value);
|
||||
return current;
|
||||
}
|
||||
|
||||
private int findSmallestValue(Node root) {
|
||||
return root.left == null ? root.value : findSmallestValue(root.left);
|
||||
}
|
||||
|
||||
public void traverseInOrder(Node node) {
|
||||
if (node != null) {
|
||||
traverseInOrder(node.left);
|
||||
visit(node.value);
|
||||
traverseInOrder(node.right);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePreOrder(Node node) {
|
||||
if (node != null) {
|
||||
visit(node.value);
|
||||
traversePreOrder(node.left);
|
||||
traversePreOrder(node.right);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePostOrder(Node node) {
|
||||
if (node != null) {
|
||||
traversePostOrder(node.left);
|
||||
traversePostOrder(node.right);
|
||||
visit(node.value);
|
||||
}
|
||||
}
|
||||
|
||||
public void traverseLevelOrder() {
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Queue<Node> nodes = new LinkedList<>();
|
||||
nodes.add(root);
|
||||
|
||||
while (!nodes.isEmpty()) {
|
||||
|
||||
Node node = nodes.remove();
|
||||
|
||||
System.out.print(" " + node.value);
|
||||
|
||||
if (node.left != null) {
|
||||
nodes.add(node.left);
|
||||
}
|
||||
|
||||
if (node.left != null) {
|
||||
nodes.add(node.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void traverseInOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
while(current.left != null) {
|
||||
current = current.left;
|
||||
stack.push(current);
|
||||
}
|
||||
current = stack.pop();
|
||||
visit(current.value);
|
||||
if(current.right != null) {
|
||||
current = current.right;
|
||||
stack.push(current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePreOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
while(! stack.isEmpty()) {
|
||||
current = stack.pop();
|
||||
visit(current.value);
|
||||
|
||||
if(current.right != null)
|
||||
stack.push(current.right);
|
||||
|
||||
if(current.left != null)
|
||||
stack.push(current.left);
|
||||
}
|
||||
}
|
||||
|
||||
public void traversePostOrderWithoutRecursion() {
|
||||
Stack<Node> stack = new Stack<Node>();
|
||||
Node prev = root;
|
||||
Node current = root;
|
||||
stack.push(root);
|
||||
|
||||
while (!stack.isEmpty()) {
|
||||
current = stack.peek();
|
||||
boolean hasChild = (current.left != null || current.right != null);
|
||||
boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null));
|
||||
|
||||
if (!hasChild || isPrevLastChild) {
|
||||
current = stack.pop();
|
||||
visit(current.value);
|
||||
prev = current;
|
||||
} else {
|
||||
if (current.right != null) {
|
||||
stack.push(current.right);
|
||||
}
|
||||
if (current.left != null) {
|
||||
stack.push(current.left);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void visit(int value) {
|
||||
System.out.print(" " + value);
|
||||
}
|
||||
|
||||
class Node {
|
||||
int value;
|
||||
Node left;
|
||||
Node right;
|
||||
|
||||
Node(int value) {
|
||||
this.value = value;
|
||||
right = null;
|
||||
left = null;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package com.baeldung.graph;
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.algorithms.quadtree;
|
||||
|
||||
public class Point {
|
||||
private float x;
|
||||
private float y;
|
||||
|
||||
public Point(float x, float y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
public float getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public float getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "[" + x + " , " + y + "]";
|
||||
}
|
||||
}
|
@ -0,0 +1,109 @@
|
||||
package com.baeldung.algorithms.quadtree;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class QuadTree {
|
||||
private static final int MAX_POINTS = 3;
|
||||
private Region area;
|
||||
private List<Point> points = new ArrayList<>();
|
||||
private List<QuadTree> quadTrees = new ArrayList<>();
|
||||
private StringBuilder searchTraversePath;
|
||||
|
||||
public QuadTree(Region area) {
|
||||
this.area = area;
|
||||
}
|
||||
|
||||
public boolean addPoint(Point point) {
|
||||
if (this.area.containsPoint(point)) {
|
||||
if (this.points.size() < MAX_POINTS) {
|
||||
this.points.add(point);
|
||||
return true;
|
||||
} else {
|
||||
if (this.quadTrees.size() == 0) {
|
||||
createQuadrants();
|
||||
}
|
||||
return addPointToOneQuadrant(point);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean addPointToOneQuadrant(Point point) {
|
||||
boolean isPointAdded;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
isPointAdded = this.quadTrees.get(i)
|
||||
.addPoint(point);
|
||||
if (isPointAdded)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void createQuadrants() {
|
||||
Region region;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
region = this.area.getQuadrant(i);
|
||||
quadTrees.add(new QuadTree(region));
|
||||
}
|
||||
}
|
||||
|
||||
public List<Point> search(Region searchRegion, List<Point> matches, String depthIndicator) {
|
||||
searchTraversePath = new StringBuilder();
|
||||
if (matches == null) {
|
||||
matches = new ArrayList<Point>();
|
||||
searchTraversePath.append(depthIndicator)
|
||||
.append("Search Boundary =")
|
||||
.append(searchRegion)
|
||||
.append("\n");
|
||||
}
|
||||
if (!this.area.doesOverlap(searchRegion)) {
|
||||
return matches;
|
||||
} else {
|
||||
for (Point point : points) {
|
||||
if (searchRegion.containsPoint(point)) {
|
||||
searchTraversePath.append(depthIndicator)
|
||||
.append("Found match " + point)
|
||||
.append("\n");
|
||||
matches.add(point);
|
||||
}
|
||||
}
|
||||
if (this.quadTrees.size() > 0) {
|
||||
for (int i = 0; i < 4; i++) {
|
||||
searchTraversePath.append(depthIndicator)
|
||||
.append("Q")
|
||||
.append(i)
|
||||
.append("-->")
|
||||
.append(quadTrees.get(i).area)
|
||||
.append("\n");
|
||||
quadTrees.get(i)
|
||||
.search(searchRegion, matches, depthIndicator + "\t");
|
||||
this.searchTraversePath.append(quadTrees.get(i)
|
||||
.printSearchTraversePath());
|
||||
}
|
||||
}
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
public String printTree(String depthIndicator) {
|
||||
String str = "";
|
||||
if (depthIndicator == "") {
|
||||
str += "Root-->" + area.toString() + "\n";
|
||||
}
|
||||
|
||||
for (Point point : points) {
|
||||
str += depthIndicator + point.toString() + "\n";
|
||||
}
|
||||
for (int i = 0; i < quadTrees.size(); i++) {
|
||||
str += depthIndicator + "Q" + String.valueOf(i) + "-->" + quadTrees.get(i).area.toString() + "\n";
|
||||
str += quadTrees.get(i)
|
||||
.printTree(depthIndicator + "\t");
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
public String printSearchTraversePath() {
|
||||
return searchTraversePath.toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.baeldung.algorithms.quadtree;
|
||||
|
||||
public class Region {
|
||||
private float x1;
|
||||
private float y1;
|
||||
private float x2;
|
||||
private float y2;
|
||||
|
||||
public Region(float x1, float y1, float x2, float y2) {
|
||||
if (x1 >= x2 || y1 >= y2)
|
||||
throw new IllegalArgumentException("(x1,y1) should be lesser than (x2,y2)");
|
||||
this.x1 = x1;
|
||||
this.y1 = y1;
|
||||
this.x2 = x2;
|
||||
this.y2 = y2;
|
||||
}
|
||||
|
||||
public Region getQuadrant(int quadrantIndex) {
|
||||
float quadrantWidth = (this.x2 - this.x1) / 2;
|
||||
float quadrantHeight = (this.y2 - this.y1) / 2;
|
||||
|
||||
// 0=SW, 1=NW, 2=NE, 3=SE
|
||||
switch (quadrantIndex) {
|
||||
case 0:
|
||||
return new Region(x1, y1, x1 + quadrantWidth, y1 + quadrantHeight);
|
||||
case 1:
|
||||
return new Region(x1, y1 + quadrantHeight, x1 + quadrantWidth, y2);
|
||||
case 2:
|
||||
return new Region(x1 + quadrantWidth, y1 + quadrantHeight, x2, y2);
|
||||
case 3:
|
||||
return new Region(x1 + quadrantWidth, y1, x2, y1 + quadrantHeight);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean containsPoint(Point point) {
|
||||
// Consider left and top side to be inclusive for points on border
|
||||
return point.getX() >= this.x1
|
||||
&& point.getX() < this.x2
|
||||
&& point.getY() >= this.y1
|
||||
&& point.getY() < this.y2;
|
||||
}
|
||||
|
||||
public boolean doesOverlap(Region testRegion) {
|
||||
// Is test region completely to left of my region?
|
||||
if (testRegion.getX2() < this.getX1()) {
|
||||
return false;
|
||||
}
|
||||
// Is test region completely to right of my region?
|
||||
if (testRegion.getX1() > this.getX2()) {
|
||||
return false;
|
||||
}
|
||||
// Is test region completely above my region?
|
||||
if (testRegion.getY1() > this.getY2()) {
|
||||
return false;
|
||||
}
|
||||
// Is test region completely below my region?
|
||||
if (testRegion.getY2() < this.getY1()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "[Region (x1=" + x1 + ", y1=" + y1 + "), (x2=" + x2 + ", y2=" + y2 + ")]";
|
||||
}
|
||||
|
||||
public float getX1() {
|
||||
return x1;
|
||||
}
|
||||
|
||||
public float getY1() {
|
||||
return y1;
|
||||
}
|
||||
|
||||
public float getX2() {
|
||||
return x2;
|
||||
}
|
||||
|
||||
public float getY2() {
|
||||
return y2;
|
||||
}
|
||||
|
||||
}
|
@ -1,194 +1,194 @@
|
||||
package com.baeldung.algorithms.string.search;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Random;
|
||||
|
||||
public class StringSearchAlgorithms {
|
||||
public static long getBiggerPrime(int m) {
|
||||
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random());
|
||||
return prime.longValue();
|
||||
}
|
||||
|
||||
public static long getLowerPrime(long number) {
|
||||
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random());
|
||||
return prime.longValue();
|
||||
}
|
||||
|
||||
private static int getNumberOfBits(final int number) {
|
||||
return Integer.SIZE - Integer.numberOfLeadingZeros(number);
|
||||
}
|
||||
|
||||
private static int getNumberOfBits(final long number) {
|
||||
return Long.SIZE - Long.numberOfLeadingZeros(number);
|
||||
}
|
||||
|
||||
public static int simpleTextSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length;
|
||||
int textSize = text.length;
|
||||
|
||||
int i = 0;
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
int j = 0;
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j += 1;
|
||||
if (j >= patternSize)
|
||||
return i;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int RabinKarpMethod(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length; // m
|
||||
int textSize = text.length; // n
|
||||
|
||||
long prime = getBiggerPrime(patternSize);
|
||||
|
||||
long r = 1;
|
||||
for (int i = 0; i < patternSize - 1; i++) {
|
||||
r *= 2;
|
||||
r = r % prime;
|
||||
}
|
||||
|
||||
long[] t = new long[textSize];
|
||||
t[0] = 0;
|
||||
|
||||
long pfinger = 0;
|
||||
|
||||
for (int j = 0; j < patternSize; j++) {
|
||||
t[0] = (2 * t[0] + text[j]) % prime;
|
||||
pfinger = (2 * pfinger + pattern[j]) % prime;
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
boolean passed = false;
|
||||
|
||||
int diff = textSize - patternSize;
|
||||
for (i = 0; i <= diff; i++) {
|
||||
if (t[i] == pfinger) {
|
||||
passed = true;
|
||||
for (int k = 0; k < patternSize; k++) {
|
||||
if (text[i + k] != pattern[k]) {
|
||||
passed = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (passed) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
if (i < diff) {
|
||||
long value = 2 * (t[i] - r * text[i]) + text[i + patternSize];
|
||||
t[i + 1] = ((value % prime) + prime) % prime;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
|
||||
}
|
||||
|
||||
public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length; // m
|
||||
int textSize = text.length; // n
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
int[] shift = KnuthMorrisPrattShift(pattern);
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j += 1;
|
||||
if (j >= patternSize)
|
||||
return i;
|
||||
}
|
||||
|
||||
if (j > 0) {
|
||||
i += shift[j - 1];
|
||||
j = Math.max(j - shift[j - 1], 0);
|
||||
} else {
|
||||
i++;
|
||||
j = 0;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int[] KnuthMorrisPrattShift(char[] pattern) {
|
||||
int patternSize = pattern.length;
|
||||
|
||||
int[] shift = new int[patternSize];
|
||||
shift[0] = 1;
|
||||
|
||||
int i = 1, j = 0;
|
||||
|
||||
while ((i + j) < patternSize) {
|
||||
if (pattern[i + j] == pattern[j]) {
|
||||
shift[i + j] = i;
|
||||
j++;
|
||||
} else {
|
||||
if (j == 0)
|
||||
shift[i] = i + 1;
|
||||
|
||||
if (j > 0) {
|
||||
i = i + shift[j - 1];
|
||||
j = Math.max(j - shift[j - 1], 0);
|
||||
} else {
|
||||
i = i + 1;
|
||||
j = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return shift;
|
||||
}
|
||||
|
||||
public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length;
|
||||
int textSize = text.length;
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
j = patternSize - 1;
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j--;
|
||||
if (j < 0)
|
||||
return i;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) {
|
||||
|
||||
int shift[] = new int[256];
|
||||
|
||||
for (int k = 0; k < 256; k++) {
|
||||
shift[k] = pattern.length;
|
||||
}
|
||||
|
||||
for (int k = 0; k < pattern.length - 1; k++) {
|
||||
shift[pattern[k]] = pattern.length - 1 - k;
|
||||
}
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
while ((i + pattern.length) <= text.length) {
|
||||
j = pattern.length - 1;
|
||||
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j -= 1;
|
||||
if (j < 0)
|
||||
return i;
|
||||
}
|
||||
|
||||
i = i + shift[text[i + pattern.length - 1]];
|
||||
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
package com.baeldung.algorithms.textsearch;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Random;
|
||||
|
||||
public class TextSearchAlgorithms {
|
||||
public static long getBiggerPrime(int m) {
|
||||
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(m) + 1, new Random());
|
||||
return prime.longValue();
|
||||
}
|
||||
|
||||
public static long getLowerPrime(long number) {
|
||||
BigInteger prime = BigInteger.probablePrime(getNumberOfBits(number) - 1, new Random());
|
||||
return prime.longValue();
|
||||
}
|
||||
|
||||
private static int getNumberOfBits(final int number) {
|
||||
return Integer.SIZE - Integer.numberOfLeadingZeros(number);
|
||||
}
|
||||
|
||||
private static int getNumberOfBits(final long number) {
|
||||
return Long.SIZE - Long.numberOfLeadingZeros(number);
|
||||
}
|
||||
|
||||
public static int simpleTextSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length;
|
||||
int textSize = text.length;
|
||||
|
||||
int i = 0;
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
int j = 0;
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j += 1;
|
||||
if (j >= patternSize)
|
||||
return i;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int RabinKarpMethod(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length; // m
|
||||
int textSize = text.length; // n
|
||||
|
||||
long prime = getBiggerPrime(patternSize);
|
||||
|
||||
long r = 1;
|
||||
for (int i = 0; i < patternSize - 1; i++) {
|
||||
r *= 2;
|
||||
r = r % prime;
|
||||
}
|
||||
|
||||
long[] t = new long[textSize];
|
||||
t[0] = 0;
|
||||
|
||||
long pfinger = 0;
|
||||
|
||||
for (int j = 0; j < patternSize; j++) {
|
||||
t[0] = (2 * t[0] + text[j]) % prime;
|
||||
pfinger = (2 * pfinger + pattern[j]) % prime;
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
boolean passed = false;
|
||||
|
||||
int diff = textSize - patternSize;
|
||||
for (i = 0; i <= diff; i++) {
|
||||
if (t[i] == pfinger) {
|
||||
passed = true;
|
||||
for (int k = 0; k < patternSize; k++) {
|
||||
if (text[i + k] != pattern[k]) {
|
||||
passed = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (passed) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
if (i < diff) {
|
||||
long value = 2 * (t[i] - r * text[i]) + text[i + patternSize];
|
||||
t[i + 1] = ((value % prime) + prime) % prime;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
|
||||
}
|
||||
|
||||
public static int KnuthMorrisPrattSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length; // m
|
||||
int textSize = text.length; // n
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
int[] shift = KnuthMorrisPrattShift(pattern);
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j += 1;
|
||||
if (j >= patternSize)
|
||||
return i;
|
||||
}
|
||||
|
||||
if (j > 0) {
|
||||
i += shift[j - 1];
|
||||
j = Math.max(j - shift[j - 1], 0);
|
||||
} else {
|
||||
i++;
|
||||
j = 0;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int[] KnuthMorrisPrattShift(char[] pattern) {
|
||||
int patternSize = pattern.length;
|
||||
|
||||
int[] shift = new int[patternSize];
|
||||
shift[0] = 1;
|
||||
|
||||
int i = 1, j = 0;
|
||||
|
||||
while ((i + j) < patternSize) {
|
||||
if (pattern[i + j] == pattern[j]) {
|
||||
shift[i + j] = i;
|
||||
j++;
|
||||
} else {
|
||||
if (j == 0)
|
||||
shift[i] = i + 1;
|
||||
|
||||
if (j > 0) {
|
||||
i = i + shift[j - 1];
|
||||
j = Math.max(j - shift[j - 1], 0);
|
||||
} else {
|
||||
i = i + 1;
|
||||
j = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return shift;
|
||||
}
|
||||
|
||||
public static int BoyerMooreHorspoolSimpleSearch(char[] pattern, char[] text) {
|
||||
int patternSize = pattern.length;
|
||||
int textSize = text.length;
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
while ((i + patternSize) <= textSize) {
|
||||
j = patternSize - 1;
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j--;
|
||||
if (j < 0)
|
||||
return i;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public static int BoyerMooreHorspoolSearch(char[] pattern, char[] text) {
|
||||
|
||||
int shift[] = new int[256];
|
||||
|
||||
for (int k = 0; k < 256; k++) {
|
||||
shift[k] = pattern.length;
|
||||
}
|
||||
|
||||
for (int k = 0; k < pattern.length - 1; k++) {
|
||||
shift[pattern[k]] = pattern.length - 1 - k;
|
||||
}
|
||||
|
||||
int i = 0, j = 0;
|
||||
|
||||
while ((i + pattern.length) <= text.length) {
|
||||
j = pattern.length - 1;
|
||||
|
||||
while (text[i + j] == pattern[j]) {
|
||||
j -= 1;
|
||||
if (j < 0)
|
||||
return i;
|
||||
}
|
||||
|
||||
i = i + shift[text[i + pattern.length - 1]];
|
||||
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
@ -1,43 +1,41 @@
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import com.baeldung.algorithms.binarysearch.BinarySearch;
|
||||
|
||||
public class BinarySearchUnitTest {
|
||||
|
||||
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
||||
int key = 6;
|
||||
int expectedIndexForSearchKey = 7;
|
||||
int low = 0;
|
||||
int high = sortedArray.length - 1;
|
||||
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.algorithms.binarysearch;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinarySearchUnitTest {
|
||||
|
||||
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
||||
int key = 6;
|
||||
int expectedIndexForSearchKey = 7;
|
||||
int low = 0;
|
||||
int high = sortedArray.length - 1;
|
||||
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
|
||||
BinarySearch binSearch = new BinarySearch();
|
||||
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,136 @@
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinaryTreeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(!bt.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(bt.containsNode(6));
|
||||
assertTrue(bt.containsNode(4));
|
||||
|
||||
assertFalse(bt.containsNode(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
int initialSize = bt.getSize();
|
||||
|
||||
assertTrue(bt.containsNode(3));
|
||||
bt.add(3);
|
||||
assertEquals(initialSize, bt.getSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertFalse(bt.containsNode(99));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
assertTrue(bt.containsNode(9));
|
||||
bt.delete(9);
|
||||
assertFalse(bt.containsNode(9));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
int initialSize = bt.getSize();
|
||||
|
||||
assertFalse(bt.containsNode(99));
|
||||
bt.delete(99);
|
||||
assertFalse(bt.containsNode(99));
|
||||
assertEquals(initialSize, bt.getSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void it_deletes_the_root() {
|
||||
int value = 12;
|
||||
BinaryTree bt = new BinaryTree();
|
||||
bt.add(value);
|
||||
|
||||
assertTrue(bt.containsNode(value));
|
||||
bt.delete(value);
|
||||
assertFalse(bt.containsNode(value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traverseInOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traverseInOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePreOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traversePreOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traversePostOrder(bt.root);
|
||||
System.out.println();
|
||||
bt.traversePostOrderWithoutRecursion();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() {
|
||||
|
||||
BinaryTree bt = createBinaryTree();
|
||||
|
||||
bt.traverseLevelOrder();
|
||||
}
|
||||
|
||||
private BinaryTree createBinaryTree() {
|
||||
BinaryTree bt = new BinaryTree();
|
||||
|
||||
bt.add(6);
|
||||
bt.add(4);
|
||||
bt.add(8);
|
||||
bt.add(3);
|
||||
bt.add(5);
|
||||
bt.add(7);
|
||||
bt.add(9);
|
||||
|
||||
return bt;
|
||||
}
|
||||
|
||||
}
|
@ -1,7 +1,8 @@
|
||||
package com.baeldung.graph;
|
||||
package com.baeldung.algorithms.dfs;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.algorithms.dfs.Graph;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphUnitTest {
|
@ -1,10 +1,10 @@
|
||||
package com.baeldung.algorithms.interpolationsearch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class InterpolationSearchUnitTest {
|
||||
|
||||
private int[] myData;
|
@ -0,0 +1,60 @@
|
||||
package com.baeldung.algorithms.quadtree;
|
||||
|
||||
import org.junit.Assert;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class QuadTreeSearchUnitTest {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(QuadTreeSearchUnitTest.class);
|
||||
|
||||
private static QuadTree quadTree;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
Region area = new Region(0, 0, 400, 400);
|
||||
quadTree = new QuadTree(area);
|
||||
|
||||
float[][] points = new float[][] { { 21, 25 }, { 55, 53 }, { 70, 318 }, { 98, 302 },
|
||||
{ 49, 229 }, { 135, 229 }, { 224, 292 }, { 206, 321 }, { 197, 258 }, { 245, 238 } };
|
||||
|
||||
for (int i = 0; i < points.length; i++) {
|
||||
Point point = new Point(points[i][0], points[i][1]);
|
||||
quadTree.addPoint(point);
|
||||
}
|
||||
LOGGER.info("\n" + quadTree.printTree(""));
|
||||
LOGGER.info("==============================================");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQuadTree_whenSearchingForRange_thenReturn1MatchingItem() {
|
||||
Region searchArea = new Region(200, 200, 250, 250);
|
||||
List<Point> result = quadTree.search(searchArea, null, "");
|
||||
LOGGER.info(result.toString());
|
||||
LOGGER.info(quadTree.printSearchTraversePath());
|
||||
|
||||
Assert.assertEquals(1, result.size());
|
||||
Assert.assertArrayEquals(new float[] { 245, 238 },
|
||||
new float[]{result.get(0).getX(), result.get(0).getY() }, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQuadTree_whenSearchingForRange_thenReturn2MatchingItems() {
|
||||
Region searchArea = new Region(0, 0, 100, 100);
|
||||
List<Point> result = quadTree.search(searchArea, null, "");
|
||||
LOGGER.info(result.toString());
|
||||
LOGGER.info(quadTree.printSearchTraversePath());
|
||||
|
||||
Assert.assertEquals(2, result.size());
|
||||
Assert.assertArrayEquals(new float[] { 21, 25 },
|
||||
new float[]{result.get(0).getX(), result.get(0).getY() }, 0);
|
||||
Assert.assertArrayEquals(new float[] { 55, 53 },
|
||||
new float[]{result.get(1).getX(), result.get(1).getY() }, 0);
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.baeldung.algorithms.textsearch;
|
||||
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TextSearchAlgorithmsUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void testStringSearchAlgorithms() {
|
||||
String text = "This is some nice text.";
|
||||
String pattern = "some";
|
||||
|
||||
int realPosition = text.indexOf(pattern);
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()));
|
||||
}
|
||||
|
||||
}
|
@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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-sorting</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>animal-sniffer-mvn-plugin</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
@ -43,4 +44,5 @@
|
||||
<animal-sniffer-maven-plugin.version>1.16</animal-sniffer-maven-plugin.version>
|
||||
<org.codehaus.mojo.signature.java16.version>1.0</org.codehaus.mojo.signature.java16.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,10 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>annotation-processing</artifactId>
|
||||
<name>annotation-processing</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
|
@ -1,13 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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>annotation-user</artifactId>
|
||||
<name>annotation-user</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>annotations</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>annotations</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
@ -1,14 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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>annotations</artifactId>
|
||||
<name>annotations</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
|
@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>antlr</artifactId>
|
||||
<name>antlr</name>
|
||||
@ -52,9 +53,10 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<properties>
|
||||
<antlr.version>4.7.1</antlr.version>
|
||||
<mojo.version>3.0.0</mojo.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -5,7 +5,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>apache-avro</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>apache-avro</name>
|
||||
<name>apache-avro</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
@ -67,5 +67,5 @@
|
||||
<avro.version>1.8.2</avro.version>
|
||||
<slf4j.version>1.7.25</slf4j.version>
|
||||
</properties>
|
||||
|
||||
|
||||
</project>
|
||||
|
@ -1,11 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>apache-bval</groupId>
|
||||
<artifactId>apache-bval</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>apache-bval</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
|
@ -1,9 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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>apache-curator</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>apache-curator</name>
|
||||
<name>apache-curator</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
|
3
apache-cxf/cxf-aegis/README.md
Normal file
3
apache-cxf/cxf-aegis/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant Articles
|
||||
|
||||
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)
|
@ -1,9 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-aegis</artifactId>
|
||||
<name>cxf-aegis</name>
|
||||
|
||||
<name>cxf-aegis</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
|
@ -1,11 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-introduction</artifactId>
|
||||
<name>cxf-introduction</name>
|
||||
|
||||
<name>cxf-introduction</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
|
@ -1,11 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-jaxrs-implementation</artifactId>
|
||||
<name>cxf-jaxrs-implementation</name>
|
||||
|
||||
<name>cxf-jaxrs-implementation</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-cxf</artifactId>
|
||||
|
3
apache-cxf/cxf-spring/README.md
Normal file
3
apache-cxf/cxf-spring/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
|
@ -1,9 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>cxf-spring</artifactId>
|
||||
<name>cxf-spring</name>
|
||||
<packaging>war</packaging>
|
||||
<name>cxf-spring</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
@ -98,7 +99,6 @@
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
|
@ -1,3 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -16,6 +16,6 @@
|
||||
<modules>
|
||||
<module>sse-jaxrs-server</module>
|
||||
<module>sse-jaxrs-client</module>
|
||||
</modules>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
@ -5,7 +5,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>sse-jaxrs-client</artifactId>
|
||||
<name>sse-jaxrs-client</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>sse-jaxrs</artifactId>
|
||||
|
@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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>apache-fop</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
|
@ -16,7 +16,7 @@
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>contextConfigLocation</param-name>
|
||||
<param-value>org.baeldung.config</param-value>
|
||||
<param-value>com.baeldung.config</param-value>
|
||||
</context-param>
|
||||
|
||||
<listener>
|
||||
|
@ -1,4 +1,4 @@
|
||||
package org.baeldung.java;
|
||||
package com.baeldung.java;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
@ -1,4 +1,4 @@
|
||||
package org.baeldung.java;
|
||||
package com.baeldung.java;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.BufferedReader;
|
@ -6,7 +6,7 @@
|
||||
<artifactId>apache-geode</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>apache-geode</name>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
@ -20,8 +20,9 @@
|
||||
<version>${geode.core}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<properties>
|
||||
<geode.core>1.6.0</geode.core>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,11 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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>apache-meecrowave</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<name>apache-meecrowave</name>
|
||||
<description>A sample REST API application with Meecrowave</description>
|
||||
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
@ -38,7 +39,7 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
@ -48,14 +49,15 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<meecrowave-junit.version>1.2.0</meecrowave-junit.version>
|
||||
<okhttp.version>3.10.0</okhttp.version>
|
||||
<meecrowave-jpa.version>1.2.1</meecrowave-jpa.version>
|
||||
<meecrowave-core.version>1.2.1</meecrowave-core.version>
|
||||
<meecrowave-maven-plugin.version>1.2.1</meecrowave-maven-plugin.version>
|
||||
<meecrowave-junit.version>1.2.0</meecrowave-junit.version>
|
||||
<okhttp.version>3.10.0</okhttp.version>
|
||||
<meecrowave-jpa.version>1.2.1</meecrowave-jpa.version>
|
||||
<meecrowave-core.version>1.2.1</meecrowave-core.version>
|
||||
<meecrowave-maven-plugin.version>1.2.1</meecrowave-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
4
apache-olingo/olingo2/README.md
Normal file
4
apache-olingo/olingo2/README.md
Normal file
@ -0,0 +1,4 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [OData Protocol Guide](https://www.baeldung.com/odata)
|
||||
- [Intro to OData with Olingo](https://www.baeldung.com/olingo)
|
@ -1,87 +1,87 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.baeldung.examples.olingo2</groupId>
|
||||
<artifactId>olingo2</artifactId>
|
||||
<name>olingo2</name>
|
||||
<description>Sample Olingo 2 Project</description>
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.examples.olingo2</groupId>
|
||||
<artifactId>olingo2</artifactId>
|
||||
<name>olingo2</name>
|
||||
<description>Sample Olingo 2 Project</description>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jersey</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jersey</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Olingo 2 Dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.apache.olingo</groupId>
|
||||
<artifactId>olingo-odata2-core</artifactId>
|
||||
<version>${olingo2.version}</version>
|
||||
<!-- Avoid jax-rs version conflict by excluding Olingo's version -->
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.olingo</groupId>
|
||||
<artifactId>olingo-odata2-jpa-processor-core</artifactId>
|
||||
<version>${olingo2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.olingo</groupId>
|
||||
<artifactId>olingo-odata2-jpa-processor-ref</artifactId>
|
||||
<version>${olingo2.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.eclipse.persistence</groupId>
|
||||
<artifactId>eclipselink</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<!-- Olingo 2 Dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.apache.olingo</groupId>
|
||||
<artifactId>olingo-odata2-core</artifactId>
|
||||
<version>${olingo2.version}</version>
|
||||
<!-- Avoid jax-rs version conflict by excluding Olingo's version -->
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.olingo</groupId>
|
||||
<artifactId>olingo-odata2-jpa-processor-core</artifactId>
|
||||
<version>${olingo2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.olingo</groupId>
|
||||
<artifactId>olingo-odata2-jpa-processor-ref</artifactId>
|
||||
<version>${olingo2.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.eclipse.persistence</groupId>
|
||||
<artifactId>eclipselink</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<olingo2.version>2.0.11</olingo2.version>
|
||||
</properties>
|
||||
<properties>
|
||||
<olingo2.version>2.0.11</olingo2.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
@ -1,4 +1,4 @@
|
||||
package org.baeldung.examples.olingo2;
|
||||
package com.baeldung.examples.olingo2;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@ -9,10 +9,8 @@ import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.EntityTransaction;
|
||||
import javax.persistence.FlushModeType;
|
||||
import javax.persistence.LockModeType;
|
||||
import javax.persistence.Persistence;
|
||||
import javax.persistence.Query;
|
||||
import javax.persistence.StoredProcedureQuery;
|
||||
import javax.persistence.SynchronizationType;
|
||||
import javax.persistence.TypedQuery;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaDelete;
|
||||
@ -25,11 +23,8 @@ import org.apache.olingo.odata2.api.processor.ODataContext;
|
||||
import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext;
|
||||
import org.apache.olingo.odata2.jpa.processor.api.ODataJPAServiceFactory;
|
||||
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
|
||||
import org.baeldung.examples.olingo2.JerseyConfig.EntityManagerFilter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.orm.jpa.EntityManagerFactoryUtils;
|
||||
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
@ -58,7 +53,7 @@ public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory {
|
||||
ODataJPAContext ctx = getODataJPAContext();
|
||||
ODataContext octx = ctx.getODataContext();
|
||||
HttpServletRequest request = (HttpServletRequest)octx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT);
|
||||
EntityManager em = (EntityManager)request.getAttribute(EntityManagerFilter.EM_REQUEST_ATTRIBUTE);
|
||||
EntityManager em = (EntityManager)request.getAttribute(JerseyConfig.EntityManagerFilter.EM_REQUEST_ATTRIBUTE);
|
||||
|
||||
// Here we're passing the EM that was created by the EntityManagerFilter (see JerseyConfig)
|
||||
ctx.setEntityManager(new EntityManagerWrapper(em));
|
@ -1,11 +1,10 @@
|
||||
package org.baeldung.examples.olingo2;
|
||||
package com.baeldung.examples.olingo2;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.EntityTransaction;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.ws.rs.ApplicationPath;
|
||||
import javax.ws.rs.Path;
|
@ -1,8 +1,7 @@
|
||||
package org.baeldung.examples.olingo2;
|
||||
package com.baeldung.examples.olingo2;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
|
||||
|
||||
@SpringBootApplication
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user