Merge pull request #50 from eugenp/master

update
This commit is contained in:
Maiklins 2020-05-01 21:45:17 +02:00 committed by GitHub
commit 524962d3da
39 changed files with 509 additions and 147 deletions

View File

@ -15,9 +15,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
- [Maximum Subarray Problem](https://www.baeldung.com/java-maximum-subarray)
- [How to Merge Two Sorted Arrays](https://www.baeldung.com/java-merge-sorted-arrays)
- [Median of Stream of Integers using Heap](https://www.baeldung.com/java-stream-integers-median-using-heap)
- [Kruskals Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4) [[next -->]](/../algorithms-miscellaneous-6)

View File

@ -21,16 +21,10 @@
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>pl.allegro.finance</groupId>
<artifactId>tradukisto</artifactId>

View File

@ -2,3 +2,9 @@
- [Boruvkas Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm)
- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent)
- [Kruskals Algorithm for Spanning Trees](https://www.baeldung.com/java-spanning-trees-kruskal)
- [Balanced Brackets Algorithm in Java](https://www.baeldung.com/java-balanced-brackets-algorithm)
- [Efficiently Merge Sorted Java Sequences](https://www.baeldung.com/java-merge-sorted-sequences)
- [Introduction to Greedy Algorithms with Java](https://www.baeldung.com/java-greedy-algorithms)
- [The Caesar Cipher in Java](https://www.baeldung.com/java-caesar-cipher)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)

View File

@ -18,10 +18,35 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
<version>${junit.platform.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${org.assertj.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
</dependencies>
<properties>
<guava.version>28.1-jre</guava.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<junit.platform.version>1.6.0</junit.platform.version>
<commons-math3.version>3.6.1</commons-math3.version>
</properties>
</project>

View File

@ -1,13 +1,13 @@
package com.baeldung.algorithms.minheapmerge;
public class HeapNode {
int element;
int arrayIndex;
int nextElementIndex = 1;
public HeapNode(int element, int arrayIndex) {
this.element = element;
this.arrayIndex = arrayIndex;
}
}
package com.baeldung.algorithms.minheapmerge;
public class HeapNode {
int element;
int arrayIndex;
int nextElementIndex = 1;
public HeapNode(int element, int arrayIndex) {
this.element = element;
this.arrayIndex = arrayIndex;
}
}

View File

@ -1,88 +1,88 @@
package com.baeldung.algorithms.minheapmerge;
public class MinHeap {
HeapNode[] heapNodes;
public MinHeap(HeapNode heapNodes[]) {
this.heapNodes = heapNodes;
heapifyFromLastLeafsParent();
}
void heapifyFromLastLeafsParent() {
int lastLeafsParentIndex = getParentNodeIndex(heapNodes.length);
while (lastLeafsParentIndex >= 0) {
heapify(lastLeafsParentIndex);
lastLeafsParentIndex--;
}
}
void heapify(int index) {
int leftNodeIndex = getLeftNodeIndex(index);
int rightNodeIndex = getRightNodeIndex(index);
int smallestElementIndex = index;
if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) {
smallestElementIndex = leftNodeIndex;
}
if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) {
smallestElementIndex = rightNodeIndex;
}
if (smallestElementIndex != index) {
swap(index, smallestElementIndex);
heapify(smallestElementIndex);
}
}
int getParentNodeIndex(int index) {
return (index - 1) / 2;
}
int getLeftNodeIndex(int index) {
return (2 * index + 1);
}
int getRightNodeIndex(int index) {
return (2 * index + 2);
}
HeapNode getRootNode() {
return heapNodes[0];
}
void heapifyFromRoot() {
heapify(0);
}
void swap(int i, int j) {
HeapNode temp = heapNodes[i];
heapNodes[i] = heapNodes[j];
heapNodes[j] = temp;
}
static int[] merge(int[][] array) {
HeapNode[] heapNodes = new HeapNode[array.length];
int resultingArraySize = 0;
for (int i = 0; i < array.length; i++) {
HeapNode node = new HeapNode(array[i][0], i);
heapNodes[i] = node;
resultingArraySize += array[i].length;
}
MinHeap minHeap = new MinHeap(heapNodes);
int[] resultingArray = new int[resultingArraySize];
for (int i = 0; i < resultingArraySize; i++) {
HeapNode root = minHeap.getRootNode();
resultingArray[i] = root.element;
if (root.nextElementIndex < array[root.arrayIndex].length) {
root.element = array[root.arrayIndex][root.nextElementIndex++];
} else {
root.element = Integer.MAX_VALUE;
}
minHeap.heapifyFromRoot();
}
return resultingArray;
}
}
package com.baeldung.algorithms.minheapmerge;
public class MinHeap {
HeapNode[] heapNodes;
public MinHeap(HeapNode heapNodes[]) {
this.heapNodes = heapNodes;
heapifyFromLastLeafsParent();
}
void heapifyFromLastLeafsParent() {
int lastLeafsParentIndex = getParentNodeIndex(heapNodes.length);
while (lastLeafsParentIndex >= 0) {
heapify(lastLeafsParentIndex);
lastLeafsParentIndex--;
}
}
void heapify(int index) {
int leftNodeIndex = getLeftNodeIndex(index);
int rightNodeIndex = getRightNodeIndex(index);
int smallestElementIndex = index;
if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) {
smallestElementIndex = leftNodeIndex;
}
if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) {
smallestElementIndex = rightNodeIndex;
}
if (smallestElementIndex != index) {
swap(index, smallestElementIndex);
heapify(smallestElementIndex);
}
}
int getParentNodeIndex(int index) {
return (index - 1) / 2;
}
int getLeftNodeIndex(int index) {
return (2 * index + 1);
}
int getRightNodeIndex(int index) {
return (2 * index + 2);
}
HeapNode getRootNode() {
return heapNodes[0];
}
void heapifyFromRoot() {
heapify(0);
}
void swap(int i, int j) {
HeapNode temp = heapNodes[i];
heapNodes[i] = heapNodes[j];
heapNodes[j] = temp;
}
static int[] merge(int[][] array) {
HeapNode[] heapNodes = new HeapNode[array.length];
int resultingArraySize = 0;
for (int i = 0; i < array.length; i++) {
HeapNode node = new HeapNode(array[i][0], i);
heapNodes[i] = node;
resultingArraySize += array[i].length;
}
MinHeap minHeap = new MinHeap(heapNodes);
int[] resultingArray = new int[resultingArraySize];
for (int i = 0; i < resultingArraySize; i++) {
HeapNode root = minHeap.getRootNode();
resultingArray[i] = root.element;
if (root.nextElementIndex < array[root.arrayIndex].length) {
root.element = array[root.arrayIndex][root.nextElementIndex++];
} else {
root.element = Integer.MAX_VALUE;
}
minHeap.heapifyFromRoot();
}
return resultingArray;
}
}

View File

@ -1,22 +1,22 @@
package com.baeldung.algorithms.minheapmerge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class MinHeapUnitTest {
private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } };
private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 };
@Test
public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() {
int[] resultArray = MinHeap.merge(inputArray);
assertThat(resultArray.length, is(equalTo(10)));
assertThat(resultArray, is(equalTo(expectedArray)));
}
}
package com.baeldung.algorithms.minheapmerge;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class MinHeapUnitTest {
private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } };
private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 };
@Test
public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() {
int[] resultArray = MinHeap.merge(inputArray);
assertThat(resultArray.length, is(equalTo(10)));
assertThat(resultArray, is(equalTo(expectedArray)));
}
}

