JAVA-12097: renamed algorithms-module to algorithms-modules
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
package com.baeldung.algorithms.analysis;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class AnalysisRunnerLiveTest {
|
||||
|
||||
int n = 10;
|
||||
int total = 0;
|
||||
|
||||
@Test
|
||||
public void whenConstantComplexity_thenConstantRuntime() {
|
||||
|
||||
System.out.println("**** n = " + n + " ****");
|
||||
System.out.println();
|
||||
|
||||
// Constant Time
|
||||
System.out.println("**** Constant time ****");
|
||||
|
||||
System.out.println("Hey - your input is: " + n);
|
||||
System.out.println("Running time not dependent on input size!");
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLogarithmicComplexity_thenLogarithmicRuntime() {
|
||||
// Logarithmic Time
|
||||
System.out.println("**** Logarithmic Time ****");
|
||||
for (int i = 1; i < n; i = i * 2) {
|
||||
// System.out.println("Hey - I'm busy looking at: " + i);
|
||||
total++;
|
||||
}
|
||||
System.out.println("Total amount of times run: " + total);
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLinearComplexity_thenLinearRuntime() {
|
||||
// Linear Time
|
||||
System.out.println("**** Linear Time ****");
|
||||
for (int i = 0; i < n; i++) {
|
||||
// System.out.println("Hey - I'm busy looking at: " + i);
|
||||
total++;
|
||||
}
|
||||
System.out.println("Total amount of times run: " + total);
|
||||
System.out.println();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNLogNComplexity_thenNLogNRuntime() {
|
||||
// N Log N Time
|
||||
System.out.println("**** nlogn Time ****");
|
||||
total = 0;
|
||||
for (
|
||||
|
||||
int i = 1; i <= n; i++) {
|
||||
for (int j = 1; j < n; j = j * 2) {
|
||||
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
|
||||
total++;
|
||||
}
|
||||
}
|
||||
System.out.println("Total amount of times run: " + total);
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenQuadraticComplexity_thenQuadraticRuntime() {
|
||||
// Quadratic Time
|
||||
System.out.println("**** Quadratic Time ****");
|
||||
total = 0;
|
||||
for (
|
||||
|
||||
int i = 1; i <= n; i++) {
|
||||
for (int j = 1; j <= n; j++) {
|
||||
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
|
||||
total++;
|
||||
}
|
||||
}
|
||||
System.out.println("Total amount of times run: " + total);
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCubicComplexity_thenCubicRuntime() {
|
||||
// Cubic Time
|
||||
System.out.println("**** Cubic Time ****");
|
||||
total = 0;
|
||||
for (
|
||||
|
||||
int i = 1; i <= n; i++) {
|
||||
for (int j = 1; j <= n; j++) {
|
||||
for (int k = 1; k <= n; k++) {
|
||||
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j + " and " + k);
|
||||
total++;
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("Total amount of times run: " + total);
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenExponentialComplexity_thenExponentialRuntime() {
|
||||
// Exponential Time
|
||||
System.out.println("**** Exponential Time ****");
|
||||
total = 0;
|
||||
for (
|
||||
|
||||
int i = 1; i <= Math.pow(2, n); i++) {
|
||||
// System.out.println("Hey - I'm busy looking at: " + i);
|
||||
total++;
|
||||
}
|
||||
System.out.println("Total amount of times run: " + total);
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFactorialComplexity_thenFactorialRuntime() {
|
||||
// Factorial Time
|
||||
System.out.println("**** Factorial Time ****");
|
||||
total = 0;
|
||||
for (
|
||||
|
||||
int i = 1; i <=
|
||||
|
||||
factorial(n); i++) {
|
||||
// System.out.println("Hey - I'm busy looking at: " + i);
|
||||
total++;
|
||||
}
|
||||
System.out.println("Total amount of times run: " + total);
|
||||
}
|
||||
|
||||
static int factorial(int n) {
|
||||
if (n == 0 || n == 1)
|
||||
return 1;
|
||||
else
|
||||
return n * factorial(n - 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.baeldung.algorithms.checksortedlist;
|
||||
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingComparators;
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingIterativeApproach;
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingOrderingClass;
|
||||
import static com.baeldung.algorithms.checksortedlist.SortedListChecker.checkIfSortedUsingRecursion;
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SortedListCheckerUnitTest {
|
||||
|
||||
private List<String> sortedListOfString;
|
||||
private List<String> unsortedListOfString;
|
||||
private List<String> singletonList;
|
||||
|
||||
private List<Employee> employeesSortedByName;
|
||||
private List<Employee> employeesNotSortedByName;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY");
|
||||
unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada");
|
||||
singletonList = Collections.singletonList("NY");
|
||||
|
||||
employeesSortedByName = asList(new Employee(1L, "John"), new Employee(2L, "Kevin"), new Employee(3L, "Mike"));
|
||||
employeesNotSortedByName = asList(new Employee(1L, "Kevin"), new Employee(2L, "John"), new Employee(3L, "Mike"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingRecursion_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSingleElementList_whenUsingRecursion_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingRecursion_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() {
|
||||
assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() {
|
||||
assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.algorithms.enumstatemachine;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LeaveRequestStateUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
|
||||
LeaveRequestState state = LeaveRequestState.Escalated;
|
||||
|
||||
assertEquals(state.responsiblePerson(), "Team Leader");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
|
||||
LeaveRequestState state = LeaveRequestState.Approved;
|
||||
|
||||
assertEquals(state.responsiblePerson(), "Department Manager");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
|
||||
LeaveRequestState state = LeaveRequestState.Submitted;
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Escalated);
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Approved);
|
||||
|
||||
state = state.nextState();
|
||||
assertEquals(state, LeaveRequestState.Approved);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.algorithms.graphcycledetection;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.graphcycledetection.domain.Graph;
|
||||
import com.baeldung.algorithms.graphcycledetection.domain.Vertex;
|
||||
|
||||
public class GraphCycleDetectionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenGraph_whenCycleExists_thenReturnTrue() {
|
||||
|
||||
Vertex vertexA = new Vertex("A");
|
||||
Vertex vertexB = new Vertex("B");
|
||||
Vertex vertexC = new Vertex("C");
|
||||
Vertex vertexD = new Vertex("D");
|
||||
|
||||
Graph graph = new Graph();
|
||||
graph.addVertex(vertexA);
|
||||
graph.addVertex(vertexB);
|
||||
graph.addVertex(vertexC);
|
||||
graph.addVertex(vertexD);
|
||||
|
||||
graph.addEdge(vertexA, vertexB);
|
||||
graph.addEdge(vertexB, vertexC);
|
||||
graph.addEdge(vertexC, vertexA);
|
||||
graph.addEdge(vertexD, vertexC);
|
||||
|
||||
assertTrue(graph.hasCycle());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGraph_whenNoCycleExists_thenReturnFalse() {
|
||||
|
||||
Vertex vertexA = new Vertex("A");
|
||||
Vertex vertexB = new Vertex("B");
|
||||
Vertex vertexC = new Vertex("C");
|
||||
Vertex vertexD = new Vertex("D");
|
||||
|
||||
Graph graph = new Graph();
|
||||
graph.addVertex(vertexA);
|
||||
graph.addVertex(vertexB);
|
||||
graph.addVertex(vertexC);
|
||||
graph.addVertex(vertexD);
|
||||
|
||||
graph.addEdge(vertexA, vertexB);
|
||||
graph.addEdge(vertexB, vertexC);
|
||||
graph.addEdge(vertexA, vertexC);
|
||||
graph.addEdge(vertexD, vertexC);
|
||||
|
||||
assertFalse(graph.hasCycle());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.baeldung.algorithms.printtriangles;
|
||||
|
||||
import junitparams.JUnitParamsRunner;
|
||||
import junitparams.Parameters;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(JUnitParamsRunner.class)
|
||||
public class PrintTriangleExamplesUnitTest {
|
||||
|
||||
private static Object[][] rightTriangles() {
|
||||
String expected0 = "";
|
||||
|
||||
String expected2 = "*" + System.lineSeparator()
|
||||
+ "**" + System.lineSeparator();
|
||||
|
||||
String expected5 = "*" + System.lineSeparator()
|
||||
+ "**" + System.lineSeparator()
|
||||
+ "***" + System.lineSeparator()
|
||||
+ "****" + System.lineSeparator()
|
||||
+ "*****" + System.lineSeparator();
|
||||
|
||||
String expected7 = "*" + System.lineSeparator()
|
||||
+ "**" + System.lineSeparator()
|
||||
+ "***" + System.lineSeparator()
|
||||
+ "****" + System.lineSeparator()
|
||||
+ "*****" + System.lineSeparator()
|
||||
+ "******" + System.lineSeparator()
|
||||
+ "*******" + System.lineSeparator();
|
||||
|
||||
return new Object[][] {
|
||||
{ 0, expected0 },
|
||||
{ 2, expected2 },
|
||||
{ 5, expected5 },
|
||||
{ 7, expected7 }
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "rightTriangles")
|
||||
public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printARightTriangle(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
private static Object[][] isoscelesTriangles() {
|
||||
String expected0 = "";
|
||||
|
||||
String expected2 = " *" + System.lineSeparator()
|
||||
+ "***" + System.lineSeparator();
|
||||
|
||||
String expected5 = " *" + System.lineSeparator()
|
||||
+ " ***" + System.lineSeparator()
|
||||
+ " *****" + System.lineSeparator()
|
||||
+ " *******" + System.lineSeparator()
|
||||
+ "*********" + System.lineSeparator();
|
||||
|
||||
String expected7 = " *" + System.lineSeparator()
|
||||
+ " ***" + System.lineSeparator()
|
||||
+ " *****" + System.lineSeparator()
|
||||
+ " *******" + System.lineSeparator()
|
||||
+ " *********" + System.lineSeparator()
|
||||
+ " ***********" + System.lineSeparator()
|
||||
+ "*************" + System.lineSeparator();
|
||||
|
||||
return new Object[][] {
|
||||
{ 0, expected0 },
|
||||
{ 2, expected2 },
|
||||
{ 5, expected5 },
|
||||
{ 7, expected7 }
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "isoscelesTriangles")
|
||||
public void whenPrintAnIsoscelesTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printAnIsoscelesTriangle(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "isoscelesTriangles")
|
||||
public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Parameters(method = "isoscelesTriangles")
|
||||
public void whenPrintAnIsoscelesTriangleUsingSubstringIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
|
||||
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingSubstring(nrOfRows);
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.algorithms.romannumerals;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RomanArabicConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void given2018Roman_WhenConvertingToArabic_ThenReturn2018() {
|
||||
|
||||
String roman2018 = "MMXVIII";
|
||||
|
||||
int result = RomanArabicConverter.romanToArabic(roman2018);
|
||||
|
||||
assertThat(result).isEqualTo(2018);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() {
|
||||
|
||||
int arabic1999 = 1999;
|
||||
|
||||
String result = RomanArabicConverter.arabicToRoman(arabic1999);
|
||||
|
||||
assertThat(result).isEqualTo("MCMXCIX");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.algorithms.twopointertechnique;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LinkedListFindMiddleUnitTest {
|
||||
|
||||
LinkedListFindMiddle linkedListFindMiddle = new LinkedListFindMiddle();
|
||||
|
||||
@Test
|
||||
public void givenLinkedListOfMyNodes_whenLinkedListFindMiddle_thenCorrect() {
|
||||
|
||||
MyNode<String> head = createNodesList(8);
|
||||
|
||||
assertThat(linkedListFindMiddle.findMiddle(head)).isEqualTo("4");
|
||||
|
||||
head = createNodesList(9);
|
||||
|
||||
assertThat(linkedListFindMiddle.findMiddle(head)).isEqualTo("5");
|
||||
}
|
||||
|
||||
private static MyNode<String> createNodesList(int n) {
|
||||
|
||||
MyNode<String> head = new MyNode<String>("1");
|
||||
MyNode<String> current = head;
|
||||
|
||||
for (int i = 2; i <= n; i++) {
|
||||
MyNode<String> newNode = new MyNode<String>(String.valueOf(i));
|
||||
current.setNext(newNode);
|
||||
current = newNode;
|
||||
}
|
||||
|
||||
return head;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.algorithms.twopointertechnique;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RotateArrayUnitTest {
|
||||
|
||||
private RotateArray rotateArray = new RotateArray();
|
||||
|
||||
private int[] inputArray;
|
||||
|
||||
private int step;
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegers_whenRotateKsteps_thenCorrect() {
|
||||
|
||||
inputArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
|
||||
step = 4;
|
||||
|
||||
rotateArray.rotate(inputArray, step);
|
||||
|
||||
assertThat(inputArray).containsExactly(new int[] { 4, 5, 6, 7, 1, 2, 3 });
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.algorithms.twopointertechnique;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class TwoSumUnitTest {
|
||||
|
||||
private TwoSum twoSum = new TwoSum();
|
||||
|
||||
private int[] sortedArray;
|
||||
|
||||
private int targetValue;
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairExists() {
|
||||
|
||||
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
||||
|
||||
targetValue = 12;
|
||||
|
||||
assertTrue(twoSum.twoSumSlow(sortedArray, targetValue));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairDoesNotExists() {
|
||||
|
||||
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
||||
|
||||
targetValue = 20;
|
||||
|
||||
assertFalse(twoSum.twoSumSlow(sortedArray, targetValue));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenTwoSum_thenPairExists() {
|
||||
|
||||
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
||||
|
||||
targetValue = 12;
|
||||
|
||||
assertTrue(twoSum.twoSum(sortedArray, targetValue));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenASortedArrayOfIntegers_whenTwoSum_thenPairDoesNotExists() {
|
||||
|
||||
sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
|
||||
|
||||
targetValue = 20;
|
||||
|
||||
assertFalse(twoSum.twoSum(sortedArray, targetValue));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.counter;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
|
||||
import com.baeldung.counter.CounterUtil.MutableInteger;
|
||||
|
||||
@Fork(value = 1, warmups = 3)
|
||||
@BenchmarkMode(Mode.All)
|
||||
public class CounterStatistics {
|
||||
|
||||
private static final Map<String, Integer> counterMap = new HashMap<>();
|
||||
private static final Map<String, MutableInteger> counterWithMutableIntMap = new HashMap<>();
|
||||
private static final Map<String, int[]> counterWithIntArrayMap = new HashMap<>();
|
||||
private static final Map<String, Long> counterWithLongWrapperMap = new HashMap<>();
|
||||
private static final Map<String, Long> counterWithLongWrapperStreamMap = new HashMap<>();
|
||||
|
||||
static {
|
||||
CounterUtil.COUNTRY_NAMES = new String[10000];
|
||||
final String prefix = "NewString";
|
||||
Random random = new Random();
|
||||
for (int i=0; i<10000; i++) {
|
||||
CounterUtil.COUNTRY_NAMES[i] = new String(prefix + random.nextInt(1000));
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void wrapperAsCounter() {
|
||||
CounterUtil.counterWithWrapperObject(counterMap);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void lambdaExpressionWithWrapper() {
|
||||
CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void parallelStreamWithWrapper() {
|
||||
CounterUtil.counterWithParallelStreamAndWrapper(counterWithLongWrapperStreamMap);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void mutableIntegerAsCounter() {
|
||||
CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void primitiveArrayAsCounter() {
|
||||
CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.counter;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.counter.CounterUtil.MutableInteger;
|
||||
|
||||
public class CounterUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenMapWithWrapperAsCounter_runsSuccessfully() {
|
||||
Map<String, Integer> counterMap = new HashMap<>();
|
||||
CounterUtil.counterWithWrapperObject(counterMap);
|
||||
|
||||
assertEquals(3, counterMap.get("China")
|
||||
.intValue());
|
||||
assertEquals(2, counterMap.get("India")
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
|
||||
Map<String, Long> counterMap = new HashMap<>();
|
||||
CounterUtil.counterWithLambdaAndWrapper(counterMap);
|
||||
|
||||
assertEquals(3l, counterMap.get("China")
|
||||
.longValue());
|
||||
assertEquals(2l, counterMap.get("India")
|
||||
.longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
|
||||
Map<String, MutableInteger> counterMap = new HashMap<>();
|
||||
CounterUtil.counterWithMutableInteger(counterMap);
|
||||
assertEquals(3, counterMap.get("China")
|
||||
.getCount());
|
||||
assertEquals(2, counterMap.get("India")
|
||||
.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapWithPrimitiveArray_runsSuccessfully() {
|
||||
Map<String, int[]> counterMap = new HashMap<>();
|
||||
CounterUtil.counterWithPrimitiveArray(counterMap);
|
||||
assertEquals(3, counterMap.get("China")[0]);
|
||||
assertEquals(2, counterMap.get("India")[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.counter;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class CounterUtil {
|
||||
|
||||
public static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
|
||||
|
||||
public static void counterWithWrapperObject(Map<String, Integer> counterMap) {
|
||||
for (String country : COUNTRY_NAMES) {
|
||||
counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static void counterWithLambdaAndWrapper(Map<String, Long> counterMap) {
|
||||
Stream.of(COUNTRY_NAMES)
|
||||
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
|
||||
}
|
||||
|
||||
public static void counterWithParallelStreamAndWrapper(Map<String, Long> counterMap) {
|
||||
Stream.of(COUNTRY_NAMES)
|
||||
.parallel()
|
||||
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
|
||||
}
|
||||
|
||||
public static class MutableInteger {
|
||||
int count;
|
||||
|
||||
public MutableInteger(int count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
this.count++;
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return this.count;
|
||||
}
|
||||
}
|
||||
|
||||
public static void counterWithMutableInteger(Map<String, MutableInteger> counterMap) {
|
||||
for (String country : COUNTRY_NAMES) {
|
||||
counterMap.compute(country, (k, v) -> v == null ? new MutableInteger(0) : v)
|
||||
.increment();
|
||||
}
|
||||
}
|
||||
|
||||
public static void counterWithPrimitiveArray(Map<String, int[]> counterMap) {
|
||||
for (String country : COUNTRY_NAMES) {
|
||||
counterMap.compute(country, (k, v) -> v == null ? new int[] { 0 } : v)[0]++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.folding;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FoldingHashUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int value = hasher.hash("Java language", 2, 100_000);
|
||||
assertEquals(value, 48933);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int java = hasher.hash("Java language", 2, 100_000);
|
||||
final int vaja = hasher.hash("vaJa language", 2, 100_000);
|
||||
assertTrue(java == vaja);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int[] value = hasher.extract(new int[] { 5 }, 0, 2);
|
||||
assertArrayEquals(new int[] { 5 }, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3);
|
||||
assertArrayEquals(new int[] { 1, 2, 3 }, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2);
|
||||
assertArrayEquals(new int[] { 2, 3 }, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception {
|
||||
final FoldingHash hasher = new FoldingHash();
|
||||
final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000);
|
||||
assertArrayEquals(new int[] { 3, 4, 5 }, value);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user