+3
-4
@@ -85,7 +85,6 @@ transaction.log
|
||||
*-shell.log
|
||||
|
||||
apache-cxf/cxf-aegis/baeldung.xml
|
||||
apache-fop/src/test/resources/input.xml
|
||||
apache-fop/src/test/resources/output_herold.pdf
|
||||
apache-fop/src/test/resources/output_html2fo.pdf
|
||||
apache-fop/src/test/resources/output_jtidy.pdf
|
||||
testing-modules/report-*.json
|
||||
|
||||
libraries-2/*.db
|
||||
+13
-2
@@ -1,16 +1,21 @@
|
||||
package com.baeldung.jgrapht;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import org.jgrapht.ext.JGraphXAdapter;
|
||||
import org.jgrapht.graph.DefaultDirectedGraph;
|
||||
import org.jgrapht.graph.DefaultEdge;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mxgraph.layout.mxCircleLayout;
|
||||
import com.mxgraph.layout.mxIGraphLayout;
|
||||
import com.mxgraph.util.mxCellRenderer;
|
||||
@@ -20,7 +25,7 @@ public class GraphImageGenerationUnitTest {
|
||||
|
||||
@Before
|
||||
public void createGraph() throws IOException {
|
||||
File imgFile = new File("src/test/resources/graph.png");
|
||||
File imgFile = new File("src/test/resources/graph1.png");
|
||||
imgFile.createNewFile();
|
||||
g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
|
||||
String x1 = "x1";
|
||||
@@ -34,12 +39,18 @@ public class GraphImageGenerationUnitTest {
|
||||
g.addEdge(x3, x1);
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
File imgFile = new File("src/test/resources/graph1.png");
|
||||
imgFile.deleteOnExit();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
|
||||
JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g);
|
||||
mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
|
||||
layout.execute(graphAdapter.getDefaultParent());
|
||||
File imgFile = new File("src/test/resources/graph.png");
|
||||
File imgFile = new File("src/test/resources/graph1.png");
|
||||
BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null);
|
||||
ImageIO.write(image, "PNG", imgFile);
|
||||
assertTrue(imgFile.exists());
|
||||
|
||||
@@ -7,4 +7,6 @@
|
||||
- [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)
|
||||
- [Implementing a 2048 Solver in Java](https://www.baeldung.com/2048-java-solver)
|
||||
- [Finding Top K Elements in an Array](https://www.baeldung.com/java-array-top-elements)
|
||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-5)
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package com.baeldung.algorithms.play2048;
|
||||
|
||||
public class Play2048 {
|
||||
private static final int SIZE = 3;
|
||||
private static final int SIZE = 4;
|
||||
private static final int INITIAL_NUMBERS = 2;
|
||||
|
||||
public static void main(String[] args) {
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.algorithms.topkelements;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class BruteForceTopKElementsFinder implements TopKElementsFinder<Integer> {
|
||||
|
||||
public List<Integer> findTopK(List<Integer> input, int k) {
|
||||
List<Integer> array = new ArrayList<>(input);
|
||||
List<Integer> topKList = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < k; i++) {
|
||||
int maxIndex = 0;
|
||||
|
||||
for (int j = 1; j < array.size(); j++) {
|
||||
if (array.get(j) > array.get(maxIndex)) {
|
||||
maxIndex = j;
|
||||
}
|
||||
}
|
||||
|
||||
topKList.add(array.remove(maxIndex));
|
||||
}
|
||||
|
||||
return topKList;
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.algorithms.topkelements;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
public class MaxHeapTopKElementsFinder implements TopKElementsFinder<Integer> {
|
||||
|
||||
public List<Integer> findTopK(List<Integer> input, int k) {
|
||||
PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
|
||||
|
||||
input.forEach(number -> {
|
||||
maxHeap.add(number);
|
||||
|
||||
if (maxHeap.size() > k) {
|
||||
maxHeap.poll();
|
||||
}
|
||||
});
|
||||
|
||||
List<Integer> topKList = new ArrayList<>(maxHeap);
|
||||
Collections.reverse(topKList);
|
||||
|
||||
return topKList;
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.algorithms.topkelements;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface TopKElementsFinder<T extends Comparable<T>> {
|
||||
List<T> findTopK(List<T> input, int k);
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.algorithms.topkelements;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class TreeSetTopKElementsFinder implements TopKElementsFinder<Integer> {
|
||||
|
||||
public List<Integer> findTopK(List<Integer> input, int k) {
|
||||
Set<Integer> sortedSet = new TreeSet<>(Comparator.reverseOrder());
|
||||
sortedSet.addAll(input);
|
||||
|
||||
return sortedSet.stream().limit(k).collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.algorithms.topkelements;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Java6Assertions.assertThat;
|
||||
|
||||
public class TopKElementsFinderUnitTest {
|
||||
private final TopKElementsFinder<Integer> bruteForceFinder = new BruteForceTopKElementsFinder();
|
||||
private final TopKElementsFinder<Integer> maxHeapFinder = new MaxHeapTopKElementsFinder();
|
||||
private final TopKElementsFinder<Integer> treeSetFinder = new TreeSetTopKElementsFinder();
|
||||
|
||||
private final int k = 4;
|
||||
private final List<Integer> distinctIntegers = Arrays.asList(1, 2, 3, 9, 7, 6, 12);
|
||||
private final List<Integer> distinctIntegersTopK = Arrays.asList(9, 7, 6, 12);
|
||||
private final List<Integer> nonDistinctIntegers = Arrays.asList(1, 2, 3, 3, 9, 9, 7, 6, 12);
|
||||
private final List<Integer> nonDistinctIntegersTopK = Arrays.asList(9, 9, 7, 12);
|
||||
|
||||
|
||||
@Test
|
||||
public void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
|
||||
assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
|
||||
assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() {
|
||||
assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() {
|
||||
assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() {
|
||||
assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
This module contains articles about searching algorithms.
|
||||
|
||||
### Relevant articles:
|
||||
|
||||
- [Binary Search Algorithm in Java](https://www.baeldung.com/java-binary-search)
|
||||
- [Depth First Search in Java](https://www.baeldung.com/java-depth-first-search)
|
||||
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
|
||||
@@ -11,3 +12,4 @@ This module contains articles about searching algorithms.
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](https://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
- [Range Search Algorithm in Java](https://www.baeldung.com/java-range-search)
|
||||
- [Fast Pattern Matching of Strings Using Suffix Tree](https://www.baeldung.com/java-pattern-matching-suffix-tree)
|
||||
- [Find the Kth Smallest Element in Two Sorted Arrays](https://www.baeldung.com/java-kth-smallest-element-in-sorted-arrays)
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package com.baeldung.algorithms.kthsmallest;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static java.lang.Math.max;
|
||||
import static java.lang.Math.min;
|
||||
|
||||
public class KthSmallest {
|
||||
|
||||
public static int findKthSmallestElement(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException {
|
||||
|
||||
checkInput(k, list1, list2);
|
||||
|
||||
// we are looking for the minimum value
|
||||
if(k == 1) {
|
||||
return min(list1[0], list2[0]);
|
||||
}
|
||||
|
||||
// we are looking for the maximum value
|
||||
if(list1.length + list2.length == k) {
|
||||
return max(list1[list1.length-1], list2[list2.length-1]);
|
||||
}
|
||||
|
||||
// swap lists if needed to make sure we take at least one element from list1
|
||||
if(k <= list2.length && list2[k-1] < list1[0]) {
|
||||
int[] list1_ = list1;
|
||||
list1 = list2;
|
||||
list2 = list1_;
|
||||
}
|
||||
|
||||
// correct left boundary if k is bigger than the size of list2
|
||||
int left = k < list2.length ? 0 : k - list2.length - 1;
|
||||
|
||||
// the inital right boundary cannot exceed the list1
|
||||
int right = min(k-1, list1.length - 1);
|
||||
|
||||
int nElementsList1, nElementsList2;
|
||||
|
||||
// binary search
|
||||
do {
|
||||
nElementsList1 = ((left + right) / 2) + 1;
|
||||
nElementsList2 = k - nElementsList1;
|
||||
|
||||
if(nElementsList2 > 0) {
|
||||
if (list1[nElementsList1 - 1] > list2[nElementsList2 - 1]) {
|
||||
right = nElementsList1 - 2;
|
||||
} else {
|
||||
left = nElementsList1;
|
||||
}
|
||||
}
|
||||
} while(!kthSmallesElementFound(list1, list2, nElementsList1, nElementsList2));
|
||||
|
||||
return nElementsList2 == 0 ? list1[nElementsList1-1] : max(list1[nElementsList1-1], list2[nElementsList2-1]);
|
||||
}
|
||||
|
||||
private static boolean kthSmallesElementFound(int[] list1, int[] list2, int nElementsList1, int nElementsList2) {
|
||||
|
||||
// we do not take any element from the second list
|
||||
if(nElementsList2 < 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if(list1[nElementsList1-1] == list2[nElementsList2-1]) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if(nElementsList1 == list1.length) {
|
||||
return list1[nElementsList1-1] <= list2[nElementsList2];
|
||||
}
|
||||
|
||||
if(nElementsList2 == list2.length) {
|
||||
return list2[nElementsList2-1] <= list1[nElementsList1];
|
||||
}
|
||||
|
||||
return list1[nElementsList1-1] <= list2[nElementsList2] && list2[nElementsList2-1] <= list1[nElementsList1];
|
||||
}
|
||||
|
||||
|
||||
private static void checkInput(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException {
|
||||
|
||||
if(list1 == null || list2 == null || k < 1) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
if(list1.length == 0 || list2.length == 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
if(k > list1.length + list2.length) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
}
|
||||
|
||||
public static int getKthElementSorted(int[] list1, int[] list2, int k) {
|
||||
|
||||
int length1 = list1.length, length2 = list2.length;
|
||||
int[] combinedArray = new int[length1 + length2];
|
||||
System.arraycopy(list1, 0, combinedArray, 0, list1.length);
|
||||
System.arraycopy(list2, 0, combinedArray, list1.length, list2.length);
|
||||
Arrays.sort(combinedArray);
|
||||
|
||||
return combinedArray[k-1];
|
||||
}
|
||||
|
||||
public static int getKthElementMerge(int[] list1, int[] list2, int k) {
|
||||
|
||||
int i1 = 0, i2 = 0;
|
||||
|
||||
while(i1 < list1.length && i2 < list2.length && (i1 + i2) < k) {
|
||||
if(list1[i1] < list2[i2]) {
|
||||
i1++;
|
||||
} else {
|
||||
i2++;
|
||||
}
|
||||
}
|
||||
|
||||
if((i1 + i2) < k) {
|
||||
return i1 < list1.length ? list1[k - i2 - 1] : list2[k - i1 - 1];
|
||||
} else if(i1 > 0 && i2 > 0) {
|
||||
return Math.max(list1[i1-1], list2[i2-1]);
|
||||
} else {
|
||||
return i1 == 0 ? list2[i2-1] : list1[i1-1];
|
||||
}
|
||||
}
|
||||
}
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
package com.baeldung.algorithms.kthsmallest;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static com.baeldung.algorithms.kthsmallest.KthSmallest.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class KthSmallestUnitTest {
|
||||
|
||||
@Nested
|
||||
class Exceptions {
|
||||
|
||||
@Test
|
||||
public void when_at_least_one_list_is_null_then_an_exception_is_thrown() {
|
||||
|
||||
Executable executable1 = () -> findKthSmallestElement(1, null, null);
|
||||
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, null);
|
||||
Executable executable3 = () -> findKthSmallestElement(1, null, new int[]{2});
|
||||
|
||||
assertThrows(IllegalArgumentException.class, executable1);
|
||||
assertThrows(IllegalArgumentException.class, executable2);
|
||||
assertThrows(IllegalArgumentException.class, executable3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_at_least_one_list_is_empty_then_an_exception_is_thrown() {
|
||||
|
||||
Executable executable1 = () -> findKthSmallestElement(1, new int[]{}, new int[]{2});
|
||||
Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, new int[]{});
|
||||
Executable executable3 = () -> findKthSmallestElement(1, new int[]{}, new int[]{});
|
||||
|
||||
assertThrows(IllegalArgumentException.class, executable1);
|
||||
assertThrows(IllegalArgumentException.class, executable2);
|
||||
assertThrows(IllegalArgumentException.class, executable3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_is_smaller_than_0_then_an_exception_is_thrown() {
|
||||
Executable executable1 = () -> findKthSmallestElement(-1, new int[]{2}, new int[]{2});
|
||||
assertThrows(IllegalArgumentException.class, executable1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_is_smaller_than_1_then_an_exception_is_thrown() {
|
||||
Executable executable1 = () -> findKthSmallestElement(0, new int[]{2}, new int[]{2});
|
||||
assertThrows(IllegalArgumentException.class, executable1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() {
|
||||
Executable executable1 = () -> findKthSmallestElement(6, new int[]{1, 5, 6}, new int[]{2, 5});
|
||||
assertThrows(NoSuchElementException.class, executable1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Nested
|
||||
class K_is_smaller_than_the_size_of_list1_and_the_size_of_list2 {
|
||||
|
||||
@Test
|
||||
public void when_k_is_1_then_the_smallest_element_is_returned_from_list1() {
|
||||
int result = findKthSmallestElement(1, new int[]{2, 7}, new int[]{3, 5});
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_is_1_then_the_smallest_element_is_returned_list2() {
|
||||
int result = findKthSmallestElement(1, new int[]{3, 5}, new int[]{2, 7});
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_kth_element_is_smallest_element_and_occurs_in_both_lists() {
|
||||
int[] list1 = new int[]{1, 2, 3};
|
||||
int[] list2 = new int[]{1, 2, 3};
|
||||
int result = findKthSmallestElement(1, list1, list2);
|
||||
assertEquals(1, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_kth_element_is_smallest_element_and_occurs_in_both_lists2() {
|
||||
int[] list1 = new int[]{1, 2, 3};
|
||||
int[] list2 = new int[]{1, 2, 3};
|
||||
int result = findKthSmallestElement(2, list1, list2);
|
||||
assertEquals(1, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_kth_element_is_largest_element_and_occurs_in_both_lists_1() {
|
||||
int[] list1 = new int[]{1, 2, 3};
|
||||
int[] list2 = new int[]{1, 2, 3};
|
||||
int result = findKthSmallestElement(5, list1, list2);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_kth_element_is_largest_element_and_occurs_in_both_lists_2() {
|
||||
int[] list1 = new int[]{1, 2, 3};
|
||||
int[] list2 = new int[]{1, 2, 3};
|
||||
int result = findKthSmallestElement(6, list1, list2);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_kth_element_and_occurs_in_both_lists() {
|
||||
int[] list1 = new int[]{1, 2, 3};
|
||||
int[] list2 = new int[]{0, 2, 3};
|
||||
int result = findKthSmallestElement(3, list1, list2);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void and_kth_element_is_in_first_list() {
|
||||
int[] list1 = new int[]{1,2,3,4};
|
||||
int[] list2 = new int[]{1,3,4,5};
|
||||
int result = findKthSmallestElement(3, list1, list2);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void and_kth_is_in_second_list() {
|
||||
int[] list1 = new int[]{1,3,4,4};
|
||||
int[] list2 = new int[]{1,2,4,5};
|
||||
int result = findKthSmallestElement(3, list1, list2);
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void and_elements_in_first_list_are_all_smaller_than_second_list() {
|
||||
int[] list1 = new int[]{1,3,7,9};
|
||||
int[] list2 = new int[]{11,12,14,15};
|
||||
int result = findKthSmallestElement(3, list1, list2);
|
||||
assertEquals(7, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void and_elements_in_first_list_are_all_smaller_than_second_list2() {
|
||||
int[] list1 = new int[]{1,3,7,9};
|
||||
int[] list2 = new int[]{11,12,14,15};
|
||||
int result = findKthSmallestElement(4, list1, list2);
|
||||
assertEquals(9, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void and_only_elements_from_second_list_are_part_of_result() {
|
||||
int[] list1 = new int[]{11,12,14,15};
|
||||
int[] list2 = new int[]{1,3,7,9};
|
||||
int result = findKthSmallestElement(3, list1, list2);
|
||||
assertEquals(7, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void and_only_elements_from_second_list_are_part_of_result2() {
|
||||
int[] list1 = new int[]{11,12,14,15};
|
||||
int[] list2 = new int[]{1,3,7,9};
|
||||
int result = findKthSmallestElement(4, list1, list2);
|
||||
assertEquals(9, result);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
class K_is_bigger_than_the_size_of_at_least_one_of_the_lists {
|
||||
|
||||
@Test
|
||||
public void k_is_smaller_than_list1_and_bigger_than_list2() {
|
||||
int[] list1 = new int[]{1, 2, 3, 4, 7, 9};
|
||||
int[] list2 = new int[]{1, 2, 3};
|
||||
int result = findKthSmallestElement(5, list1, list2);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void k_is_bigger_than_list1_and_smaller_than_list2() {
|
||||
int[] list1 = new int[]{1, 2, 3};
|
||||
int[] list2 = new int[]{1, 2, 3, 4, 7, 9};
|
||||
int result = findKthSmallestElement(5, list1, list2);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_is_bigger_than_the_size_of_both_lists_and_elements_in_second_list_are_all_smaller_than_first_list() {
|
||||
int[] list1 = new int[]{9, 11, 13, 55};
|
||||
int[] list2 = new int[]{1, 2, 3, 7};
|
||||
int result = findKthSmallestElement(6, list1, list2);
|
||||
assertEquals(11, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_is_bigger_than_the_size_of_both_lists_and_elements_in_second_list_are_all_bigger_than_first_list() {
|
||||
int[] list1 = new int[]{1, 2, 3, 7};
|
||||
int[] list2 = new int[]{9, 11, 13, 55};
|
||||
int result = findKthSmallestElement(6, list1, list2);
|
||||
assertEquals(11, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_is_bigger_than_the_size_of_both_lists() {
|
||||
int[] list1 = new int[]{3, 7, 9, 11, 55};
|
||||
int[] list2 = new int[]{1, 2, 3, 7, 13};
|
||||
int result = findKthSmallestElement(7, list1, list2);
|
||||
assertEquals(9, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_is_bigger_than_the_size_of_both_lists_and_list1_has_more_elements_than_list2() {
|
||||
int[] list1 = new int[]{3, 7, 9, 11, 55, 77, 100, 200};
|
||||
int[] list2 = new int[]{1, 2, 3, 7, 13};
|
||||
int result = findKthSmallestElement(11, list1, list2);
|
||||
assertEquals(77, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void max_test() {
|
||||
int[] list1 = new int[]{100, 200};
|
||||
int[] list2 = new int[]{1, 2, 3};
|
||||
int result = findKthSmallestElement(4, list1, list2);
|
||||
assertEquals(100, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void max_test2() {
|
||||
int[] list1 = new int[]{100, 200};
|
||||
int[] list2 = new int[]{1, 2, 3};
|
||||
int result = findKthSmallestElement(5, list1, list2);
|
||||
assertEquals(200, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_in_list2() {
|
||||
int[] list1 = new int[]{1, 2, 5};
|
||||
int[] list2 = new int[]{1, 3, 4, 7};
|
||||
int result = findKthSmallestElement(4, list1, list2);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_is_smallest_in_list2() {
|
||||
int[] list1 = new int[]{1, 2, 5};
|
||||
int[] list2 = new int[]{3, 4, 7};
|
||||
int result = findKthSmallestElement(3, list1, list2);
|
||||
assertEquals(3, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void when_k_is_smaller_than_the_size_of_both_lists_and_kth_element_is_smallest_in_list23() {
|
||||
int[] list1 = new int[]{3, 11, 27, 53, 90};
|
||||
int[] list2 = new int[]{4, 20, 21, 100};
|
||||
int result = findKthSmallestElement(5, list1, list2);
|
||||
assertEquals(21, result);
|
||||
}
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void randomTests() {
|
||||
// IntStream.range(1, 100000).forEach(i -> random());
|
||||
// }
|
||||
|
||||
private void random() {
|
||||
|
||||
Random random = new Random();
|
||||
int length1 = (Math.abs(random.nextInt())) % 1000 + 1;
|
||||
int length2 = (Math.abs(random.nextInt())) % 1000 + 1;
|
||||
|
||||
int[] list1 = sortedRandomIntArrayOfLength(length1);
|
||||
int[] list2 = sortedRandomIntArrayOfLength(length2);
|
||||
|
||||
int k = (Math.abs(random.nextInt()) % (length1 + length2)) + 1 ;
|
||||
|
||||
int result = findKthSmallestElement(k, list1, list2);
|
||||
|
||||
int result2 = getKthElementSorted(list1, list2, k);
|
||||
|
||||
int result3 = getKthElementMerge(list1, list2, k);
|
||||
|
||||
assertEquals(result2, result);
|
||||
assertEquals(result2, result3);
|
||||
}
|
||||
|
||||
private int[] sortedRandomIntArrayOfLength(int length) {
|
||||
int[] intArray = new Random().ints(length).toArray();
|
||||
Arrays.sort(intArray);
|
||||
return intArray;
|
||||
}
|
||||
}
|
||||
@@ -7,4 +7,3 @@ This module contains articles about Apache CXF
|
||||
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
|
||||
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
|
||||
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)
|
||||
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)
|
||||
@@ -2,7 +2,7 @@
|
||||
<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>apache-miscellaneous-1</artifactId>
|
||||
<artifactId>apache-libraries</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>apache-libraries</name>
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
This module contains articles about Apache POI
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
|
||||
- [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel)
|
||||
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
|
||||
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
|
||||
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
|
||||
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
|
||||
- [Setting Formulas in Excel with Apache POI](https://www.baeldung.com/java-apache-poi-set-formulas)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.poi.excel.setformula;
|
||||
|
||||
import org.apache.poi.xssf.usermodel.XSSFCell;
|
||||
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
|
||||
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
public class ExcelFormula {
|
||||
public double setFormula(String fileLocation, XSSFWorkbook wb, String formula) throws IOException {
|
||||
XSSFSheet sheet = wb.getSheetAt(0);
|
||||
int lastCellNum = sheet.getRow(0).getLastCellNum();
|
||||
XSSFCell formulaCell = sheet.getRow(0).createCell(lastCellNum);
|
||||
formulaCell.setCellFormula(formula);
|
||||
XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
|
||||
formulaEvaluator.evaluateFormulaCell(formulaCell);
|
||||
FileOutputStream fileOut = new FileOutputStream(new File(fileLocation));
|
||||
wb.write(fileOut);
|
||||
wb.close();
|
||||
fileOut.close();
|
||||
return formulaCell.getNumericCellValue();
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.poi.excel.setformula;
|
||||
|
||||
import org.apache.poi.ss.util.CellReference;
|
||||
import org.apache.poi.xssf.usermodel.XSSFSheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
class ExcelFormulaUnitTest {
|
||||
private static String FILE_NAME = "com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx";
|
||||
private String fileLocation;
|
||||
private ExcelFormula excelFormula;
|
||||
|
||||
@BeforeEach
|
||||
public void setup() throws URISyntaxException {
|
||||
fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString();
|
||||
excelFormula = new ExcelFormula();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenExcelData_whenSetFormula_thenSuccess() throws IOException {
|
||||
FileInputStream inputStream = new FileInputStream(new File(fileLocation));
|
||||
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
|
||||
XSSFSheet sheet = wb.getSheetAt(0);
|
||||
double resultColumnA = 0;
|
||||
double resultColumnB = 0;
|
||||
for (int row = 0; row <= sheet.getLastRowNum(); row++) {
|
||||
resultColumnA += sheet.getRow(row).getCell(0).getNumericCellValue();
|
||||
resultColumnB += sheet.getRow(row).getCell(1).getNumericCellValue();
|
||||
}
|
||||
String colNameA = CellReference.convertNumToColString(0);
|
||||
String colNameB = CellReference.convertNumToColString(1);
|
||||
String startCellA = colNameA + 1;
|
||||
String stopCellA = colNameA + (sheet.getLastRowNum() + 1);
|
||||
String sumFormulaForColumnA = String.format("SUM(%s:%s)", startCellA, stopCellA);
|
||||
String startCellB = colNameB + 1;
|
||||
String stopCellB = colNameB + (sheet.getLastRowNum() + 1);
|
||||
String sumFormulaForColumnB = String.format("SUM(%s:%s)", startCellB, stopCellB);
|
||||
|
||||
double resultValue = excelFormula.setFormula(fileLocation, wb, sumFormulaForColumnA + "-" + sumFormulaForColumnB);
|
||||
|
||||
Assert.assertEquals(resultColumnA - resultColumnB, resultValue, 0d);
|
||||
}
|
||||
}
|
||||
@@ -6,4 +6,4 @@ This module contains articles about Apache Shiro
|
||||
|
||||
- [Introduction to Apache Shiro](https://www.baeldung.com/apache-shiro)
|
||||
- [Permissions-Based Access Control with Apache Shiro](https://www.baeldung.com/apache-shiro-access-control)
|
||||
|
||||
- [Spring Security vs Apache Shiro](https://www.baeldung.com/spring-security-vs-apache-shiro)
|
||||
|
||||
+10
-1
@@ -39,10 +39,19 @@
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- spring-sec -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<apache-shiro-core-version>1.4.0</apache-shiro-core-version>
|
||||
<apache-shiro-core-version>1.5.3</apache-shiro-core-version>
|
||||
<log4j-version>1.2.17</log4j-version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.comparison.shiro;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.shiro.authc.AuthenticationException;
|
||||
import org.apache.shiro.authc.AuthenticationInfo;
|
||||
import org.apache.shiro.authc.AuthenticationToken;
|
||||
import org.apache.shiro.authc.SimpleAuthenticationInfo;
|
||||
import org.apache.shiro.authc.UnknownAccountException;
|
||||
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||
import org.apache.shiro.authz.AuthorizationInfo;
|
||||
import org.apache.shiro.authz.SimpleAuthorizationInfo;
|
||||
import org.apache.shiro.realm.jdbc.JdbcRealm;
|
||||
import org.apache.shiro.subject.PrincipalCollection;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CustomRealm extends JdbcRealm {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(CustomRealm.class);
|
||||
|
||||
private Map<String, String> credentials = new HashMap<>();
|
||||
private Map<String, Set<String>> roles = new HashMap<>();
|
||||
private Map<String, Set<String>> permissions = new HashMap<>();
|
||||
|
||||
{
|
||||
credentials.put("Tom", "password");
|
||||
credentials.put("Jerry", "password");
|
||||
|
||||
roles.put("Jerry", new HashSet<>(Arrays.asList("ADMIN")));
|
||||
roles.put("Tom", new HashSet<>(Arrays.asList("USER")));
|
||||
|
||||
permissions.put("ADMIN", new HashSet<>(Arrays.asList("READ", "WRITE")));
|
||||
permissions.put("USER", new HashSet<>(Arrays.asList("READ")));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
|
||||
|
||||
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
|
||||
|
||||
if (userToken.getUsername() == null || userToken.getUsername()
|
||||
.isEmpty() || !credentials.containsKey(userToken.getUsername())) {
|
||||
throw new UnknownAccountException("User doesn't exist");
|
||||
}
|
||||
|
||||
return new SimpleAuthenticationInfo(userToken.getUsername(), credentials.get(userToken.getUsername()), getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
|
||||
Set<String> roles = new HashSet<>();
|
||||
Set<String> permissions = new HashSet<>();
|
||||
|
||||
for (Object user : principals) {
|
||||
try {
|
||||
roles.addAll(getRoleNamesForUser(null, (String) user));
|
||||
permissions.addAll(getPermissions(null, null, roles));
|
||||
} catch (SQLException e) {
|
||||
logger.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
SimpleAuthorizationInfo authInfo = new SimpleAuthorizationInfo(roles);
|
||||
authInfo.setStringPermissions(permissions);
|
||||
return authInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
|
||||
if (!roles.containsKey(username)) {
|
||||
throw new SQLException("User doesn't exist");
|
||||
}
|
||||
return roles.get(username);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Set<String> getPermissions(Connection conn, String username, Collection<String> roles) throws SQLException {
|
||||
Set<String> userPermissions = new HashSet<>();
|
||||
|
||||
for (String role : roles) {
|
||||
if (!permissions.containsKey(role)) {
|
||||
throw new SQLException("Role doesn't exist");
|
||||
}
|
||||
userPermissions.addAll(permissions.get(role));
|
||||
}
|
||||
return userPermissions;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.comparison.shiro;
|
||||
|
||||
import org.apache.shiro.realm.Realm;
|
||||
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
|
||||
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
|
||||
public class ShiroApplication {
|
||||
|
||||
public static void main(String... args) {
|
||||
SpringApplication.run(ShiroApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Realm customRealm() {
|
||||
return new CustomRealm();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
|
||||
DefaultShiroFilterChainDefinition filter = new DefaultShiroFilterChainDefinition();
|
||||
|
||||
filter.addPathDefinition("/home", "authc");
|
||||
filter.addPathDefinition("/**", "anon");
|
||||
|
||||
return filter;
|
||||
}
|
||||
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.baeldung.comparison.shiro.controllers;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.shiro.SecurityUtils;
|
||||
import org.apache.shiro.authc.AuthenticationException;
|
||||
import org.apache.shiro.authc.UsernamePasswordToken;
|
||||
import org.apache.shiro.subject.Subject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.baeldung.comparison.shiro.models.UserCredentials;
|
||||
|
||||
@Controller
|
||||
public class ShiroController {
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(ShiroController.class);
|
||||
|
||||
@GetMapping("/")
|
||||
public String getIndex() {
|
||||
return "comparison/index";
|
||||
}
|
||||
|
||||
@GetMapping("/login")
|
||||
public String showLoginPage() {
|
||||
return "comparison/login";
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public String doLogin(HttpServletRequest req, UserCredentials credentials, RedirectAttributes attr) {
|
||||
|
||||
Subject subject = SecurityUtils.getSubject();
|
||||
|
||||
if (!subject.isAuthenticated()) {
|
||||
UsernamePasswordToken token = new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword());
|
||||
try {
|
||||
subject.login(token);
|
||||
} catch (AuthenticationException ae) {
|
||||
logger.error(ae.getMessage());
|
||||
attr.addFlashAttribute("error", "Invalid Credentials");
|
||||
return "redirect:/login";
|
||||
}
|
||||
}
|
||||
return "redirect:/home";
|
||||
}
|
||||
|
||||
@GetMapping("/home")
|
||||
public String getMeHome(Model model) {
|
||||
|
||||
addUserAttributes(model);
|
||||
|
||||
return "comparison/home";
|
||||
}
|
||||
|
||||
@GetMapping("/admin")
|
||||
public String adminOnly(Model model) {
|
||||
addUserAttributes(model);
|
||||
|
||||
Subject currentUser = SecurityUtils.getSubject();
|
||||
if (currentUser.hasRole("ADMIN")) {
|
||||
model.addAttribute("adminContent", "only admin can view this");
|
||||
}
|
||||
return "comparison/home";
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
public String logout() {
|
||||
Subject subject = SecurityUtils.getSubject();
|
||||
subject.logout();
|
||||
return "redirect:/";
|
||||
}
|
||||
|
||||
private void addUserAttributes(Model model) {
|
||||
Subject currentUser = SecurityUtils.getSubject();
|
||||
String permission = "";
|
||||
|
||||
if (currentUser.hasRole("ADMIN")) {
|
||||
model.addAttribute("role", "ADMIN");
|
||||
} else if (currentUser.hasRole("USER")) {
|
||||
model.addAttribute("role", "USER");
|
||||
}
|
||||
|
||||
if (currentUser.isPermitted("READ")) {
|
||||
permission = permission + " READ";
|
||||
}
|
||||
|
||||
if (currentUser.isPermitted("WRITE")) {
|
||||
permission = permission + " WRITE";
|
||||
}
|
||||
model.addAttribute("username", currentUser.getPrincipal());
|
||||
model.addAttribute("permission", permission);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.comparison.shiro.models;
|
||||
|
||||
public class UserCredentials {
|
||||
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "username = " + getUsername();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user