View File

@ -17,6 +17,12 @@
</parent>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>

View File

@ -5,6 +5,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
public class CreditAppUnitTest {
@ -40,13 +41,28 @@ public class CreditAppUnitTest {
assertNotNull(lender);
}
@Ignore
@Test
public void givenBorrower_whenDoubleOrNotString_thenRequestLoan() {
Borrower borrower = new Borrower();
double amount = 100.0;
/*if(amount instanceof Double) { // Compilation error, no autoboxing
borrower.requestLoan(amount);
}
if(!(amount instanceof String)) { // Compilation error, incompatible operands
borrower.requestLoan(amount);
}*/
}
@Test
public void givenBorrower_whenLoanAmountIsDouble_thenRequestLoan() {
Borrower borrower = new Borrower();
double amount = 100.0;
//if(amount instanceof Double) // Compilation error, no autoboxing
if(Double.class.isInstance(amount)) {
if(Double.class.isInstance(amount)) { // No compilation error
borrower.requestLoan(amount);
}
assertEquals(100, borrower.getTotalLoanAmount());
@ -57,8 +73,7 @@ public class CreditAppUnitTest {
Borrower borrower = new Borrower();
Double amount = 100.0;
//if(amount instanceof String) // Compilation error, incompatible operands
if(!String.class.isInstance(amount)) {
if(!String.class.isInstance(amount)) { // No compilation error
borrower.requestLoan(amount);
}
assertEquals(100, borrower.getTotalLoanAmount());

View File

@ -20,6 +20,23 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>${modelmapper.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,32 @@
package com.baeldung.modelmapper;
import org.modelmapper.ModelMapper;
import java.util.List;
import java.util.stream.Collectors;
/**
* This is a helper class that contains method for custom mapping of the users list.
* Initially, an instance of ModelMapper was created.
*
* @author Sasa Milenkovic
*/
public class MapperUtil {
private static ModelMapper modelMapper = new ModelMapper();
private MapperUtil() {
}
public static <S, T> List<T> mapList(List<S> source, Class<T> targetClass) {
return source
.stream()
.map(element -> modelMapper.map(element, targetClass))
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.modelmapper;
/**
* User model entity class
*
* @author Sasa Milenkovic
*/
public class User {
private String userId;
private String username;
private String email;
private String contactNumber;
private String userType;
// Standard constructors, getters and setters
public User() {
}
public User(String userId, String username, String email, String contactNumber, String userType) {
this.userId = userId;
this.username = username;
this.email = email;
this.contactNumber = contactNumber;
this.userType = userType;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String userName) {
this.username = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.modelmapper;
/**
* UserDTO model class
*
* @author Sasa Milenkovic
*/
public class UserDTO {
private String userId;
private String username;
private String email;
// getters and setters
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.modelmapper;
import java.util.Collection;
/**
* UserList class that contain collection of users
*
* @author Sasa Milenkovic
*/
public class UserList {
private Collection<User> users;
public Collection<User> getUsers() {
return users;
}
public void setUsers(Collection<User> users) {
this.users = users;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.modelmapper;
import java.util.List;
/**
* UserListDTO class that contain list of username properties
*
* @author Sasa Milenkovic
*/
public class UserListDTO {
private List<String> usernames;
public List<String> getUsernames() {
return usernames;
}
public void setUsernames(List<String> usernames) {
this.usernames = usernames;
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.modelmapper;
import org.modelmapper.AbstractConverter;
import java.util.List;
import java.util.stream.Collectors;
/**
* UsersListConverter class map the property data from the list of users into the list of user names.
*
* @author Sasa Milenkovic
*/
public class UsersListConverter extends AbstractConverter<List<User>, List<String>> {
@Override
protected List<String> convert(List<User> users) {
return users
.stream()
.map(User::getUsername)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,92 @@
package com.baeldung.modelmapper;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeMap;
import org.modelmapper.TypeToken;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertThat;
/**
* This class has test methods of mapping Integer to Character list,
* mapping users list to DTO list using MapperUtil custom type method and property mapping using converter class
*
* @author Sasa Milenkovic
*/
public class UsersListMappingUnitTest {
private ModelMapper modelMapper;
private List<User> users;
@Before
public void init() {
modelMapper = new ModelMapper();
TypeMap<UserList, UserListDTO> typeMap = modelMapper.createTypeMap(UserList.class, UserListDTO.class);
typeMap.addMappings(mapper -> mapper.using(new UsersListConverter())
.map(UserList::getUsers, UserListDTO::setUsernames));
users = new ArrayList();
users.add(new User("b100", "user1", "user1@baeldung.com", "111-222", "USER"));
users.add(new User("b101", "user2", "user2@baeldung.com", "111-333", "USER"));
users.add(new User("b102", "user3", "user3@baeldung.com", "111-444", "ADMIN"));
}
@Test
public void whenInteger_thenMapToCharacter() {
List<Integer> integers = new ArrayList<Integer>();
integers.add(1);
integers.add(2);
integers.add(3);
List<Character> characters = modelMapper.map(integers, new TypeToken<List<Character>>() {
}.getType());
assertThat(characters, hasItems('1', '2', '3'));
}
@Test
public void givenUsersList_whenUseGenericType_thenMapToUserDTO() {
// Mapping lists using custom (generic) type mapping
List<UserDTO> userDtoList = MapperUtil.mapList(users, UserDTO.class);
assertThat(userDtoList, Matchers.<UserDTO>hasItem(
Matchers.both(hasProperty("userId", equalTo("b100")))
.and(hasProperty("email", equalTo("user1@baeldung.com")))
.and(hasProperty("username", equalTo("user1")))));
}
@Test
public void givenUsersList_whenUseConverter_thenMapToUsernames() {
// Mapping lists using property mapping and converter
UserList userList = new UserList();
userList.setUsers(users);
UserListDTO dtos = new UserListDTO();
modelMapper.map(userList, dtos);
assertThat(dtos.getUsernames(), hasItems("user1", "user2", "user3"));
}
}

View File

@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
@ -45,6 +45,9 @@
<guava.version>23.0</guava.version>
<commons.io.version>2.6</commons.io.version>
<jmh.version>1.19</jmh.version>
<modelmapper.version>2.3.7</modelmapper.version>
<junit.version>4.12</junit.version>
<hamcrest.version>2.2</hamcrest.version>
</properties>
</project>

View File

@ -28,7 +28,7 @@ public class FaviconConfiguration {
@Bean
protected ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
ClassPathResource classPathResource = new ClassPathResource("com/baeldung/images");
ClassPathResource classPathResource = new ClassPathResource("com/baeldung/images/");
List<Resource> locations = Arrays.asList(classPathResource);
requestHandler.setLocations(locations);
return requestHandler;