Merge branch 'master' into BAEL-7513-Merge-overlapping-intervals-in-collection

This commit is contained in:
Sam Gardner
2024-03-28 14:36:31 +00:00
1840 changed files with 47641 additions and 5160 deletions
@@ -19,11 +19,6 @@
<artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
@@ -29,11 +29,7 @@
<artifactId>tradukisto</artifactId>
<version>${tradukisto.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- API, java.xml.bind module -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
@@ -7,4 +7,11 @@
- [Rotate Arrays in Java](https://www.baeldung.com/java-rotate-arrays)
- [Find Missing Number From a Given Array in Java](https://www.baeldung.com/java-array-find-missing-number)
- [Calculate Weighted Mean in Java](https://www.baeldung.com/java-compute-weighted-average)
- [Check if Two Strings Are Rotations of Each Other](https://www.baeldung.com/java-string-check-strings-rotations)
- [Find the Largest Prime Under the Given Number in Java](https://www.baeldung.com/java-largest-prime-lower-threshold)
- [Count the Number of Unique Digits in an Integer using Java](https://www.baeldung.com/java-int-count-unique-digits)
- [Generate Juggler Sequence in Java](https://www.baeldung.com/java-generate-juggler-sequence)
- [Finding the Parent of a Node in a Binary Search Tree with Java](https://www.baeldung.com/java-find-parent-node-binary-search-tree)
- [Check if a Number Is a Happy Number in Java](https://www.baeldung.com/java-happy-sad-number-test)
- [Find the Largest Number Possible After Removing k Digits of a Number](https://www.baeldung.com/java-find-largest-number-remove-k-digits)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
@@ -0,0 +1,57 @@
package com.baeldung.algorithms.largestNumberRemovingK;
import java.util.*;
public class LargestNumberRemoveKDigits {
public static int findLargestNumberUsingArithmetic(int num, int k) {
for (int j = 0; j < k; j++) {
int result = 0;
int i = 1;
while (num / i > 0) {
int temp = (num / (i * 10))
* i
+ (num % i);
i *= 10;
result = Math.max(result, temp);
}
num = result;
}
return num;
}
public static int findLargestNumberUsingStack(int num, int k) {
String numStr = Integer.toString(num);
int length = numStr.length();
if (k == length) return 0;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < length; i++) {
char digit = numStr.charAt(i);
while (k > 0 && !stack.isEmpty() && stack.peek() < digit) {
stack.pop();
k--;
}
stack.push(digit);
}
while (k > 0) {
stack.pop();
k--;
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.insert(0, stack.pop());
}
return Integer.parseInt(result.toString());
}
}
@@ -0,0 +1,54 @@
package com.baeldung.algorithms.parentnodebinarytree;
import java.util.Objects;
public class ParentKeeperTreeNode {
int value;
ParentKeeperTreeNode parent;
ParentKeeperTreeNode left;
ParentKeeperTreeNode right;
public ParentKeeperTreeNode(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParentKeeperTreeNode treeNode = (ParentKeeperTreeNode) o;
return value == treeNode.value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
public void insert(int value) {
insert(this, value);
}
private void insert(ParentKeeperTreeNode currentNode, final int value) {
if (currentNode.left == null && value < currentNode.value) {
currentNode.left = new ParentKeeperTreeNode(value);
currentNode.left.parent = currentNode;
return;
}
if (currentNode.right == null && value > currentNode.value) {
currentNode.right = new ParentKeeperTreeNode(value);
currentNode.right.parent = currentNode;
return;
}
if (value > currentNode.value) {
insert(currentNode.right, value);
}
if (value < currentNode.value) {
insert(currentNode.left, value);
}
}
}
@@ -0,0 +1,107 @@
package com.baeldung.algorithms.parentnodebinarytree;
import java.util.Deque;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Objects;
import static java.lang.String.format;
public class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TreeNode treeNode = (TreeNode) o;
return value == treeNode.value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
public void insert(int value) {
insert(this, value);
}
private void insert(TreeNode currentNode, final int value) {
if (currentNode.left == null && value < currentNode.value) {
currentNode.left = new TreeNode(value);
return;
}
if (currentNode.right == null && value > currentNode.value) {
currentNode.right = new TreeNode(value);
return;
}
if (value > currentNode.value) {
insert(currentNode.right, value);
}
if (value < currentNode.value) {
insert(currentNode.left, value);
}
}
public TreeNode parent(int target) throws NoSuchElementException {
return parent(this, new TreeNode(target));
}
private TreeNode parent(TreeNode current, TreeNode target) throws NoSuchElementException {
if (target.equals(current) || current == null) {
throw new NoSuchElementException(format("No parent node found for 'target.value=%s' " +
"The target is not in the tree or the target is the topmost root node.",
target.value));
}
if (target.equals(current.left) || target.equals(current.right)) {
return current;
}
return parent(target.value < current.value ? current.left : current.right, target);
}
public TreeNode iterativeParent(int target) {
return iterativeParent(this, new TreeNode(target));
}
private TreeNode iterativeParent(TreeNode current, TreeNode target) {
Deque<TreeNode> parentCandidates = new LinkedList<>();
String notFoundMessage = format("No parent node found for 'target.value=%s' " +
"The target is not in the tree or the target is the topmost root node.",
target.value);
if (target.equals(current)) {
throw new NoSuchElementException(notFoundMessage);
}
while (current != null || !parentCandidates.isEmpty()) {
while (current != null) {
parentCandidates.addFirst(current);
current = current.left;
}
current = parentCandidates.pollFirst();
if (target.equals(current.left) || target.equals(current.right)) {
return current;
}
current = current.right;
}
throw new NoSuchElementException(notFoundMessage);
}
}
@@ -0,0 +1,123 @@
package com.baeldung.algorithms.stringrotation;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class StringRotation {
public static boolean doubledOriginContainsRotation(String origin, String rotation) {
if (origin.length() == rotation.length()) {
return origin.concat(origin)
.contains(rotation);
}
return false;
}
public static boolean isRotationUsingCommonStartWithOrigin(String origin, String rotation) {
if (origin.length() == rotation.length()) {
List<Integer> indexes = IntStream.range(0, origin.length())
.filter(i -> rotation.charAt(i) == origin.charAt(0))
.boxed()
.collect(Collectors.toList());
for (int startingAt : indexes) {
if (isRotation(startingAt, rotation, origin)) {
return true;
}
}
}
return false;
}
static boolean isRotation(int startingAt, String rotation, String origin) {
for (int i = 0; i < origin.length(); i++) {
if (rotation.charAt((startingAt + i) % origin.length()) != origin.charAt(i)) {
return false;
}
}
return true;
}
public static boolean isRotationUsingQueue(String origin, String rotation) {
if (origin.length() == rotation.length()) {
return checkWithQueue(origin, rotation);
}
return false;
}
static boolean checkWithQueue(String origin, String rotation) {
if (origin.length() == rotation.length()) {
Queue<Character> originQueue = getCharactersQueue(origin);
Queue<Character> rotationQueue = getCharactersQueue(rotation);
int k = rotation.length();
while (k > 0 && null != rotationQueue.peek()) {
k--;
char ch = rotationQueue.peek();
rotationQueue.remove();
rotationQueue.add(ch);
if (rotationQueue.equals(originQueue)) {
return true;
}
}
}
return false;
}
static Queue<Character> getCharactersQueue(String origin) {
return origin.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toCollection(LinkedList::new));
}
public static boolean isRotationUsingSuffixAndPrefix(String origin, String rotation) {
if (origin.length() == rotation.length()) {
return checkPrefixAndSuffix(origin, rotation);
}
return false;
}
static boolean checkPrefixAndSuffix(String origin, String rotation) {
if (origin.length() == rotation.length()) {
for (int i = 0; i < origin.length(); i++) {
if (origin.charAt(i) == rotation.charAt(0)) {
if (checkRotationPrefixWithOriginSuffix(origin, rotation, i)) {
if (checkOriginPrefixWithRotationSuffix(origin, rotation, i))
return true;
}
}
}
}
return false;
}
private static boolean checkRotationPrefixWithOriginSuffix(String origin, String rotation, int i) {
return origin.substring(i)
.equals(rotation.substring(0, origin.length() - i));
}
private static boolean checkOriginPrefixWithRotationSuffix(String origin, String rotation, int i) {
return origin.substring(0, i)
.equals(rotation.substring(origin.length() - i));
}
}
@@ -0,0 +1,36 @@
package com.baeldung.algorithms.uniquedigit;
import java.util.HashSet;
import java.util.Set;
public class UniqueDigitCounter {
public static int countWithSet(int number) {
number = Math.abs(number);
Set<Character> uniqueDigits = new HashSet<>();
String numberStr = String.valueOf(number);
for (char digit : numberStr.toCharArray()) {
uniqueDigits.add(digit);
}
return uniqueDigits.size();
}
public static int countWithBitManipulation(int number) {
if (number == 0) {
return 1;
}
number = Math.abs(number);
int mask = 0;
while (number > 0) {
int digit = number % 10;
mask |= 1 << digit;
number /= 10;
}
return Integer.bitCount(mask);
}
public static long countWithStreamApi(int number) {
return String.valueOf(Math.abs(number)).chars().distinct().count();
}
}
@@ -0,0 +1,82 @@
package com.baeldung.algorithms.happynumber;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
class HappyNumberDecider {
public static boolean isHappyNumber(int n) {
Set<Integer> checkedNumbers = new HashSet<>();
while (true) {
n = sumDigitsSquare(n);
if (n == 1) {
return true;
}
if (checkedNumbers.contains(n)) {
return false;
}
checkedNumbers.add(n);
}
}
public static boolean isHappyNumberFloyd(int n) {
int slow = n;
int fast = n;
do {
slow = sumDigitsSquare(slow);
fast = sumDigitsSquare(sumDigitsSquare(fast));
} while (slow != fast);
return slow == 1;
}
private static int sumDigitsSquare(int n) {
int squareSum = 0;
while (n != 0) {
squareSum += (n % 10) * (n % 10);
n /= 10;
}
return squareSum;
}
}
public class HappyNumberUnitTest {
@Test
void whenUsingIsHappyNumber_thenGetTheExpectedResult() {
assertTrue(HappyNumberDecider.isHappyNumber(7));
assertTrue(HappyNumberDecider.isHappyNumber(10));
assertTrue(HappyNumberDecider.isHappyNumber(13));
assertTrue(HappyNumberDecider.isHappyNumber(19));
assertTrue(HappyNumberDecider.isHappyNumber(23));
assertFalse(HappyNumberDecider.isHappyNumber(4));
assertFalse(HappyNumberDecider.isHappyNumber(6));
assertFalse(HappyNumberDecider.isHappyNumber(11));
assertFalse(HappyNumberDecider.isHappyNumber(15));
assertFalse(HappyNumberDecider.isHappyNumber(20));
}
@Test
void whenUsingIsHappyNumber2_thenGetTheExpectedResult() {
assertTrue(HappyNumberDecider.isHappyNumberFloyd(7));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(10));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(13));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(19));
assertTrue(HappyNumberDecider.isHappyNumberFloyd(23));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(4));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(6));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(11));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(15));
assertFalse(HappyNumberDecider.isHappyNumberFloyd(20));
}
}
@@ -0,0 +1,68 @@
package com.baeldung.algorithms.jugglersequence;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class JugglerSequenceGenerator {
public static List<Integer> byLoop(int n) {
if (n <= 0) {
throw new IllegalArgumentException("The initial integer must be greater than zero.");
}
List<Integer> seq = new ArrayList<>();
int current = n;
seq.add(current);
while (current != 1) {
int next = (int) (Math.sqrt(current) * (current % 2 == 0 ? 1 : current));
seq.add(next);
current = next;
}
return seq;
}
public static List<Integer> byRecursion(int n) {
if (n <= 0) {
throw new IllegalArgumentException("The initial integer must be greater than zero.");
}
List<Integer> seq = new ArrayList<>();
fillSeqRecursively(n, seq);
return seq;
}
private static void fillSeqRecursively(int current, List<Integer> result) {
result.add(current);
if (current == 1) {
return;
}
int next = (int) (Math.sqrt(current) * (current % 2 == 0 ? 1 : current));
fillSeqRecursively(next, result);
}
}
public class JugglerSequenceUnitTest {
@Test
void whenGeneratingJugglerSeqUsingLoop_thenGetTheExpectedResult() {
assertThrows(IllegalArgumentException.class, () -> JugglerSequenceGenerator.byLoop(0));
assertEquals(List.of(3, 5, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byLoop(3));
assertEquals(List.of(4, 2, 1), JugglerSequenceGenerator.byLoop(4));
assertEquals(List.of(9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byLoop(9));
assertEquals(List.of(21, 96, 9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byLoop(21));
assertEquals(List.of(42, 6, 2, 1), JugglerSequenceGenerator.byLoop(42));
}
@Test
void whenGeneratingJugglerSeqUsingRecursion_thenGetTheExpectedResult() {
assertThrows(IllegalArgumentException.class, () -> JugglerSequenceGenerator.byRecursion(0));
assertEquals(List.of(3, 5, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byRecursion(3));
assertEquals(List.of(4, 2, 1), JugglerSequenceGenerator.byRecursion(4));
assertEquals(List.of(9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byRecursion(9));
assertEquals(List.of(21, 96, 9, 27, 140, 11, 36, 6, 2, 1), JugglerSequenceGenerator.byRecursion(21));
assertEquals(List.of(42, 6, 2, 1), JugglerSequenceGenerator.byRecursion(42));
}
}
@@ -0,0 +1,25 @@
package com.baeldung.algorithms.largestNumberRemovingK;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class LargestNumberRemoveKDigitsUnitTest {
@Test
public void givenNumber_UsingArithmeticRemoveKDigits_thenReturnLargestNumber(){
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(9461, 1), 961);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(463, 2), 6);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(98625410, 6), 98);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(20, 2), 0);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingArithmetic(98989, 4), 9);
}
@Test
public void givenNumber_UsingStackRemoveKDigits_thenReturnLargestNumber(){
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(9461, 1), 961);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(463, 2), 6);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(98625410, 6), 98);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(20, 2), 0);
Assertions.assertEquals(LargestNumberRemoveKDigits.findLargestNumberUsingStack(98989, 4), 9);
}
}
@@ -0,0 +1,83 @@
package com.baeldung.algorithms.parentnodebinarytree;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.NoSuchElementException;
import static org.junit.jupiter.api.Assertions.*;
class BinaryTreeParentNodeFinderUnitTest {
private TreeNode subject;
@BeforeEach
void setUp() {
subject = new TreeNode(8);
subject.insert(5);
subject.insert(12);
subject.insert(3);
subject.insert(7);
subject.insert(1);
subject.insert(4);
subject.insert(11);
subject.insert(14);
subject.insert(13);
subject.insert(16);
}
@Test
void givenBinaryTree_whenFindParentNode_thenReturnCorrectParentNode() {
assertEquals(8, subject.parent(5).value);
assertEquals(5, subject.parent(3).value);
assertEquals(5, subject.parent(7).value);
assertEquals(3, subject.parent(4).value);
assertEquals(3, subject.parent(1).value);
assertEquals(8, subject.parent(12).value);
assertEquals(12, subject.parent(14).value);
assertEquals(12, subject.parent(11).value);
assertEquals(14, subject.parent(16).value);
assertEquals(14, subject.parent(13).value);
assertThrows(NoSuchElementException.class, () -> subject.parent(1231));
assertThrows(NoSuchElementException.class, () -> subject.parent(8));
}
@Test
void givenBinaryTree_whenFindParentNodeIteratively_thenReturnCorrectParentNode() {
assertEquals(8, subject.iterativeParent(5).value);
assertEquals(5, subject.iterativeParent(3).value);
assertEquals(5, subject.iterativeParent(7).value);
assertEquals(3, subject.iterativeParent(4).value);
assertEquals(3, subject.iterativeParent(1).value);
assertEquals(8, subject.iterativeParent(12).value);
assertEquals(12, subject.iterativeParent(14).value);
assertEquals(12, subject.iterativeParent(11).value);
assertEquals(14, subject.iterativeParent(16).value);
assertEquals(14, subject.iterativeParent(13).value);
assertThrows(NoSuchElementException.class, () -> subject.iterativeParent(1231));
assertThrows(NoSuchElementException.class, () -> subject.iterativeParent(8));
}
@Test
void givenParentKeeperBinaryTree_whenGetParent_thenReturnCorrectParent() {
ParentKeeperTreeNode subject = new ParentKeeperTreeNode(8);
subject.insert(5);
subject.insert(12);
subject.insert(3);
subject.insert(7);
subject.insert(1);
subject.insert(4);
subject.insert(11);
subject.insert(14);
subject.insert(13);
subject.insert(16);
assertNull(subject.parent);
assertEquals(8, subject.left.parent.value);
assertEquals(8, subject.right.parent.value);
assertEquals(5, subject.left.left.parent.value);
assertEquals(5, subject.left.right.parent.value);
// tests for other nodes
}
}
@@ -0,0 +1,61 @@
package com.baeldung.algorithms.stringrotation;
import static com.baeldung.algorithms.stringrotation.StringRotation.doubledOriginContainsRotation;
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingCommonStartWithOrigin;
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingQueue;
import static com.baeldung.algorithms.stringrotation.StringRotation.isRotationUsingSuffixAndPrefix;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class StringRotationUnitTest {
@Test
void givenOriginAndRotationInput_whenCheckIfOriginContainsRotation_thenIsRotation() {
assertTrue(doubledOriginContainsRotation("abcd", "cdab"));
assertTrue(doubledOriginContainsRotation("abcd", "abcd"));
}
@Test
void givenOriginAndRotationInput_whenCheckIfOriginContainsRotation_thenNoRotation() {
assertFalse(doubledOriginContainsRotation("abcd", "bbbb"));
assertFalse(doubledOriginContainsRotation("abcd", "abcde"));
}
@Test
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenIsRotation() {
assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "cdab"));
assertTrue(isRotationUsingCommonStartWithOrigin("abcd", "abcd"));
}
@Test
void givenOriginAndRotationInput_whenCheckingCommonStartWithOrigin_thenNoRotation() {
assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "bbbb"));
assertFalse(isRotationUsingCommonStartWithOrigin("abcd", "abcde"));
}
@Test
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenIsRotation() {
assertTrue(isRotationUsingQueue("abcd", "cdab"));
assertTrue(isRotationUsingQueue("abcd", "abcd"));
}
@Test
void givenOriginAndRotationInput_whenCheckingUsingQueues_thenNoRotation() {
assertFalse(isRotationUsingQueue("abcd", "bbbb"));
assertFalse(isRotationUsingQueue("abcd", "abcde"));
}
@Test
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenIsRotation() {
assertTrue(isRotationUsingSuffixAndPrefix("abcd", "cdab"));
assertTrue(isRotationUsingSuffixAndPrefix("abcd", "abcd"));
}
@Test
void givenOriginAndRotationInput_whenCheckingUsingSuffixAndPrefix_thenNoRotation() {
assertFalse(isRotationUsingSuffixAndPrefix("abcd", "bbbb"));
assertFalse(isRotationUsingSuffixAndPrefix("abcd", "abcde"));
}
}
@@ -0,0 +1,38 @@
package com.baeldung.algorithms.uniquedigit;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class UniqueDigitCounterUnitTest {
@Test
public void givenNotNegativeNumber_whenCountUniqueDigits_thenCorrectCount() {
assertEquals(3, UniqueDigitCounter.countWithSet(122333));
assertEquals(1, UniqueDigitCounter.countWithSet(0));
assertEquals(2, UniqueDigitCounter.countWithSet(101));
assertEquals(3, UniqueDigitCounter.countWithBitManipulation(122333));
assertEquals(1, UniqueDigitCounter.countWithBitManipulation(0));
assertEquals(2, UniqueDigitCounter.countWithBitManipulation(101));
assertEquals(3, UniqueDigitCounter.countWithStreamApi(122333));
assertEquals(1, UniqueDigitCounter.countWithStreamApi(0));
assertEquals(2, UniqueDigitCounter.countWithStreamApi(101));
}
@Test
public void givenNegativeNumber_whenCountUniqueDigits_thenCorrectCount() {
assertEquals(3, UniqueDigitCounter.countWithSet(-122333));
assertEquals(3, UniqueDigitCounter.countWithBitManipulation(-122333));
assertEquals(3, UniqueDigitCounter.countWithStreamApi(-122333));
}
@Test
public void givenLargeNumber_whenCountUniqueDigits_thenCorrectCount() {
assertEquals(2, UniqueDigitCounter.countWithSet(1000000000));
assertEquals(2, UniqueDigitCounter.countWithBitManipulation(1000000000));
assertEquals(2, UniqueDigitCounter.countWithStreamApi(1000000000));
}
}
@@ -0,0 +1,2 @@
### Relevant Articles:
- [Vigenère Cipher in Java](https://www.baeldung.com/java-vigenere-cipher)
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>algorithms-miscellaneous-8</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>algorithms-miscellaneous-8</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
</project>
@@ -0,0 +1,69 @@
package com.baeldung.algorithms.vigenere;
public class VigenereCipher {
private final String characters;
public VigenereCipher() {
this("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
public VigenereCipher(String characters) {
this.characters = characters;
}
public String encode(String input, String key) {
String result = "";
int keyPosition = 0;
for (char c : input.toCharArray()) {
char k = key.charAt(keyPosition % key.length());
int charIndex = characters.indexOf(c);
int keyIndex = characters.indexOf(k);
if (charIndex >= 0) {
if (keyIndex >= 0) {
int newCharIndex = (charIndex + keyIndex + 1) % characters.length();
c = characters.charAt(newCharIndex);
}
keyPosition++;
}
result += c;
}
return result;
}
public String decode(String input, String key) {
String result = "";
int keyPosition = 0;
for (char c : input.toCharArray()) {
char k = key.charAt(keyPosition % key.length());
int charIndex = characters.indexOf(c);
int keyIndex = characters.indexOf(k);
if (charIndex >= 0) {
if (keyIndex >= 0) {
int newCharIndex = charIndex - keyIndex - 1;
if (newCharIndex < 0) {
newCharIndex = characters.length() + newCharIndex;
}
c = characters.charAt(newCharIndex);
}
keyPosition++;
}
result += c;
}
return result;
}
}
@@ -0,0 +1,76 @@
package com.baeldung.algorithms.vigenere;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class VigenereCipherUnitTest {
@Test
void encodeBaeldung() {
VigenereCipher cipher = new VigenereCipher();
String output = cipher.encode("BAELDUNG", "HELLO");
Assertions.assertEquals("JFQXSCSS", output);
}
@Test
void encodeBaeldungMixedCharacters() {
VigenereCipher cipher = new VigenereCipher("JQFVHPWORZSLNMKYCGBUXIEDTA");
String output = cipher.encode("BAELDUNG", "HELLO");
Assertions.assertEquals("DERDPTZV", output);
}
@Test
void encodeArticleTitle() {
VigenereCipher cipher = new VigenereCipher();
String output = cipher.encode("VIGENERE CIPHER IN JAVA", "BAELDUNG");
Assertions.assertEquals("XJLQRZFL EJUTIM WU LBAM", output);
}
@Test
void encodeArticleTitleMoreCharacters() {
VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ ");
String output = cipher.encode("VIGENERE CIPHER IN JAVA", "BAELDUNG");
Assertions.assertEquals("XJLQRZELBDNALZEGKOEVEPO", output);
}
@Test
void decodeBaeldung() {
VigenereCipher cipher = new VigenereCipher();
String output = cipher.decode("JFQXSCSS", "HELLO");
Assertions.assertEquals("BAELDUNG", output);
}
@Test
void decodeBaeldungMixedCharacters() {
VigenereCipher cipher = new VigenereCipher("JQFVHPWORZSLNMKYCGBUXIEDTA");
String output = cipher.decode("DERDPTZV", "HELLO");
Assertions.assertEquals("BAELDUNG", output);
}
@Test
void decodeArticleTitleMoreCharacters() {
VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ ");
String output = cipher.decode("XJLQRZELBDNALZEGKOEVEPO", "BAELDUNG");
Assertions.assertEquals("VIGENERE CIPHER IN JAVA", output);
}
@Test
void encodeDecodeBaeldung() {
VigenereCipher cipher = new VigenereCipher();
String input = "BAELDUNG";
String key = "HELLO";
String encoded = cipher.encode(input, key);
String decoded = cipher.decode(encoded, key);
Assertions.assertEquals(input, decoded);
}
}
+2 -1
View File
@@ -22,6 +22,7 @@
<module>algorithms-miscellaneous-5</module>
<module>algorithms-miscellaneous-6</module>
<module>algorithms-miscellaneous-7</module>
<module>algorithms-miscellaneous-8</module>
<module>algorithms-searching</module>
<module>algorithms-sorting</module>
<module>algorithms-sorting-2</module>
@@ -34,4 +35,4 @@
<tradukisto.version>1.0.1</tradukisto.version>
</properties>
</project>
</project>