merge upstream
This commit is contained in:
commit
85a327266f
|
@ -1,5 +1,5 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>algorithms-miscellaneous-3</artifactId>
|
<artifactId>algorithms-miscellaneous-3</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
@ -18,17 +18,28 @@
|
||||||
<version>${org.assertj.core.version}</version>
|
<version>${org.assertj.core.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.commons</groupId>
|
<groupId>org.apache.commons</groupId>
|
||||||
<artifactId>commons-collections4</artifactId>
|
<artifactId>commons-collections4</artifactId>
|
||||||
<version>${commons-collections4.version}</version>
|
<version>${commons-collections4.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.guava</groupId>
|
<groupId>com.google.guava</groupId>
|
||||||
<artifactId>guava</artifactId>
|
<artifactId>guava</artifactId>
|
||||||
<version>${guava.version}</version>
|
<version>${guava.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.retrofit2</groupId>
|
||||||
|
<artifactId>retrofit</artifactId>
|
||||||
|
<version>${retrofit.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.retrofit2</groupId>
|
||||||
|
<artifactId>converter-jackson</artifactId>
|
||||||
|
<version>${retrofit.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -61,5 +72,6 @@
|
||||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||||
<commons-collections4.version>4.3</commons-collections4.version>
|
<commons-collections4.version>4.3</commons-collections4.version>
|
||||||
<guava.version>28.0-jre</guava.version>
|
<guava.version>28.0-jre</guava.version>
|
||||||
|
<retrofit.version>2.6.0</retrofit.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,35 @@
|
||||||
|
package com.baeldung.algorithms.interpolationsearch;
|
||||||
|
|
||||||
|
public class InterpolationSearch {
|
||||||
|
|
||||||
|
public static int interpolationSearch(int[] data, int item) {
|
||||||
|
|
||||||
|
int highEnd = (data.length - 1);
|
||||||
|
int lowEnd = 0;
|
||||||
|
|
||||||
|
while (item >= data[lowEnd] && item <= data[highEnd] && lowEnd <= highEnd) {
|
||||||
|
|
||||||
|
int probe = lowEnd + (highEnd - lowEnd) * (item - data[lowEnd]) / (data[highEnd] - data[lowEnd]);
|
||||||
|
|
||||||
|
if (highEnd == lowEnd) {
|
||||||
|
if (data[lowEnd] == item) {
|
||||||
|
return lowEnd;
|
||||||
|
} else {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data[probe] == item) {
|
||||||
|
return probe;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data[probe] < item) {
|
||||||
|
lowEnd = probe + 1;
|
||||||
|
} else {
|
||||||
|
highEnd = probe - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates all coordinates for a particular cluster centroid.
|
||||||
|
*/
|
||||||
|
public class Centroid {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The centroid coordinates.
|
||||||
|
*/
|
||||||
|
private final Map<String, Double> coordinates;
|
||||||
|
|
||||||
|
public Centroid(Map<String, Double> coordinates) {
|
||||||
|
this.coordinates = coordinates;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Double> getCoordinates() {
|
||||||
|
return coordinates;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (o == null || getClass() != o.getClass()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Centroid centroid = (Centroid) o;
|
||||||
|
return Objects.equals(getCoordinates(), centroid.getCoordinates());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(getCoordinates());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Centroid " + coordinates;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Defines a contract to calculate distance between two feature vectors. The less the
|
||||||
|
* calculated distance, the more two items are similar to each other.
|
||||||
|
*/
|
||||||
|
public interface Distance {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the distance between two feature vectors.
|
||||||
|
*
|
||||||
|
* @param f1 The first set of features.
|
||||||
|
* @param f2 The second set of features.
|
||||||
|
* @return Calculated distance.
|
||||||
|
* @throws IllegalArgumentException If the given feature vectors are invalid.
|
||||||
|
*/
|
||||||
|
double calculate(Map<String, Double> f1, Map<String, Double> f2);
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates methods to calculates errors between centroid and the cluster members.
|
||||||
|
*/
|
||||||
|
public class Errors {
|
||||||
|
|
||||||
|
public static double sse(Map<Centroid, List<Record>> clustered, Distance distance) {
|
||||||
|
double sum = 0;
|
||||||
|
for (Map.Entry<Centroid, List<Record>> entry : clustered.entrySet()) {
|
||||||
|
Centroid centroid = entry.getKey();
|
||||||
|
for (Record record : entry.getValue()) {
|
||||||
|
double d = distance.calculate(centroid.getCoordinates(), record.getFeatures());
|
||||||
|
sum += Math.pow(d, 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the distance between two items using the Euclidean formula.
|
||||||
|
*/
|
||||||
|
public class EuclideanDistance implements Distance {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double calculate(Map<String, Double> f1, Map<String, Double> f2) {
|
||||||
|
if (f1 == null || f2 == null) {
|
||||||
|
throw new IllegalArgumentException("Feature vectors can't be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
double sum = 0;
|
||||||
|
for (String key : f1.keySet()) {
|
||||||
|
Double v1 = f1.get(key);
|
||||||
|
Double v2 = f2.get(key);
|
||||||
|
|
||||||
|
if (v1 != null && v2 != null) sum += Math.pow(v1 - v2, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.sqrt(sum);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,236 @@
|
||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import static java.util.stream.Collectors.toList;
|
||||||
|
import static java.util.stream.Collectors.toSet;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates an implementation of KMeans clustering algorithm.
|
||||||
|
*
|
||||||
|
* @author Ali Dehghani
|
||||||
|
*/
|
||||||
|
public class KMeans {
|
||||||
|
|
||||||
|
private KMeans() {
|
||||||
|
throw new IllegalAccessError("You shouldn't call this constructor");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Will be used to generate random numbers.
|
||||||
|
*/
|
||||||
|
private static final Random random = new Random();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Performs the K-Means clustering algorithm on the given dataset.
|
||||||
|
*
|
||||||
|
* @param records The dataset.
|
||||||
|
* @param k Number of Clusters.
|
||||||
|
* @param distance To calculate the distance between two items.
|
||||||
|
* @param maxIterations Upper bound for the number of iterations.
|
||||||
|
* @return K clusters along with their features.
|
||||||
|
*/
|
||||||
|
public static Map<Centroid, List<Record>> fit(List<Record> records, int k, Distance distance, int maxIterations) {
|
||||||
|
applyPreconditions(records, k, distance, maxIterations);
|
||||||
|
|
||||||
|
List<Centroid> centroids = randomCentroids(records, k);
|
||||||
|
Map<Centroid, List<Record>> clusters = new HashMap<>();
|
||||||
|
Map<Centroid, List<Record>> lastState = new HashMap<>();
|
||||||
|
|
||||||
|
// iterate for a pre-defined number of times
|
||||||
|
for (int i = 0; i < maxIterations; i++) {
|
||||||
|
boolean isLastIteration = i == maxIterations - 1;
|
||||||
|
|
||||||
|
// in each iteration we should find the nearest centroid for each record
|
||||||
|
for (Record record : records) {
|
||||||
|
Centroid centroid = nearestCentroid(record, centroids, distance);
|
||||||
|
assignToCluster(clusters, record, centroid);
|
||||||
|
}
|
||||||
|
|
||||||
|
// if the assignment does not change, then the algorithm terminates
|
||||||
|
boolean shouldTerminate = isLastIteration || clusters.equals(lastState);
|
||||||
|
lastState = clusters;
|
||||||
|
if (shouldTerminate) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// at the end of each iteration we should relocate the centroids
|
||||||
|
centroids = relocateCentroids(clusters);
|
||||||
|
clusters = new HashMap<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
return lastState;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move all cluster centroids to the average of all assigned features.
|
||||||
|
*
|
||||||
|
* @param clusters The current cluster configuration.
|
||||||
|
* @return Collection of new and relocated centroids.
|
||||||
|
*/
|
||||||
|
private static List<Centroid> relocateCentroids(Map<Centroid, List<Record>> clusters) {
|
||||||
|
return clusters
|
||||||
|
.entrySet()
|
||||||
|
.stream()
|
||||||
|
.map(e -> average(e.getKey(), e.getValue()))
|
||||||
|
.collect(toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves the given centroid to the average position of all assigned features. If
|
||||||
|
* the centroid has no feature in its cluster, then there would be no need for a
|
||||||
|
* relocation. Otherwise, for each entry we calculate the average of all records
|
||||||
|
* first by summing all the entries and then dividing the final summation value by
|
||||||
|
* the number of records.
|
||||||
|
*
|
||||||
|
* @param centroid The centroid to move.
|
||||||
|
* @param records The assigned features.
|
||||||
|
* @return The moved centroid.
|
||||||
|
*/
|
||||||
|
private static Centroid average(Centroid centroid, List<Record> records) {
|
||||||
|
// if this cluster is empty, then we shouldn't move the centroid
|
||||||
|
if (records == null || records.isEmpty()) {
|
||||||
|
return centroid;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Since some records don't have all possible attributes, we initialize
|
||||||
|
// average coordinates equal to current centroid coordinates
|
||||||
|
Map<String, Double> average = centroid.getCoordinates();
|
||||||
|
|
||||||
|
// The average function works correctly if we clear all coordinates corresponding
|
||||||
|
// to present record attributes
|
||||||
|
records
|
||||||
|
.stream()
|
||||||
|
.flatMap(e -> e
|
||||||
|
.getFeatures()
|
||||||
|
.keySet()
|
||||||
|
.stream())
|
||||||
|
.forEach(k -> average.put(k, 0.0));
|
||||||
|
|
||||||
|
for (Record record : records) {
|
||||||
|
record
|
||||||
|
.getFeatures()
|
||||||
|
.forEach((k, v) -> average.compute(k, (k1, currentValue) -> v + currentValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
average.forEach((k, v) -> average.put(k, v / records.size()));
|
||||||
|
|
||||||
|
return new Centroid(average);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Assigns a feature vector to the given centroid. If this is the first assignment for this centroid,
|
||||||
|
* first we should create the list.
|
||||||
|
*
|
||||||
|
* @param clusters The current cluster configuration.
|
||||||
|
* @param record The feature vector.
|
||||||
|
* @param centroid The centroid.
|
||||||
|
*/
|
||||||
|
private static void assignToCluster(Map<Centroid, List<Record>> clusters, Record record, Centroid centroid) {
|
||||||
|
clusters.compute(centroid, (key, list) -> {
|
||||||
|
if (list == null) {
|
||||||
|
list = new ArrayList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
list.add(record);
|
||||||
|
return list;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* With the help of the given distance calculator, iterates through centroids and finds the
|
||||||
|
* nearest one to the given record.
|
||||||
|
*
|
||||||
|
* @param record The feature vector to find a centroid for.
|
||||||
|
* @param centroids Collection of all centroids.
|
||||||
|
* @param distance To calculate the distance between two items.
|
||||||
|
* @return The nearest centroid to the given feature vector.
|
||||||
|
*/
|
||||||
|
private static Centroid nearestCentroid(Record record, List<Centroid> centroids, Distance distance) {
|
||||||
|
double minimumDistance = Double.MAX_VALUE;
|
||||||
|
Centroid nearest = null;
|
||||||
|
|
||||||
|
for (Centroid centroid : centroids) {
|
||||||
|
double currentDistance = distance.calculate(record.getFeatures(), centroid.getCoordinates());
|
||||||
|
|
||||||
|
if (currentDistance < minimumDistance) {
|
||||||
|
minimumDistance = currentDistance;
|
||||||
|
nearest = centroid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nearest;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates k random centroids. Before kicking-off the centroid generation process,
|
||||||
|
* first we calculate the possible value range for each attribute. Then when
|
||||||
|
* we're going to generate the centroids, we generate random coordinates in
|
||||||
|
* the [min, max] range for each attribute.
|
||||||
|
*
|
||||||
|
* @param records The dataset which helps to calculate the [min, max] range for
|
||||||
|
* each attribute.
|
||||||
|
* @param k Number of clusters.
|
||||||
|
* @return Collections of randomly generated centroids.
|
||||||
|
*/
|
||||||
|
private static List<Centroid> randomCentroids(List<Record> records, int k) {
|
||||||
|
List<Centroid> centroids = new ArrayList<>();
|
||||||
|
Map<String, Double> maxs = new HashMap<>();
|
||||||
|
Map<String, Double> mins = new HashMap<>();
|
||||||
|
|
||||||
|
for (Record record : records) {
|
||||||
|
record
|
||||||
|
.getFeatures()
|
||||||
|
.forEach((key, value) -> {
|
||||||
|
// compares the value with the current max and choose the bigger value between them
|
||||||
|
maxs.compute(key, (k1, max) -> max == null || value > max ? value : max);
|
||||||
|
|
||||||
|
// compare the value with the current min and choose the smaller value between them
|
||||||
|
mins.compute(key, (k1, min) -> min == null || value < min ? value : min);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<String> attributes = records
|
||||||
|
.stream()
|
||||||
|
.flatMap(e -> e
|
||||||
|
.getFeatures()
|
||||||
|
.keySet()
|
||||||
|
.stream())
|
||||||
|
.collect(toSet());
|
||||||
|
for (int i = 0; i < k; i++) {
|
||||||
|
Map<String, Double> coordinates = new HashMap<>();
|
||||||
|
for (String attribute : attributes) {
|
||||||
|
double max = maxs.get(attribute);
|
||||||
|
double min = mins.get(attribute);
|
||||||
|
coordinates.put(attribute, random.nextDouble() * (max - min) + min);
|
||||||
|
}
|
||||||
|
|
||||||
|
centroids.add(new Centroid(coordinates));
|
||||||
|
}
|
||||||
|
|
||||||
|
return centroids;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void applyPreconditions(List<Record> records, int k, Distance distance, int maxIterations) {
|
||||||
|
if (records == null || records.isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("The dataset can't be empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (k <= 1) {
|
||||||
|
throw new IllegalArgumentException("It doesn't make sense to have less than or equal to 1 cluster");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (distance == null) {
|
||||||
|
throw new IllegalArgumentException("The distance calculator is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maxIterations <= 0) {
|
||||||
|
throw new IllegalArgumentException("Max iterations should be a positive number");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,144 @@
|
||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import okhttp3.OkHttpClient;
|
||||||
|
import retrofit2.Retrofit;
|
||||||
|
import retrofit2.converter.jackson.JacksonConverterFactory;
|
||||||
|
|
||||||
|
import static java.util.stream.Collectors.toSet;
|
||||||
|
|
||||||
|
public class LastFm {
|
||||||
|
|
||||||
|
private static OkHttpClient okHttp = new OkHttpClient.Builder()
|
||||||
|
.addInterceptor(new LastFmService.Authenticator("put your API key here"))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
private static Retrofit retrofit = new Retrofit.Builder()
|
||||||
|
.client(okHttp)
|
||||||
|
.addConverterFactory(JacksonConverterFactory.create())
|
||||||
|
.baseUrl("http://ws.audioscrobbler.com/")
|
||||||
|
.build();
|
||||||
|
|
||||||
|
private static LastFmService lastFm = retrofit.create(LastFmService.class);
|
||||||
|
|
||||||
|
private static ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
List<String> artists = getTop100Artists();
|
||||||
|
Set<String> tags = getTop100Tags();
|
||||||
|
List<Record> records = datasetWithTaggedArtists(artists, tags);
|
||||||
|
|
||||||
|
Map<Centroid, List<Record>> clusters = KMeans.fit(records, 7, new EuclideanDistance(), 1000);
|
||||||
|
// Print the cluster configuration
|
||||||
|
clusters.forEach((key, value) -> {
|
||||||
|
System.out.println("------------------------------ CLUSTER -----------------------------------");
|
||||||
|
|
||||||
|
System.out.println(sortedCentroid(key));
|
||||||
|
String members = String.join(", ", value
|
||||||
|
.stream()
|
||||||
|
.map(Record::getDescription)
|
||||||
|
.collect(toSet()));
|
||||||
|
System.out.print(members);
|
||||||
|
|
||||||
|
System.out.println();
|
||||||
|
System.out.println();
|
||||||
|
});
|
||||||
|
|
||||||
|
Map<String, Object> json = convertToD3CompatibleMap(clusters);
|
||||||
|
System.out.println(mapper.writeValueAsString(json));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, Object> convertToD3CompatibleMap(Map<Centroid, List<Record>> clusters) {
|
||||||
|
Map<String, Object> json = new HashMap<>();
|
||||||
|
json.put("name", "Musicians");
|
||||||
|
List<Map<String, Object>> children = new ArrayList<>();
|
||||||
|
clusters.forEach((key, value) -> {
|
||||||
|
Map<String, Object> child = new HashMap<>();
|
||||||
|
child.put("name", dominantGenre(sortedCentroid(key)));
|
||||||
|
List<Map<String, String>> nested = new ArrayList<>();
|
||||||
|
for (Record record : value) {
|
||||||
|
nested.add(Collections.singletonMap("name", record.getDescription()));
|
||||||
|
}
|
||||||
|
child.put("children", nested);
|
||||||
|
|
||||||
|
children.add(child);
|
||||||
|
});
|
||||||
|
json.put("children", children);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String dominantGenre(Centroid centroid) {
|
||||||
|
return centroid
|
||||||
|
.getCoordinates()
|
||||||
|
.keySet()
|
||||||
|
.stream()
|
||||||
|
.limit(2)
|
||||||
|
.collect(Collectors.joining(", "));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Centroid sortedCentroid(Centroid key) {
|
||||||
|
List<Map.Entry<String, Double>> entries = new ArrayList<>(key
|
||||||
|
.getCoordinates()
|
||||||
|
.entrySet());
|
||||||
|
entries.sort((e1, e2) -> e2
|
||||||
|
.getValue()
|
||||||
|
.compareTo(e1.getValue()));
|
||||||
|
|
||||||
|
Map<String, Double> sorted = new LinkedHashMap<>();
|
||||||
|
for (Map.Entry<String, Double> entry : entries) {
|
||||||
|
sorted.put(entry.getKey(), entry.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Centroid(sorted);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Record> datasetWithTaggedArtists(List<String> artists, Set<String> topTags) throws IOException {
|
||||||
|
List<Record> records = new ArrayList<>();
|
||||||
|
for (String artist : artists) {
|
||||||
|
Map<String, Double> tags = lastFm
|
||||||
|
.topTagsFor(artist)
|
||||||
|
.execute()
|
||||||
|
.body()
|
||||||
|
.all();
|
||||||
|
|
||||||
|
// Only keep popular tags.
|
||||||
|
tags
|
||||||
|
.entrySet()
|
||||||
|
.removeIf(e -> !topTags.contains(e.getKey()));
|
||||||
|
|
||||||
|
records.add(new Record(artist, tags));
|
||||||
|
}
|
||||||
|
return records;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Set<String> getTop100Tags() throws IOException {
|
||||||
|
return lastFm
|
||||||
|
.topTags()
|
||||||
|
.execute()
|
||||||
|
.body()
|
||||||
|
.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> getTop100Artists() throws IOException {
|
||||||
|
List<String> artists = new ArrayList<>();
|
||||||
|
for (int i = 1; i <= 2; i++) {
|
||||||
|
artists.addAll(lastFm
|
||||||
|
.topArtists(i)
|
||||||
|
.execute()
|
||||||
|
.body()
|
||||||
|
.all());
|
||||||
|
}
|
||||||
|
|
||||||
|
return artists;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,118 @@
|
||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import okhttp3.HttpUrl;
|
||||||
|
import okhttp3.Interceptor;
|
||||||
|
import okhttp3.Request;
|
||||||
|
import okhttp3.Response;
|
||||||
|
import retrofit2.Call;
|
||||||
|
import retrofit2.http.GET;
|
||||||
|
import retrofit2.http.Query;
|
||||||
|
|
||||||
|
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
|
||||||
|
import static java.util.stream.Collectors.toList;
|
||||||
|
|
||||||
|
public interface LastFmService {
|
||||||
|
|
||||||
|
@GET("/2.0/?method=chart.gettopartists&format=json&limit=50")
|
||||||
|
Call<Artists> topArtists(@Query("page") int page);
|
||||||
|
|
||||||
|
@GET("/2.0/?method=artist.gettoptags&format=json&limit=20&autocorrect=1")
|
||||||
|
Call<Tags> topTagsFor(@Query("artist") String artist);
|
||||||
|
|
||||||
|
@GET("/2.0/?method=chart.gettoptags&format=json&limit=100")
|
||||||
|
Call<TopTags> topTags();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTP interceptor to intercept all HTTP requests and add the API key to them.
|
||||||
|
*/
|
||||||
|
class Authenticator implements Interceptor {
|
||||||
|
|
||||||
|
private final String apiKey;
|
||||||
|
|
||||||
|
Authenticator(String apiKey) {
|
||||||
|
this.apiKey = apiKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response intercept(Chain chain) throws IOException {
|
||||||
|
HttpUrl url = chain
|
||||||
|
.request()
|
||||||
|
.url()
|
||||||
|
.newBuilder()
|
||||||
|
.addQueryParameter("api_key", apiKey)
|
||||||
|
.build();
|
||||||
|
Request request = chain
|
||||||
|
.request()
|
||||||
|
.newBuilder()
|
||||||
|
.url(url)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return chain.proceed(request);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@JsonAutoDetect(fieldVisibility = ANY)
|
||||||
|
class TopTags {
|
||||||
|
|
||||||
|
private Map<String, Object> tags;
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public Set<String> all() {
|
||||||
|
List<Map<String, Object>> topTags = (List<Map<String, Object>>) tags.get("tag");
|
||||||
|
return topTags
|
||||||
|
.stream()
|
||||||
|
.map(e -> ((String) e.get("name")))
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@JsonAutoDetect(fieldVisibility = ANY)
|
||||||
|
class Tags {
|
||||||
|
|
||||||
|
@JsonProperty("toptags") private Map<String, Object> topTags;
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public Map<String, Double> all() {
|
||||||
|
try {
|
||||||
|
Map<String, Double> all = new HashMap<>();
|
||||||
|
List<Map<String, Object>> tags = (List<Map<String, Object>>) topTags.get("tag");
|
||||||
|
for (Map<String, Object> tag : tags) {
|
||||||
|
all.put(((String) tag.get("name")), ((Integer) tag.get("count")).doubleValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
return all;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Collections.emptyMap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@JsonAutoDetect(fieldVisibility = ANY)
|
||||||
|
class Artists {
|
||||||
|
|
||||||
|
private Map<String, Object> artists;
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public List<String> all() {
|
||||||
|
try {
|
||||||
|
List<Map<String, Object>> artists = (List<Map<String, Object>>) this.artists.get("artist");
|
||||||
|
return artists
|
||||||
|
.stream()
|
||||||
|
.map(e -> ((String) e.get("name")))
|
||||||
|
.collect(toList());
|
||||||
|
} catch (Exception e) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,65 @@
|
||||||
|
package com.baeldung.algorithms.kmeans;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates all feature values for a few attributes. Optionally each record
|
||||||
|
* can be described with the {@link #description} field.
|
||||||
|
*/
|
||||||
|
public class Record {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The record description. For example, this can be the artist name for the famous musician
|
||||||
|
* example.
|
||||||
|
*/
|
||||||
|
private final String description;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encapsulates all attributes and their corresponding values, i.e. features.
|
||||||
|
*/
|
||||||
|
private final Map<String, Double> features;
|
||||||
|
|
||||||
|
public Record(String description, Map<String, Double> features) {
|
||||||
|
this.description = description;
|
||||||
|
this.features = features;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Record(Map<String, Double> features) {
|
||||||
|
this("", features);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Double> getFeatures() {
|
||||||
|
return features;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
String prefix = description == null || description
|
||||||
|
.trim()
|
||||||
|
.isEmpty() ? "Record" : description;
|
||||||
|
|
||||||
|
return prefix + ": " + features;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object o) {
|
||||||
|
if (this == o) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (o == null || getClass() != o.getClass()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Record record = (Record) o;
|
||||||
|
return Objects.equals(getDescription(), record.getDescription()) && Objects.equals(getFeatures(), record.getFeatures());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return Objects.hash(getDescription(), getFeatures());
|
||||||
|
}
|
||||||
|
}
|
|
@ -4,7 +4,7 @@ import org.apache.commons.lang3.StringUtils;
|
||||||
|
|
||||||
public class PrintTriangleExamples {
|
public class PrintTriangleExamples {
|
||||||
|
|
||||||
public static String printARightAngledTriangle(int N) {
|
public static String printARightTriangle(int N) {
|
||||||
StringBuilder result = new StringBuilder();
|
StringBuilder result = new StringBuilder();
|
||||||
for (int r = 1; r <= N; r++) {
|
for (int r = 1; r <= N; r++) {
|
||||||
for (int j = 1; j <= r; j++) {
|
for (int j = 1; j <= r; j++) {
|
||||||
|
@ -29,6 +29,17 @@ public class PrintTriangleExamples {
|
||||||
return result.toString();
|
return result.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static String printAnIsoscelesTriangleUsingStringUtils(int N) {
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
|
||||||
|
for (int r = 1; r <= N; r++) {
|
||||||
|
result.append(StringUtils.repeat(' ', N - r));
|
||||||
|
result.append(StringUtils.repeat('*', 2 * r - 1));
|
||||||
|
result.append(System.lineSeparator());
|
||||||
|
}
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
|
||||||
public static String printAnIsoscelesTriangleUsingSubstring(int N) {
|
public static String printAnIsoscelesTriangleUsingSubstring(int N) {
|
||||||
StringBuilder result = new StringBuilder();
|
StringBuilder result = new StringBuilder();
|
||||||
String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1);
|
String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1);
|
||||||
|
@ -41,8 +52,9 @@ public class PrintTriangleExamples {
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
System.out.println(printARightAngledTriangle(5));
|
System.out.println(printARightTriangle(5));
|
||||||
System.out.println(printAnIsoscelesTriangle(5));
|
System.out.println(printAnIsoscelesTriangle(5));
|
||||||
|
System.out.println(printAnIsoscelesTriangleUsingStringUtils(5));
|
||||||
System.out.println(printAnIsoscelesTriangleUsingSubstring(5));
|
System.out.println(printAnIsoscelesTriangleUsingSubstring(5));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,490 @@
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Radiohead"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Red Hot Chili Peppers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Coldplay"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Nirvana"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Panic! at the Disco"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Cure"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Linkin Park"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Radiohead"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Red Hot Chili Peppers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Coldplay"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Nirvana"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Panic! at the Disco"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Cure"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Linkin Park"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Muse"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Maroon 5"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Foo Fighters"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Paramore"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Oasis"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Fall Out Boy"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "OneRepublic"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Weezer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "System of a Down"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The White Stripes"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "rock, alternative"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Lil Nas X"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Post Malone"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Drake"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Kanye West"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Kendrick Lamar"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tyler, the Creator"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Eminem"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Childish Gambino"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Frank Ocean"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lil Nas X"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Post Malone"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Drake"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Kanye West"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Kendrick Lamar"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tyler, the Creator"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Eminem"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Childish Gambino"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Frank Ocean"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lizzo"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Travi$ Scott"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "A$AP Rocky"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Nicki Minaj"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "xxxtentacion"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "Hip-Hop, rap"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Arctic Monkeys"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Imagine Dragons"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Killers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Gorillaz"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Black Keys"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Arctic Monkeys"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Imagine Dragons"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Killers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Gorillaz"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Black Keys"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Twenty One Pilots"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ellie Goulding"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Florence + the Machine"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Vampire Weekend"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Smiths"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Strokes"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "MGMT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Foster the People"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Two Door Cinema Club"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Cage the Elephant"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Arcade Fire"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The 1975"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "indie, alternative"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Ed Sheeran"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tame Impala"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ed Sheeran"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Tame Impala"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Green Day"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Metallica"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "blink-182"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Bon Iver"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Clash"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "rock, punk rock"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Calvin Harris"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Weeknd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Chainsmokers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Daft Punk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Marshmello"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "David Guetta"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Calvin Harris"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Weeknd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Chainsmokers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Daft Punk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Marshmello"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "David Guetta"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Avicii"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Kygo"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Martin Garrix"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Major Lazer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Depeche Mode"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "electronic, dance"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Queen"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Beatles"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "David Bowie"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Fleetwood Mac"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Pink Floyd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Rolling Stones"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Led Zeppelin"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Queen"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Beatles"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "David Bowie"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Fleetwood Mac"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Pink Floyd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "The Rolling Stones"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Led Zeppelin"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Elton John"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "classic rock, rock"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"name": "Billie Eilish"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ariana Grande"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Taylor Swift"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Beyoncé"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Shawn Mendes"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Rihanna"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lana Del Rey"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Katy Perry"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lady Gaga"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Miley Cyrus"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Mark Ronson"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Madonna"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lorde"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Khalid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Billie Eilish"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Ariana Grande"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Taylor Swift"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Beyoncé"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Shawn Mendes"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Rihanna"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lana Del Rey"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Katy Perry"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lady Gaga"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Miley Cyrus"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Mark Ronson"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Madonna"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Lorde"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Khalid"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Sia"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Sam Smith"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Halsey"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Michael Jackson"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Charli XCX"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Britney Spears"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Dua Lipa"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Jonas Brothers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Bruno Mars"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Carly Rae Jepsen"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "P!nk"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Adele"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "pop, female vocalists"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"name": "Musicians"
|
||||||
|
}
|
|
@ -0,0 +1,68 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<style>
|
||||||
|
.node circle {
|
||||||
|
fill: #fff;
|
||||||
|
stroke: steelblue;
|
||||||
|
stroke-width: 1.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.node {
|
||||||
|
font: 10px sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.link {
|
||||||
|
fill: none;
|
||||||
|
stroke: #ccc;
|
||||||
|
stroke-width: 1.5px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
<body>
|
||||||
|
<script src="http://d3js.org/d3.v3.min.js"></script>
|
||||||
|
<script>
|
||||||
|
var diameter = 1100;
|
||||||
|
var tree = d3.layout.tree()
|
||||||
|
.size([360, diameter / 2 - 300])
|
||||||
|
.separation(function (a, b) {
|
||||||
|
return (a.parent == b.parent ? 1 : 2) / a.depth;
|
||||||
|
});
|
||||||
|
var diagonal = d3.svg.diagonal.radial()
|
||||||
|
.projection(function (d) {
|
||||||
|
return [d.y, d.x / 180 * Math.PI];
|
||||||
|
});
|
||||||
|
var svg = d3.select("body").append("svg")
|
||||||
|
.attr("width", diameter)
|
||||||
|
.attr("height", diameter - 150)
|
||||||
|
.append("g")
|
||||||
|
.attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")");
|
||||||
|
d3.json("lastfm.json", function (error, root) {
|
||||||
|
var nodes = tree.nodes(root),
|
||||||
|
links = tree.links(nodes);
|
||||||
|
var link = svg.selectAll(".link")
|
||||||
|
.data(links)
|
||||||
|
.enter().append("path")
|
||||||
|
.attr("class", "link")
|
||||||
|
.attr("d", diagonal);
|
||||||
|
var node = svg.selectAll(".node")
|
||||||
|
.data(nodes)
|
||||||
|
.enter().append("g")
|
||||||
|
.attr("class", "node")
|
||||||
|
.attr("transform", function (d) {
|
||||||
|
return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
|
||||||
|
})
|
||||||
|
node.append("circle")
|
||||||
|
.attr("r", 4.5);
|
||||||
|
node.append("text")
|
||||||
|
.attr("dy", ".31em")
|
||||||
|
.attr("text-anchor", function (d) {
|
||||||
|
return d.x < 180 ? "start" : "end";
|
||||||
|
})
|
||||||
|
.attr("transform", function (d) {
|
||||||
|
return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)";
|
||||||
|
})
|
||||||
|
.text(function (d) {
|
||||||
|
return d.name;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
d3.select(self.frameElement).style("height", diameter - 150 + "px");
|
||||||
|
</script>
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.algorithms.interpolationsearch;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class InterpolationSearchUnitTest {
|
||||||
|
|
||||||
|
private int[] myData;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
myData = new int[]{13,21,34,55,69,73,84,101};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSortedArray_whenLookingFor84_thenReturn6() {
|
||||||
|
int pos = InterpolationSearch.interpolationSearch(myData, 84);
|
||||||
|
assertEquals(6, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSortedArray_whenLookingFor19_thenReturnMinusOne() {
|
||||||
|
int pos = InterpolationSearch.interpolationSearch(myData, 19);
|
||||||
|
assertEquals(-1, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -9,9 +9,9 @@ import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
@RunWith(JUnitParamsRunner.class)
|
@RunWith(JUnitParamsRunner.class)
|
||||||
public class PrintTriangleExamplesUnitTest {
|
public class PrintTriangleExamplesUnitTest {
|
||||||
|
|
||||||
private static Object[][] rightAngledTriangles() {
|
private static Object[][] rightTriangles() {
|
||||||
String expected0 = "";
|
String expected0 = "";
|
||||||
|
|
||||||
String expected2 = "*" + System.lineSeparator()
|
String expected2 = "*" + System.lineSeparator()
|
||||||
+ "**" + System.lineSeparator();
|
+ "**" + System.lineSeparator();
|
||||||
|
@ -39,9 +39,9 @@ public class PrintTriangleExamplesUnitTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Parameters(method = "rightAngledTriangles")
|
@Parameters(method = "rightTriangles")
|
||||||
public void whenPrintARightAngledTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||||
String actual = PrintTriangleExamples.printARightAngledTriangle(nrOfRows);
|
String actual = PrintTriangleExamples.printARightTriangle(nrOfRows);
|
||||||
|
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
@ -81,6 +81,14 @@ public class PrintTriangleExamplesUnitTest {
|
||||||
|
|
||||||
assertEquals(expected, actual);
|
assertEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Parameters(method = "isoscelesTriangles")
|
||||||
|
public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||||
|
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows);
|
||||||
|
|
||||||
|
assertEquals(expected, actual);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Parameters(method = "isoscelesTriangles")
|
@Parameters(method = "isoscelesTriangles")
|
||||||
|
|
|
@ -5,3 +5,4 @@
|
||||||
- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort)
|
- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort)
|
||||||
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
|
- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort)
|
||||||
- [Heap Sort in Java](https://www.baeldung.com/java-heap-sort)
|
- [Heap Sort in Java](https://www.baeldung.com/java-heap-sort)
|
||||||
|
- [Shell Sort in Java](https://www.baeldung.com/java-shell-sort)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.algorithms.stringsortingbynumber;
|
package com.baeldung.algorithms.sort.bynumber;
|
||||||
|
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
package com.baeldung.algorithms.stringsortingbynumber;
|
package com.baeldung.algorithms.sort.bynumber;
|
||||||
|
|
||||||
import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators;
|
import com.baeldung.algorithms.sort.bynumber.NaturalOrderComparators;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
|
@ -8,3 +8,4 @@
|
||||||
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
||||||
- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml)
|
- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml)
|
||||||
- [Integrating Groovy into Java Applications](https://www.baeldung.com/groovy-java-applications)
|
- [Integrating Groovy into Java Applications](https://www.baeldung.com/groovy-java-applications)
|
||||||
|
- [Concatenate Strings with Groovy](https://www.baeldung.com/groovy-concatenate-strings)
|
||||||
|
|
|
@ -1,3 +1,5 @@
|
||||||
## Relevant Articles
|
## Relevant Articles
|
||||||
|
|
||||||
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
|
||||||
|
- [Checking If an Array Is Sorted in Java](https://www.baeldung.com/java-check-sorted-array)
|
||||||
|
- [Looping Diagonally Through a 2d Java Array](https://www.baeldung.com/java-loop-diagonal-array)
|
||||||
|
|
|
@ -0,0 +1,11 @@
|
||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
public class SequenceGenerator {
|
||||||
|
private int currentValue = 0;
|
||||||
|
|
||||||
|
public int getNextSequence() throws InterruptedException {
|
||||||
|
currentValue = currentValue + 1;
|
||||||
|
Thread.sleep(500);
|
||||||
|
return currentValue;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
import com.google.common.util.concurrent.Monitor;
|
||||||
|
|
||||||
|
public class SequenceGeneratorUsingMonitor extends SequenceGenerator {
|
||||||
|
|
||||||
|
private Monitor monitor = new Monitor();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getNextSequence() throws InterruptedException {
|
||||||
|
monitor.enter();
|
||||||
|
try {
|
||||||
|
return super.getNextSequence();
|
||||||
|
} finally {
|
||||||
|
monitor.leave();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
|
public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator {
|
||||||
|
|
||||||
|
private ReentrantLock mutex = new ReentrantLock();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getNextSequence() throws InterruptedException {
|
||||||
|
try {
|
||||||
|
mutex.lock();
|
||||||
|
return super.getNextSequence();
|
||||||
|
} finally {
|
||||||
|
mutex.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
|
|
||||||
|
public class SequenceGeneratorUsingSemaphore extends SequenceGenerator {
|
||||||
|
|
||||||
|
private Semaphore mutex = new Semaphore(1);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getNextSequence() throws InterruptedException {
|
||||||
|
try {
|
||||||
|
mutex.acquire();
|
||||||
|
return super.getNextSequence();
|
||||||
|
} finally {
|
||||||
|
mutex.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
public class SequenceGeneratorUsingSynchronizedBlock extends SequenceGenerator {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getNextSequence() throws InterruptedException {
|
||||||
|
synchronized (this) {
|
||||||
|
return super.getNextSequence();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,10 @@
|
||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
public class SequenceGeneratorUsingSynchronizedMethod extends SequenceGenerator {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized int getNextSequence() throws InterruptedException {
|
||||||
|
return super.getNextSequence();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,81 @@
|
||||||
|
package com.baeldung.concurrent.mutex;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.concurrent.mutex.SequenceGenerator;
|
||||||
|
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingMonitor;
|
||||||
|
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingReentrantLock;
|
||||||
|
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSemaphore;
|
||||||
|
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedBlock;
|
||||||
|
import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedMethod;
|
||||||
|
|
||||||
|
public class MutexUnitTest {
|
||||||
|
|
||||||
|
private final int RANGE = 30;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavior() throws Exception {
|
||||||
|
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGenerator());
|
||||||
|
Assert.assertNotEquals(RANGE, uniqueSequences.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSequenceGeneratorUsingSynchronizedMethod_whenRaceCondition_thenSuccess() throws Exception {
|
||||||
|
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedMethod());
|
||||||
|
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSequenceGeneratorUsingSynchronizedBlock_whenRaceCondition_thenSuccess() throws Exception {
|
||||||
|
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedBlock());
|
||||||
|
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSequenceGeneratorUsingReentrantLock_whenRaceCondition_thenSuccess() throws Exception {
|
||||||
|
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingReentrantLock());
|
||||||
|
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSequenceGeneratorUsingSemaphore_whenRaceCondition_thenSuccess() throws Exception {
|
||||||
|
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSemaphore());
|
||||||
|
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSequenceGeneratorUsingMonitor_whenRaceCondition_thenSuccess() throws Exception {
|
||||||
|
Set<Integer> uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingMonitor());
|
||||||
|
Assert.assertEquals(RANGE, uniqueSequences.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Set<Integer> getASetOFUniqueSequences(SequenceGenerator generator) throws Exception {
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(3);
|
||||||
|
Set<Integer> uniqueSequences = new HashSet<>();
|
||||||
|
List<Future<Integer>> futures = new ArrayList<>();
|
||||||
|
|
||||||
|
for (int i = 0; i < RANGE; i++) {
|
||||||
|
futures.add(executor.submit(generator::getNextSequence));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Future<Integer> future : futures) {
|
||||||
|
uniqueSequences.add(future.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
executor.awaitTermination(15, TimeUnit.SECONDS);
|
||||||
|
executor.shutdown();
|
||||||
|
|
||||||
|
return uniqueSequences;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,65 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<groupId>com.baeldung.jndi</groupId>
|
||||||
|
<artifactId>core-java-jndi</artifactId>
|
||||||
|
<version>1.0-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>../../</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<version>5.5.1</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-core</artifactId>
|
||||||
|
<version>5.0.9.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-context</artifactId>
|
||||||
|
<version>5.0.9.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-jdbc</artifactId>
|
||||||
|
<version>5.0.9.RELEASE</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-test</artifactId>
|
||||||
|
<version>5.0.9.RELEASE</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<version>1.4.199</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
|
@ -0,0 +1,60 @@
|
||||||
|
package com.baeldung.jndi;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeAll;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||||
|
import org.springframework.jndi.JndiTemplate;
|
||||||
|
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
|
||||||
|
|
||||||
|
import javax.naming.*;
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
import java.util.Enumeration;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class JndiUnitTest {
|
||||||
|
|
||||||
|
private static InitialContext ctx;
|
||||||
|
private static DriverManagerDataSource ds;
|
||||||
|
|
||||||
|
@BeforeAll
|
||||||
|
static void setUp() throws Exception {
|
||||||
|
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
|
||||||
|
ds = new DriverManagerDataSource("jdbc:h2:mem:mydb");
|
||||||
|
builder.activate();
|
||||||
|
|
||||||
|
JndiTemplate jndiTemplate = new JndiTemplate();
|
||||||
|
ctx = (InitialContext) jndiTemplate.getContext();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenACompositeName_whenAddingAnElement_thenNameIncludesIt() throws Exception {
|
||||||
|
Name objectName = new CompositeName("java:comp/env/jdbc");
|
||||||
|
|
||||||
|
Enumeration<String> elements = objectName.getAll();
|
||||||
|
while(elements.hasMoreElements()) {
|
||||||
|
System.out.println(elements.nextElement());
|
||||||
|
}
|
||||||
|
|
||||||
|
objectName.add("example");
|
||||||
|
|
||||||
|
assertEquals("env", objectName.get(1));
|
||||||
|
assertEquals("example", objectName.get(objectName.size() - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenADataSource_whenAddingDriver_thenBind() throws Exception {
|
||||||
|
ds.setDriverClassName("org.h2.Driver");
|
||||||
|
ctx.bind("java:comp/env/jdbc/datasource", ds);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenContext_whenLookupByName_thenValidDataSource() throws Exception {
|
||||||
|
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
|
||||||
|
|
||||||
|
assertNotNull(ds);
|
||||||
|
assertNotNull(ds.getConnection());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.jndi.exceptions;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.MethodOrderer;
|
||||||
|
import org.junit.jupiter.api.Order;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.TestMethodOrder;
|
||||||
|
import org.springframework.jndi.JndiTemplate;
|
||||||
|
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
|
||||||
|
|
||||||
|
import javax.naming.InitialContext;
|
||||||
|
import javax.naming.NameNotFoundException;
|
||||||
|
import javax.naming.NoInitialContextException;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||||
|
public class JndiExceptionsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Order(1)
|
||||||
|
void givenNoContext_whenLookupObject_thenThrowNoInitialContext() {
|
||||||
|
assertThrows(NoInitialContextException.class, () -> {
|
||||||
|
JndiTemplate jndiTemplate = new JndiTemplate();
|
||||||
|
InitialContext ctx = (InitialContext) jndiTemplate.getContext();
|
||||||
|
ctx.lookup("java:comp/env/jdbc/datasource");
|
||||||
|
}).printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Order(2)
|
||||||
|
void givenEmptyContext_whenLookupNotBounds_thenThrowNameNotFound() {
|
||||||
|
assertThrows(NameNotFoundException.class, () -> {
|
||||||
|
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
|
||||||
|
builder.activate();
|
||||||
|
|
||||||
|
JndiTemplate jndiTemplate = new JndiTemplate();
|
||||||
|
InitialContext ctx = (InitialContext) jndiTemplate.getContext();
|
||||||
|
ctx.lookup("badJndiName");
|
||||||
|
}).printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant Articles
|
||||||
|
|
||||||
|
- [Checking if a URL Exists in Java](https://www.baeldung.com/java-check-url-exists)
|
|
@ -7,4 +7,4 @@ This module uses Java 9, so make sure to have the JDK 9 installed to run it.
|
||||||
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
|
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
|
||||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||||
- [Guide to java.lang.ProcessBuilder API](https://www.baeldung.com/java-lang-processbuilder-api)
|
- [Guide to java.lang.ProcessBuilder API](https://www.baeldung.com/java-lang-processbuilder-api)
|
||||||
|
- [Get the Current Working Directory in Java](https://www.baeldung.com/java-current-directory)
|
||||||
|
|
|
@ -21,12 +21,12 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.security</groupId>
|
<groupId>org.springframework.security</groupId>
|
||||||
<artifactId>spring-security-web</artifactId>
|
<artifactId>spring-security-web</artifactId>
|
||||||
<version>${spring.version}</version>
|
<version>${spring-security.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.security</groupId>
|
<groupId>org.springframework.security</groupId>
|
||||||
<artifactId>spring-security-config</artifactId>
|
<artifactId>spring-security-config</artifactId>
|
||||||
<version>${spring.version}</version>
|
<version>${spring-security.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!-- Spring -->
|
<!-- Spring -->
|
||||||
|
|
|
@ -0,0 +1,130 @@
|
||||||
|
<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>java-jdi</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>java-jdi</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-java</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../parent-java</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>log4j</groupId>
|
||||||
|
<artifactId>log4j</artifactId>
|
||||||
|
<version>${log4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
<version>${org.slf4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-classic</artifactId>
|
||||||
|
<version>${logback.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-core</artifactId>
|
||||||
|
<version>${jmh-core.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
|
<version>${jmh-generator.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.sun</groupId>
|
||||||
|
<artifactId>tools</artifactId>
|
||||||
|
<version>${tools.version}</version>
|
||||||
|
<scope>system</scope>
|
||||||
|
<systemPath>${java.home}/../lib/tools.jar</systemPath>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>java-jdi</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
|
||||||
|
<plugins>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-javadoc-plugin</artifactId>
|
||||||
|
<version>${maven-javadoc-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<profile>
|
||||||
|
<id>integration</id>
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>integration-test</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>test</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<includes>
|
||||||
|
<include>**/*IntegrationTest.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<systemPropertyVariables>
|
||||||
|
<test.mime>json</test.mime>
|
||||||
|
</systemPropertyVariables>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
|
|
||||||
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
<tool.version>1.8</tool.version>
|
||||||
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
|
<logback.version>1.1.7</logback.version>
|
||||||
|
<tools.version>1.8</tools.version>
|
||||||
|
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||||
|
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||||
|
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
|
@ -0,0 +1,14 @@
|
||||||
|
package com.baeldung.jdi;
|
||||||
|
|
||||||
|
public class JDIExample {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String jpda = "Java Platform Debugger Architecture";
|
||||||
|
System.out.println("Hi Everyone, Welcome to " + jpda); //add a break point here
|
||||||
|
|
||||||
|
String jdi = "Java Debug Interface"; //add a break point here and also stepping in here
|
||||||
|
String text = "Today, we'll dive into " + jdi;
|
||||||
|
System.out.println(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,171 @@
|
||||||
|
package com.baeldung.jdi;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.io.OutputStreamWriter;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.sun.jdi.AbsentInformationException;
|
||||||
|
import com.sun.jdi.Bootstrap;
|
||||||
|
import com.sun.jdi.ClassType;
|
||||||
|
import com.sun.jdi.IncompatibleThreadStateException;
|
||||||
|
import com.sun.jdi.LocalVariable;
|
||||||
|
import com.sun.jdi.Location;
|
||||||
|
import com.sun.jdi.StackFrame;
|
||||||
|
import com.sun.jdi.VMDisconnectedException;
|
||||||
|
import com.sun.jdi.Value;
|
||||||
|
import com.sun.jdi.VirtualMachine;
|
||||||
|
import com.sun.jdi.connect.Connector;
|
||||||
|
import com.sun.jdi.connect.IllegalConnectorArgumentsException;
|
||||||
|
import com.sun.jdi.connect.LaunchingConnector;
|
||||||
|
import com.sun.jdi.connect.VMStartException;
|
||||||
|
import com.sun.jdi.event.BreakpointEvent;
|
||||||
|
import com.sun.jdi.event.ClassPrepareEvent;
|
||||||
|
import com.sun.jdi.event.Event;
|
||||||
|
import com.sun.jdi.event.EventSet;
|
||||||
|
import com.sun.jdi.event.LocatableEvent;
|
||||||
|
import com.sun.jdi.event.StepEvent;
|
||||||
|
import com.sun.jdi.request.BreakpointRequest;
|
||||||
|
import com.sun.jdi.request.ClassPrepareRequest;
|
||||||
|
import com.sun.jdi.request.StepRequest;
|
||||||
|
|
||||||
|
public class JDIExampleDebugger {
|
||||||
|
|
||||||
|
private Class debugClass;
|
||||||
|
private int[] breakPointLines;
|
||||||
|
|
||||||
|
public Class getDebugClass() {
|
||||||
|
return debugClass;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDebugClass(Class debugClass) {
|
||||||
|
this.debugClass = debugClass;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int[] getBreakPointLines() {
|
||||||
|
return breakPointLines;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBreakPointLines(int[] breakPointLines) {
|
||||||
|
this.breakPointLines = breakPointLines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the debug class as the main argument in the connector and launches the VM
|
||||||
|
* @return VirtualMachine
|
||||||
|
* @throws IOException
|
||||||
|
* @throws IllegalConnectorArgumentsException
|
||||||
|
* @throws VMStartException
|
||||||
|
*/
|
||||||
|
public VirtualMachine connectAndLaunchVM() throws IOException, IllegalConnectorArgumentsException, VMStartException {
|
||||||
|
LaunchingConnector launchingConnector = Bootstrap.virtualMachineManager().defaultConnector();
|
||||||
|
Map<String, Connector.Argument> arguments = launchingConnector.defaultArguments();
|
||||||
|
arguments.get("main").setValue(debugClass.getName());
|
||||||
|
VirtualMachine vm = launchingConnector.launch(arguments);
|
||||||
|
return vm;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a request to prepare the debug class, add filter as the debug class and enables it
|
||||||
|
* @param vm
|
||||||
|
*/
|
||||||
|
public void enableClassPrepareRequest(VirtualMachine vm) {
|
||||||
|
ClassPrepareRequest classPrepareRequest = vm.eventRequestManager().createClassPrepareRequest();
|
||||||
|
classPrepareRequest.addClassFilter(debugClass.getName());
|
||||||
|
classPrepareRequest.enable();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the break points at the line numbers mentioned in breakPointLines array
|
||||||
|
* @param vm
|
||||||
|
* @param event
|
||||||
|
* @throws AbsentInformationException
|
||||||
|
*/
|
||||||
|
public void setBreakPoints(VirtualMachine vm, ClassPrepareEvent event) throws AbsentInformationException {
|
||||||
|
ClassType classType = (ClassType) event.referenceType();
|
||||||
|
for(int lineNumber: breakPointLines) {
|
||||||
|
Location location = classType.locationsOfLine(lineNumber).get(0);
|
||||||
|
BreakpointRequest bpReq = vm.eventRequestManager().createBreakpointRequest(location);
|
||||||
|
bpReq.enable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays the visible variables
|
||||||
|
* @param event
|
||||||
|
* @throws IncompatibleThreadStateException
|
||||||
|
* @throws AbsentInformationException
|
||||||
|
*/
|
||||||
|
public void displayVariables(LocatableEvent event) throws IncompatibleThreadStateException, AbsentInformationException {
|
||||||
|
StackFrame stackFrame = event.thread().frame(0);
|
||||||
|
if(stackFrame.location().toString().contains(debugClass.getName())) {
|
||||||
|
Map<LocalVariable, Value> visibleVariables = stackFrame.getValues(stackFrame.visibleVariables());
|
||||||
|
System.out.println("Variables at " +stackFrame.location().toString() + " > ");
|
||||||
|
for (Map.Entry<LocalVariable, Value> entry : visibleVariables.entrySet()) {
|
||||||
|
System.out.println(entry.getKey().name() + " = " + entry.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enables step request for a break point
|
||||||
|
* @param vm
|
||||||
|
* @param event
|
||||||
|
*/
|
||||||
|
public void enableStepRequest(VirtualMachine vm, BreakpointEvent event) {
|
||||||
|
//enable step request for last break point
|
||||||
|
if(event.location().toString().contains(debugClass.getName()+":"+breakPointLines[breakPointLines.length-1])) {
|
||||||
|
StepRequest stepRequest = vm.eventRequestManager().createStepRequest(event.thread(), StepRequest.STEP_LINE, StepRequest.STEP_OVER);
|
||||||
|
stepRequest.enable();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
|
JDIExampleDebugger debuggerInstance = new JDIExampleDebugger();
|
||||||
|
debuggerInstance.setDebugClass(JDIExample.class);
|
||||||
|
int[] breakPoints = {6, 9};
|
||||||
|
debuggerInstance.setBreakPointLines(breakPoints);
|
||||||
|
VirtualMachine vm = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
vm = debuggerInstance.connectAndLaunchVM();
|
||||||
|
debuggerInstance.enableClassPrepareRequest(vm);
|
||||||
|
|
||||||
|
EventSet eventSet = null;
|
||||||
|
while ((eventSet = vm.eventQueue().remove()) != null) {
|
||||||
|
for (Event event : eventSet) {
|
||||||
|
if (event instanceof ClassPrepareEvent) {
|
||||||
|
debuggerInstance.setBreakPoints(vm, (ClassPrepareEvent)event);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event instanceof BreakpointEvent) {
|
||||||
|
event.request().disable();
|
||||||
|
debuggerInstance.displayVariables((BreakpointEvent) event);
|
||||||
|
debuggerInstance.enableStepRequest(vm, (BreakpointEvent)event);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event instanceof StepEvent) {
|
||||||
|
debuggerInstance.displayVariables((StepEvent) event);
|
||||||
|
}
|
||||||
|
vm.resume();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (VMDisconnectedException e) {
|
||||||
|
System.out.println("Virtual Machine is disconnected.");
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
InputStreamReader reader = new InputStreamReader(vm.process().getInputStream());
|
||||||
|
OutputStreamWriter writer = new OutputStreamWriter(System.out);
|
||||||
|
char[] buf = new char[512];
|
||||||
|
|
||||||
|
reader.read(buf);
|
||||||
|
writer.write(buf);
|
||||||
|
writer.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
package com.baeldung.matrices;
|
||||||
|
|
||||||
|
public class HomemadeMatrix {
|
||||||
|
public static double[][] multiplyMatrices(double[][] firstMatrix, double[][] secondMatrix) {
|
||||||
|
double[][] result = new double[firstMatrix.length][secondMatrix[0].length];
|
||||||
|
|
||||||
|
for (int row = 0; row < result.length; row++) {
|
||||||
|
for (int col = 0; col < result[row].length; col++) {
|
||||||
|
result[row][col] = multiplyMatricesCell(firstMatrix, secondMatrix, row, col);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double multiplyMatricesCell(double[][] firstMatrix, double[][] secondMatrix, int row, int col) {
|
||||||
|
double cell = 0;
|
||||||
|
for (int i = 0; i < secondMatrix.length; i++) {
|
||||||
|
cell += firstMatrix[row][i] * secondMatrix[i][col];
|
||||||
|
}
|
||||||
|
return cell;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.algorithms.logarithm;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class LogarithmUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLog10_shouldReturnValidResults() {
|
||||||
|
assertEquals(Math.log10(100), 2);
|
||||||
|
assertEquals(Math.log10(1000), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenLogE_shouldReturnValidResults() {
|
||||||
|
assertEquals(Math.log(Math.E), 1);
|
||||||
|
assertEquals(Math.log(10), 2.30258, 0.00001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCustomLog_shouldReturnValidResults() {
|
||||||
|
assertEquals(customLog(2, 256), 8);
|
||||||
|
assertEquals(customLog(10, 100), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double customLog(double base, double logNumber) {
|
||||||
|
return Math.log(logNumber) / Math.log(base);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -1,9 +1,84 @@
|
||||||
package com.baeldung.matrices;
|
package com.baeldung.matrices;
|
||||||
|
|
||||||
|
import cern.colt.matrix.DoubleFactory2D;
|
||||||
|
import cern.colt.matrix.DoubleMatrix2D;
|
||||||
|
import cern.colt.matrix.linalg.Algebra;
|
||||||
|
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
|
||||||
|
import org.apache.commons.math3.linear.RealMatrix;
|
||||||
|
import org.ejml.simple.SimpleMatrix;
|
||||||
|
import org.la4j.Matrix;
|
||||||
|
import org.la4j.matrix.dense.Basic2DMatrix;
|
||||||
|
import org.nd4j.linalg.api.ndarray.INDArray;
|
||||||
|
import org.nd4j.linalg.factory.Nd4j;
|
||||||
|
import org.openjdk.jmh.annotations.Benchmark;
|
||||||
|
import org.openjdk.jmh.annotations.Mode;
|
||||||
|
import org.openjdk.jmh.runner.Runner;
|
||||||
|
import org.openjdk.jmh.runner.options.Options;
|
||||||
|
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||||
|
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
public class MatrixMultiplicationBenchmarking {
|
public class MatrixMultiplicationBenchmarking {
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
org.openjdk.jmh.Main.main(args);
|
Options opt = new OptionsBuilder()
|
||||||
|
.include(MatrixMultiplicationBenchmarking.class.getSimpleName())
|
||||||
|
.mode(Mode.AverageTime)
|
||||||
|
.forks(2)
|
||||||
|
.warmupIterations(5)
|
||||||
|
.measurementIterations(10)
|
||||||
|
.timeUnit(TimeUnit.MICROSECONDS)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
new Runner(opt).run();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
@Benchmark
|
||||||
|
public Object homemadeMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||||
|
return HomemadeMatrix.multiplyMatrices(matrixProvider.getFirstMatrix(), matrixProvider.getSecondMatrix());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public Object ejmlMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||||
|
SimpleMatrix firstMatrix = new SimpleMatrix(matrixProvider.getFirstMatrix());
|
||||||
|
SimpleMatrix secondMatrix = new SimpleMatrix(matrixProvider.getSecondMatrix());
|
||||||
|
|
||||||
|
return firstMatrix.mult(secondMatrix);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public Object apacheCommonsMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||||
|
RealMatrix firstMatrix = new Array2DRowRealMatrix(matrixProvider.getFirstMatrix());
|
||||||
|
RealMatrix secondMatrix = new Array2DRowRealMatrix(matrixProvider.getSecondMatrix());
|
||||||
|
|
||||||
|
return firstMatrix.multiply(secondMatrix);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public Object la4jMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||||
|
Matrix firstMatrix = new Basic2DMatrix(matrixProvider.getFirstMatrix());
|
||||||
|
Matrix secondMatrix = new Basic2DMatrix(matrixProvider.getSecondMatrix());
|
||||||
|
|
||||||
|
return firstMatrix.multiply(secondMatrix);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public Object nd4jMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||||
|
INDArray firstMatrix = Nd4j.create(matrixProvider.getFirstMatrix());
|
||||||
|
INDArray secondMatrix = Nd4j.create(matrixProvider.getSecondMatrix());
|
||||||
|
|
||||||
|
return firstMatrix.mmul(secondMatrix);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public Object coltMatrixMultiplication(MatrixProvider matrixProvider) {
|
||||||
|
DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense;
|
||||||
|
|
||||||
|
DoubleMatrix2D firstMatrix = doubleFactory2D.make(matrixProvider.getFirstMatrix());
|
||||||
|
DoubleMatrix2D secondMatrix = doubleFactory2D.make(matrixProvider.getSecondMatrix());
|
||||||
|
|
||||||
|
Algebra algebra = new Algebra();
|
||||||
|
return algebra.mult(firstMatrix, secondMatrix);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
package com.baeldung.matrices;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.Scope;
|
||||||
|
import org.openjdk.jmh.annotations.State;
|
||||||
|
|
||||||
|
@State(Scope.Benchmark)
|
||||||
|
public class MatrixProvider {
|
||||||
|
private double[][] firstMatrix;
|
||||||
|
private double[][] secondMatrix;
|
||||||
|
|
||||||
|
public MatrixProvider() {
|
||||||
|
firstMatrix =
|
||||||
|
new double[][] {
|
||||||
|
new double[] {1d, 5d},
|
||||||
|
new double[] {2d, 3d},
|
||||||
|
new double[] {1d ,7d}
|
||||||
|
};
|
||||||
|
|
||||||
|
secondMatrix =
|
||||||
|
new double[][] {
|
||||||
|
new double[] {1d, 2d, 3d, 7d},
|
||||||
|
new double[] {5d, 2d, 8d, 1d}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public double[][] getFirstMatrix() {
|
||||||
|
return firstMatrix;
|
||||||
|
}
|
||||||
|
|
||||||
|
public double[][] getSecondMatrix() {
|
||||||
|
return secondMatrix;
|
||||||
|
}
|
||||||
|
}
|
|
@ -7,15 +7,10 @@ import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
@BenchmarkMode(Mode.AverageTime)
|
class RealMatrixUnitTest {
|
||||||
@Fork(value = 2)
|
|
||||||
@Warmup(iterations = 5)
|
|
||||||
@Measurement(iterations = 10)
|
|
||||||
public class RealMatrixUnitTest {
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Benchmark
|
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
|
||||||
RealMatrix firstMatrix = new Array2DRowRealMatrix(
|
RealMatrix firstMatrix = new Array2DRowRealMatrix(
|
||||||
new double[][] {
|
new double[][] {
|
||||||
new double[] {1d, 5d},
|
new double[] {1d, 5d},
|
||||||
|
@ -43,5 +38,4 @@ public class RealMatrixUnitTest {
|
||||||
|
|
||||||
assertThat(actual).isEqualTo(expected);
|
assertThat(actual).isEqualTo(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,15 +8,10 @@ import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
@BenchmarkMode(Mode.AverageTime)
|
class DoubleMatrix2DUnitTest {
|
||||||
@Fork(value = 2)
|
|
||||||
@Warmup(iterations = 5)
|
|
||||||
@Measurement(iterations = 10)
|
|
||||||
public class DoubleMatrix2DUnitTest {
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Benchmark
|
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
|
||||||
DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense;
|
DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense;
|
||||||
|
|
||||||
DoubleMatrix2D firstMatrix = doubleFactory2D.make(
|
DoubleMatrix2D firstMatrix = doubleFactory2D.make(
|
||||||
|
@ -48,4 +43,4 @@ public class DoubleMatrix2DUnitTest {
|
||||||
assertThat(actual).isEqualTo(expected);
|
assertThat(actual).isEqualTo(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -6,15 +6,10 @@ import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
@BenchmarkMode(Mode.AverageTime)
|
class SimpleMatrixUnitTest {
|
||||||
@Fork(value = 2)
|
|
||||||
@Warmup(iterations = 5)
|
|
||||||
@Measurement(iterations = 10)
|
|
||||||
public class SimpleMatrixUnitTest {
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Benchmark
|
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
|
||||||
SimpleMatrix firstMatrix = new SimpleMatrix(
|
SimpleMatrix firstMatrix = new SimpleMatrix(
|
||||||
new double[][] {
|
new double[][] {
|
||||||
new double[] {1d, 5d},
|
new double[] {1d, 5d},
|
||||||
|
@ -43,4 +38,4 @@ public class SimpleMatrixUnitTest {
|
||||||
assertThat(actual).matches(m -> m.isIdentical(expected, 0d));
|
assertThat(actual).matches(m -> m.isIdentical(expected, 0d));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -5,15 +5,10 @@ import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
@BenchmarkMode(Mode.AverageTime)
|
class HomemadeMatrixUnitTest {
|
||||||
@Fork(value = 2)
|
|
||||||
@Warmup(iterations = 5)
|
|
||||||
@Measurement(iterations = 10)
|
|
||||||
public class HomemadeMatrixUnitTest {
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Benchmark
|
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
|
||||||
double[][] firstMatrix = {
|
double[][] firstMatrix = {
|
||||||
new double[]{1d, 5d},
|
new double[]{1d, 5d},
|
||||||
new double[]{2d, 3d},
|
new double[]{2d, 3d},
|
||||||
|
@ -55,4 +50,5 @@ public class HomemadeMatrixUnitTest {
|
||||||
}
|
}
|
||||||
return cell;
|
return cell;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
}
|
|
@ -7,15 +7,10 @@ import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
@BenchmarkMode(Mode.AverageTime)
|
class Basic2DMatrixUnitTest {
|
||||||
@Fork(value = 2)
|
|
||||||
@Warmup(iterations = 5)
|
|
||||||
@Measurement(iterations = 10)
|
|
||||||
public class Basic2DMatrixUnitTest {
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Benchmark
|
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
|
||||||
Matrix firstMatrix = new Basic2DMatrix(
|
Matrix firstMatrix = new Basic2DMatrix(
|
||||||
new double[][]{
|
new double[][]{
|
||||||
new double[]{1d, 5d},
|
new double[]{1d, 5d},
|
||||||
|
@ -44,4 +39,4 @@ public class Basic2DMatrixUnitTest {
|
||||||
assertThat(actual).isEqualTo(expected);
|
assertThat(actual).isEqualTo(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -7,14 +7,10 @@ import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
@BenchmarkMode(Mode.AverageTime)
|
class INDArrayUnitTest {
|
||||||
@Fork(value = 2)
|
|
||||||
@Warmup(iterations = 5)
|
|
||||||
@Measurement(iterations = 10)
|
|
||||||
public class INDArrayUnitTest {
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
void givenTwoMatrices_whenMultiply_thenMultiplicatedMatrix() {
|
||||||
INDArray firstMatrix = Nd4j.create(
|
INDArray firstMatrix = Nd4j.create(
|
||||||
new double[][]{
|
new double[][]{
|
||||||
new double[]{1d, 5d},
|
new double[]{1d, 5d},
|
||||||
|
@ -43,4 +39,4 @@ public class INDArrayUnitTest {
|
||||||
assertThat(actual).isEqualTo(expected);
|
assertThat(actual).isEqualTo(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -0,0 +1,2 @@
|
||||||
|
## Relevant Articles
|
||||||
|
- [Lossy Conversion in Java](https://www.baeldung.com/java-lossy-conversion)
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.lcm;
|
||||||
|
|
||||||
|
import java.math.BigInteger;
|
||||||
|
|
||||||
|
public class BigIntegerLCM {
|
||||||
|
|
||||||
|
public static BigInteger lcm(BigInteger number1, BigInteger number2) {
|
||||||
|
BigInteger gcd = number1.gcd(number2);
|
||||||
|
BigInteger absProduct = number1.multiply(number2).abs();
|
||||||
|
return absProduct.divide(gcd);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,40 @@
|
||||||
|
package com.baeldung.lcm;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class EuclideanAlgorithm {
|
||||||
|
|
||||||
|
public static int gcd(int number1, int number2) {
|
||||||
|
if (number1 == 0 || number2 == 0) {
|
||||||
|
return number1 + number2;
|
||||||
|
} else {
|
||||||
|
int absNumber1 = Math.abs(number1);
|
||||||
|
int absNumber2 = Math.abs(number2);
|
||||||
|
int biggerValue = Math.max(absNumber1, absNumber2);
|
||||||
|
int smallerValue = Math.min(absNumber1, absNumber2);
|
||||||
|
return gcd(biggerValue % smallerValue, smallerValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int lcm(int number1, int number2) {
|
||||||
|
if (number1 == 0 || number2 == 0)
|
||||||
|
return 0;
|
||||||
|
else {
|
||||||
|
int gcd = gcd(number1, number2);
|
||||||
|
return Math.abs(number1 * number2) / gcd;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int lcmForArray(int[] numbers) {
|
||||||
|
int lcm = numbers[0];
|
||||||
|
for (int i = 1; i <= numbers.length - 1; i++) {
|
||||||
|
lcm = lcm(lcm, numbers[i]);
|
||||||
|
}
|
||||||
|
return lcm;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int lcmByLambda(int... numbers) {
|
||||||
|
return Arrays.stream(numbers).reduce(1, (lcmSoFar, currentNumber) -> Math.abs(lcmSoFar * currentNumber) / gcd(lcmSoFar, currentNumber));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,42 @@
|
||||||
|
package com.baeldung.lcm;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public class PrimeFactorizationAlgorithm {
|
||||||
|
|
||||||
|
public static Map<Integer, Integer> getPrimeFactors(int number) {
|
||||||
|
int absNumber = Math.abs(number);
|
||||||
|
Map<Integer, Integer> primeFactorsMap = new HashMap<Integer, Integer>();
|
||||||
|
for (int factor = 2; factor <= absNumber; factor++) {
|
||||||
|
while (absNumber % factor == 0) {
|
||||||
|
Integer power = primeFactorsMap.get(factor);
|
||||||
|
if (power == null) {
|
||||||
|
power = 0;
|
||||||
|
}
|
||||||
|
primeFactorsMap.put(factor, power + 1);
|
||||||
|
absNumber /= factor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return primeFactorsMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int lcm(int number1, int number2) {
|
||||||
|
if (number1 == 0 || number2 == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
Map<Integer, Integer> primeFactorsForNum1 = getPrimeFactors(number1);
|
||||||
|
Map<Integer, Integer> primeFactorsForNum2 = getPrimeFactors(number2);
|
||||||
|
Set<Integer> primeFactorsUnionSet = new HashSet<Integer>(primeFactorsForNum1.keySet());
|
||||||
|
primeFactorsUnionSet.addAll(primeFactorsForNum2.keySet());
|
||||||
|
int lcm = 1;
|
||||||
|
for (Integer primeFactor : primeFactorsUnionSet) {
|
||||||
|
lcm *= Math.pow(primeFactor, Math.max(primeFactorsForNum1.getOrDefault(primeFactor, 0),
|
||||||
|
primeFactorsForNum2.getOrDefault(primeFactor, 0)));
|
||||||
|
}
|
||||||
|
return lcm;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.lcm;
|
||||||
|
|
||||||
|
public class SimpleAlgorithm {
|
||||||
|
public static int lcm(int number1, int number2) {
|
||||||
|
if (number1 == 0 || number2 == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int absNumber1 = Math.abs(number1);
|
||||||
|
int absNumber2 = Math.abs(number2);
|
||||||
|
int absHigherNumber = Math.max(absNumber1, absNumber2);
|
||||||
|
int absLowerNumber = Math.min(absNumber1, absNumber2);
|
||||||
|
int lcm = absHigherNumber;
|
||||||
|
while (lcm % absLowerNumber != 0) {
|
||||||
|
lcm += absHigherNumber;
|
||||||
|
}
|
||||||
|
return lcm;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.lcm;
|
||||||
|
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.math.BigInteger;
|
||||||
|
|
||||||
|
public class BigIntegerLCMUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testLCM() {
|
||||||
|
BigInteger number1 = new BigInteger("12");
|
||||||
|
BigInteger number2 = new BigInteger("18");
|
||||||
|
BigInteger expectedLCM = new BigInteger("36");
|
||||||
|
Assert.assertEquals(expectedLCM, BigIntegerLCM.lcm(number1, number2));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.lcm;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class EuclideanAlgorithmUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGCD() {
|
||||||
|
Assert.assertEquals(6, EuclideanAlgorithm.gcd(12, 18));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testLCM() {
|
||||||
|
Assert.assertEquals(36, EuclideanAlgorithm.lcm(12, 18));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testLCMForArray() {
|
||||||
|
Assert.assertEquals(15, EuclideanAlgorithm.lcmForArray(new int[]{3, 5, 15}));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testLCMByLambdaForArray() {
|
||||||
|
Assert.assertEquals(15, EuclideanAlgorithm.lcmByLambda(new int[]{3, 5, 15}));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,30 @@
|
||||||
|
package com.baeldung.lcm;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static com.baeldung.lcm.PrimeFactorizationAlgorithm.*;
|
||||||
|
|
||||||
|
|
||||||
|
public class PrimeFactorizationAlgorithmUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGetPrimeFactors() {
|
||||||
|
Map<Integer, Integer> expectedPrimeFactorsMapForTwelve = new HashMap<>();
|
||||||
|
expectedPrimeFactorsMapForTwelve.put(2, 2);
|
||||||
|
expectedPrimeFactorsMapForTwelve.put(3, 1);
|
||||||
|
Map<Integer, Integer> expectedPrimeFactorsMapForEighteen = new HashMap<>();
|
||||||
|
expectedPrimeFactorsMapForEighteen.put(2, 1);
|
||||||
|
expectedPrimeFactorsMapForEighteen.put(3, 2);
|
||||||
|
Assert.assertEquals(expectedPrimeFactorsMapForTwelve, getPrimeFactors(12));
|
||||||
|
Assert.assertEquals(expectedPrimeFactorsMapForEighteen, getPrimeFactors(18));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testLCM() {
|
||||||
|
Assert.assertEquals(36, PrimeFactorizationAlgorithm.lcm(12, 18));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
package com.baeldung.lcm;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static com.baeldung.lcm.SimpleAlgorithm.*;
|
||||||
|
|
||||||
|
public class SimpleAlgorithmUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testLCM() {
|
||||||
|
Assert.assertEquals(36, lcm(12, 18));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -23,3 +23,4 @@
|
||||||
- [Java Multi-line String](https://www.baeldung.com/java-multiline-string)
|
- [Java Multi-line String](https://www.baeldung.com/java-multiline-string)
|
||||||
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
|
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
|
||||||
- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string)
|
- [How to Reverse a String in Java](https://www.baeldung.com/java-reverse-string)
|
||||||
|
- [String toLowerCase and toUpperCase Methods in Java](https://www.baeldung.com/java-string-convert-case)
|
||||||
|
|
|
@ -1 +1,2 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
|
- [Java EE Application with Kotlin](https://www.baeldung.com/java-ee-kotlin-app)
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
### Relevant Articles
|
### Relevant Articles
|
||||||
|
|
||||||
- [Introduction to Quasar in Kotlin](https://www.baeldung.com/kotlin-quasar)
|
- [Introduction to Quasar in Kotlin](https://www.baeldung.com/kotlin-quasar)
|
||||||
|
- [Advanced Quasar Usage for Kotlin](https://www.baeldung.com/kotlin-quasar-advanced)
|
||||||
|
|
|
@ -0,0 +1,5 @@
|
||||||
|
### Relevant articles
|
||||||
|
- [Parsing YAML with SnakeYAML](http://www.baeldung.com/java-snake-yaml)
|
||||||
|
- [Guide to JMapper](https://www.baeldung.com/jmapper)
|
||||||
|
- [An Introduction to SuanShu](https://www.baeldung.com/suanshu)
|
||||||
|
- [Intro to Derive4J](https://www.baeldung.com/derive4j)
|
|
@ -0,0 +1 @@
|
||||||
|
log4j.rootLogger=INFO, stdout
|
|
@ -0,0 +1,55 @@
|
||||||
|
<?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>libraries-data-3</artifactId>
|
||||||
|
<name>libraries-data-3</name>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.yaml</groupId>
|
||||||
|
<artifactId>snakeyaml</artifactId>
|
||||||
|
<version>${snakeyaml.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.googlecode.jmapper-framework</groupId>
|
||||||
|
<artifactId>jmapper-core</artifactId>
|
||||||
|
<version>${jmapper.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.numericalmethod</groupId>
|
||||||
|
<artifactId>suanshu</artifactId>
|
||||||
|
<version>${suanshu.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.derive4j</groupId>
|
||||||
|
<artifactId>derive4j</artifactId>
|
||||||
|
<version>${derive4j.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<repositories>
|
||||||
|
<repository>
|
||||||
|
<id>nm-repo</id>
|
||||||
|
<name>Numerical Method's Maven Repository</name>
|
||||||
|
<url>http://repo.numericalmethod.com/maven/</url>
|
||||||
|
<layout>default</layout>
|
||||||
|
</repository>
|
||||||
|
</repositories>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<snakeyaml.version>1.21</snakeyaml.version>
|
||||||
|
<jmapper.version>1.6.0.1</jmapper.version>
|
||||||
|
<suanshu.version>4.0.0</suanshu.version>
|
||||||
|
<derive4j.version>1.1.0</derive4j.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
|
@ -0,0 +1,10 @@
|
||||||
|
<jmapper>
|
||||||
|
<class name="com.baeldung.jmapper.UserDto">
|
||||||
|
<attribute name="id">
|
||||||
|
<value name="id"/>
|
||||||
|
</attribute>
|
||||||
|
<attribute name="username">
|
||||||
|
<value name="email"/>
|
||||||
|
</attribute>
|
||||||
|
</class>
|
||||||
|
</jmapper>
|
|
@ -0,0 +1,5 @@
|
||||||
|
<jmapper>
|
||||||
|
<class name="com.baeldung.jmapper.UserDto1">
|
||||||
|
<global/>
|
||||||
|
</class>
|
||||||
|
</jmapper>
|
|
@ -0,0 +1,21 @@
|
||||||
|
<jmapper>
|
||||||
|
<class name="com.baeldung.jmapper.relational.User">
|
||||||
|
<attribute name="id">
|
||||||
|
<value name="id"/>
|
||||||
|
<classes>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto1"/>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto2"/>
|
||||||
|
</classes>
|
||||||
|
</attribute>
|
||||||
|
<attribute name="email">
|
||||||
|
<attributes>
|
||||||
|
<attribute name="username"/>
|
||||||
|
<attribute name="email"/>
|
||||||
|
</attributes>
|
||||||
|
<classes>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto1"/>
|
||||||
|
<class name="com.baeldung.jmapper.relational.UserDto2"/>
|
||||||
|
</classes>
|
||||||
|
</attribute>
|
||||||
|
</class>
|
||||||
|
</jmapper>
|
|
@ -0,0 +1,3 @@
|
||||||
|
firstName: "John"
|
||||||
|
lastName: "Doe"
|
||||||
|
age: 20
|
|
@ -0,0 +1,7 @@
|
||||||
|
firstName: "John"
|
||||||
|
lastName: "Doe"
|
||||||
|
age: 31
|
||||||
|
contactDetails:
|
||||||
|
- { type: "mobile", number: 123456789}
|
||||||
|
- { type: "landline", number: 456786868}
|
||||||
|
|
|
@ -0,0 +1,13 @@
|
||||||
|
firstName: "John"
|
||||||
|
lastName: "Doe"
|
||||||
|
age: 31
|
||||||
|
contactDetails:
|
||||||
|
- type: "mobile"
|
||||||
|
number: 123456789
|
||||||
|
- type: "landline"
|
||||||
|
number: 456786868
|
||||||
|
homeAddress:
|
||||||
|
line: "Xyz, DEF Street"
|
||||||
|
city: "City Y"
|
||||||
|
state: "State Y"
|
||||||
|
zip: 345657
|
|
@ -0,0 +1,6 @@
|
||||||
|
firstName: "John"
|
||||||
|
lastName: "Doe"
|
||||||
|
age: 31
|
||||||
|
contactDetails:
|
||||||
|
- !contact { type: "mobile", number: 123456789}
|
||||||
|
- !contact { type: "landline", number: 456786868}
|
|
@ -0,0 +1,4 @@
|
||||||
|
!!com.baeldung.snakeyaml.Customer
|
||||||
|
firstName: "John"
|
||||||
|
lastName: "Doe"
|
||||||
|
age: 20
|
|
@ -0,0 +1,8 @@
|
||||||
|
---
|
||||||
|
firstName: "John"
|
||||||
|
lastName: "Doe"
|
||||||
|
age: 20
|
||||||
|
---
|
||||||
|
firstName: "Jack"
|
||||||
|
lastName: "Jones"
|
||||||
|
age: 25
|
|
@ -9,7 +9,6 @@
|
||||||
- [Introduction to JCache](http://www.baeldung.com/jcache)
|
- [Introduction to JCache](http://www.baeldung.com/jcache)
|
||||||
- [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite)
|
- [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite)
|
||||||
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)
|
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)
|
||||||
- [Guide to JMapper](https://www.baeldung.com/jmapper)
|
|
||||||
- [A Guide to Apache Crunch](https://www.baeldung.com/apache-crunch)
|
- [A Guide to Apache Crunch](https://www.baeldung.com/apache-crunch)
|
||||||
- [Intro to Apache Storm](https://www.baeldung.com/apache-storm)
|
- [Intro to Apache Storm](https://www.baeldung.com/apache-storm)
|
||||||
- [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm)
|
- [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm)
|
||||||
|
|
|
@ -141,12 +141,7 @@
|
||||||
<artifactId>hazelcast</artifactId>
|
<artifactId>hazelcast</artifactId>
|
||||||
<version>${hazelcast.version}</version>
|
<version>${hazelcast.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.googlecode.jmapper-framework</groupId>
|
|
||||||
<artifactId>jmapper-core</artifactId>
|
|
||||||
<version>${jmapper.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<!-- crunch project -->
|
<!-- crunch project -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.crunch</groupId>
|
<groupId>org.apache.crunch</groupId>
|
||||||
|
@ -460,7 +455,6 @@
|
||||||
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
|
<datanucleus-maven-plugin.version>5.0.2</datanucleus-maven-plugin.version>
|
||||||
<datanucleus-xml.version>5.0.0-release</datanucleus-xml.version>
|
<datanucleus-xml.version>5.0.0-release</datanucleus-xml.version>
|
||||||
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
|
<datanucleus-jdo-query.version>5.0.4</datanucleus-jdo-query.version>
|
||||||
<jmapper.version>1.6.0.1</jmapper.version>
|
|
||||||
<org.apache.crunch.crunch-core.version>0.15.0</org.apache.crunch.crunch-core.version>
|
<org.apache.crunch.crunch-core.version>0.15.0</org.apache.crunch.crunch-core.version>
|
||||||
<org.apache.hadoop.hadoop-client>2.2.0</org.apache.hadoop.hadoop-client>
|
<org.apache.hadoop.hadoop-client>2.2.0</org.apache.hadoop.hadoop-client>
|
||||||
<ebean.version>11.22.4</ebean.version>
|
<ebean.version>11.22.4</ebean.version>
|
||||||
|
|
|
@ -5,3 +5,7 @@
|
||||||
- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client)
|
- [A Guide to Google-Http-Client](http://www.baeldung.com/google-http-client)
|
||||||
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
|
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
|
||||||
- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets)
|
- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets)
|
||||||
|
- [Integrating Retrofit with RxJava](http://www.baeldung.com/retrofit-rxjava)
|
||||||
|
- [Introduction to Retrofit](http://www.baeldung.com/retrofit)
|
||||||
|
- [A Guide to Unirest](http://www.baeldung.com/unirest)
|
||||||
|
- [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices)
|
|
@ -44,6 +44,23 @@
|
||||||
<version>${googleclient.version}</version>
|
<version>${googleclient.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Retrofit -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.retrofit2</groupId>
|
||||||
|
<artifactId>retrofit</artifactId>
|
||||||
|
<version>${retrofit.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.retrofit2</groupId>
|
||||||
|
<artifactId>converter-gson</artifactId>
|
||||||
|
<version>${retrofit.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.retrofit2</groupId>
|
||||||
|
<artifactId>adapter-rxjava</artifactId>
|
||||||
|
<version>${retrofit.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
|
<!-- https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.asynchttpclient</groupId>
|
<groupId>org.asynchttpclient</groupId>
|
||||||
|
@ -69,13 +86,52 @@
|
||||||
<version>${com.squareup.okhttp3.version}</version>
|
<version>${com.squareup.okhttp3.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.mashape.unirest</groupId>
|
||||||
|
<artifactId>unirest-java</artifactId>
|
||||||
|
<version>${unirest.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- javalin -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.javalin</groupId>
|
||||||
|
<artifactId>javalin</artifactId>
|
||||||
|
<version>${javalin.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.squareup.okhttp3</groupId>
|
||||||
|
<artifactId>logging-interceptor</artifactId>
|
||||||
|
<version>${logging-interceptor.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
<version>${jackson.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.httpcomponents</groupId>
|
||||||
|
<artifactId>httpclient</artifactId>
|
||||||
|
<version>${httpclient.version}</version>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<artifactId>commons-logging</artifactId>
|
||||||
|
<groupId>commons-logging</groupId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
<httpclient.version>4.5.3</httpclient.version>
|
||||||
|
<jackson.version>2.9.8</jackson.version>
|
||||||
<assertj.version>3.6.2</assertj.version>
|
<assertj.version>3.6.2</assertj.version>
|
||||||
<com.squareup.okhttp3.version>3.14.2</com.squareup.okhttp3.version>
|
<com.squareup.okhttp3.version>3.14.2</com.squareup.okhttp3.version>
|
||||||
<googleclient.version>1.23.0</googleclient.version>
|
<googleclient.version>1.23.0</googleclient.version>
|
||||||
<async.http.client.version>2.2.0</async.http.client.version>
|
<async.http.client.version>2.2.0</async.http.client.version>
|
||||||
|
<retrofit.version>2.3.0</retrofit.version>
|
||||||
|
<unirest.version>1.4.9</unirest.version>
|
||||||
|
<javalin.version>1.6.0</javalin.version>
|
||||||
|
<logging-interceptor.version>3.9.0</logging-interceptor.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue