Skip to content

Commit 2f4da6e

Browse files
authored
Merge branch 'master' into SMJI/stack/min_max_const_time
2 parents dc73e5f + c56d282 commit 2f4da6e

17 files changed

+478
-58
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -982,6 +982,7 @@
982982
* [JosephusProblemTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/JosephusProblemTest.java)
983983
* [KaprekarNumbersTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java)
984984
* [KaratsubaMultiplicationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/KaratsubaMultiplicationTest.java)
985+
* [KrishnamurthyNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/KrishnamurthyNumberTest.java)
985986
* [LeastCommonMultipleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java)
986987
* [LeonardoNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java)
987988
* [LiouvilleLambdaFunctionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java)

pom.xml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
<dependency>
2121
<groupId>org.junit</groupId>
2222
<artifactId>junit-bom</artifactId>
23-
<version>5.11.2</version>
23+
<version>5.11.3</version>
2424
<type>pom</type>
2525
<scope>import</scope>
2626
</dependency>
@@ -31,7 +31,7 @@
3131
<dependency>
3232
<groupId>org.junit.jupiter</groupId>
3333
<artifactId>junit-jupiter</artifactId>
34-
<version>5.11.2</version>
34+
<version>5.11.3</version>
3535
<scope>test</scope>
3636
</dependency>
3737
<dependency>
@@ -51,7 +51,7 @@
5151
<dependency>
5252
<groupId>org.junit.jupiter</groupId>
5353
<artifactId>junit-jupiter-api</artifactId>
54-
<version>5.11.2</version>
54+
<version>5.11.3</version>
5555
<scope>test</scope>
5656
</dependency>
5757
<dependency>
@@ -132,7 +132,7 @@
132132
<plugin>
133133
<groupId>com.github.spotbugs</groupId>
134134
<artifactId>spotbugs-maven-plugin</artifactId>
135-
<version>4.8.6.4</version>
135+
<version>4.8.6.5</version>
136136
<configuration>
137137
<excludeFilterFile>spotbugs-exclude.xml</excludeFilterFile>
138138
<includeTests>true</includeTests>
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.thealgorithms.ciphers;
2+
3+
import java.math.BigInteger;
4+
5+
public final class DiffieHellman {
6+
7+
private final BigInteger base;
8+
private final BigInteger secret;
9+
private final BigInteger prime;
10+
11+
// Constructor to initialize base, secret, and prime
12+
public DiffieHellman(BigInteger base, BigInteger secret, BigInteger prime) {
13+
// Check for non-null and positive values
14+
if (base == null || secret == null || prime == null || base.signum() <= 0 || secret.signum() <= 0 || prime.signum() <= 0) {
15+
throw new IllegalArgumentException("Base, secret, and prime must be non-null and positive values.");
16+
}
17+
this.base = base;
18+
this.secret = secret;
19+
this.prime = prime;
20+
}
21+
22+
// Method to calculate public value (g^x mod p)
23+
public BigInteger calculatePublicValue() {
24+
// Returns g^x mod p
25+
return base.modPow(secret, prime);
26+
}
27+
28+
// Method to calculate the shared secret key (otherPublic^secret mod p)
29+
public BigInteger calculateSharedSecret(BigInteger otherPublicValue) {
30+
if (otherPublicValue == null || otherPublicValue.signum() <= 0) {
31+
throw new IllegalArgumentException("Other public value must be non-null and positive.");
32+
}
33+
// Returns b^x mod p or a^y mod p
34+
return otherPublicValue.modPow(secret, prime);
35+
}
36+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.thealgorithms.ciphers;
2+
3+
public final class MonoAlphabetic {
4+
5+
private MonoAlphabetic() {
6+
throw new UnsupportedOperationException("Utility class");
7+
}
8+
9+
// Encryption method
10+
public static String encrypt(String data, String key) {
11+
if (!data.matches("[A-Z]+")) {
12+
throw new IllegalArgumentException("Input data contains invalid characters. Only uppercase A-Z are allowed.");
13+
}
14+
StringBuilder sb = new StringBuilder();
15+
16+
// Encrypt each character
17+
for (char c : data.toCharArray()) {
18+
int idx = charToPos(c); // Get the index of the character
19+
sb.append(key.charAt(idx)); // Map to the corresponding character in the key
20+
}
21+
return sb.toString();
22+
}
23+
24+
// Decryption method
25+
public static String decrypt(String data, String key) {
26+
StringBuilder sb = new StringBuilder();
27+
28+
// Decrypt each character
29+
for (char c : data.toCharArray()) {
30+
int idx = key.indexOf(c); // Find the index of the character in the key
31+
if (idx == -1) {
32+
throw new IllegalArgumentException("Input data contains invalid characters.");
33+
}
34+
sb.append(posToChar(idx)); // Convert the index back to the original character
35+
}
36+
return sb.toString();
37+
}
38+
39+
// Helper method: Convert a character to its position in the alphabet
40+
private static int charToPos(char c) {
41+
return c - 'A'; // Subtract 'A' to get position (0 for A, 1 for B, etc.)
42+
}
43+
44+
// Helper method: Convert a position in the alphabet to a character
45+
private static char posToChar(int pos) {
46+
return (char) (pos + 'A'); // Add 'A' to convert position back to character
47+
}
48+
}

src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ public static int cutRod(int[] price, int n) {
2222
if (price == null || price.length == 0) {
2323
throw new IllegalArgumentException("Price array cannot be null or empty.");
2424
}
25+
if (n < 0) {
26+
throw new IllegalArgumentException("Rod length cannot be negative.");
27+
}
28+
2529
// Create an array to store the maximum obtainable values for each rod length.
2630
int[] val = new int[n + 1];
2731
val[0] = 0;

src/main/java/com/thealgorithms/maths/GCD.java

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,23 @@
11
package com.thealgorithms.maths;
22

33
/**
4-
* This is Euclid's algorithm, used to find the greatest common
5-
* denominator Override function name gcd
4+
* This class provides methods to compute the Greatest Common Divisor (GCD) of two or more integers.
65
*
6+
* The Greatest Common Divisor (GCD) of two or more integers is the largest positive integer that divides each of the integers without leaving a remainder.
7+
*
8+
* The GCD can be computed using the Euclidean algorithm, which is based on the principle that the GCD of two numbers also divides their difference.
9+
*
10+
* For more information, refer to the
11+
* <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor">Greatest Common Divisor</a> Wikipedia page.
12+
*
13+
* <b>Example usage:</b>
14+
* <pre>
15+
* int result1 = GCD.gcd(48, 18);
16+
* System.out.println("GCD of 48 and 18: " + result1); // Output: 6
17+
*
18+
* int result2 = GCD.gcd(48, 18, 30);
19+
* System.out.println("GCD of 48, 18, and 30: " + result2); // Output: 6
20+
* </pre>
721
* @author Oskar Enmalm 3/10/17
822
*/
923
public final class GCD {
@@ -40,20 +54,12 @@ public static int gcd(int num1, int num2) {
4054
* @param numbers the input array
4155
* @return gcd of all of the numbers in the input array
4256
*/
43-
public static int gcd(int[] numbers) {
57+
public static int gcd(int... numbers) {
4458
int result = 0;
4559
for (final var number : numbers) {
4660
result = gcd(result, number);
4761
}
4862

4963
return result;
5064
}
51-
52-
public static void main(String[] args) {
53-
int[] myIntArray = {4, 16, 32};
54-
55-
// call gcd function (input array)
56-
System.out.println(gcd(myIntArray)); // => 4
57-
System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8
58-
}
5965
}
Lines changed: 24 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,38 @@
11
package com.thealgorithms.maths;
22

3-
/* This is a program to check if a number is a Krishnamurthy number or not.
4-
A number is a Krishnamurthy number if the sum of the factorials of the digits of the number is equal
5-
to the number itself. For example, 1, 2 and 145 are Krishnamurthy numbers. Krishnamurthy number is
6-
also referred to as a Strong number.
3+
/**
4+
* Utility class for checking if a number is a Krishnamurthy number.
5+
*
6+
* A Krishnamurthy number (also known as a Strong number) is a number whose sum of the factorials of its digits is equal to the number itself.
7+
*
8+
* For example, 145 is a Krishnamurthy number because 1! + 4! + 5! = 1 + 24 + 120 = 145.
9+
* <b>Example usage:</b>
10+
* <pre>
11+
* boolean isKrishnamurthy = KrishnamurthyNumber.isKrishnamurthy(145);
12+
* System.out.println(isKrishnamurthy); // Output: true
13+
*
14+
* isKrishnamurthy = KrishnamurthyNumber.isKrishnamurthy(123);
15+
* System.out.println(isKrishnamurthy); // Output: false
16+
* </pre>
717
*/
8-
import java.io.BufferedReader;
9-
import java.io.IOException;
10-
import java.io.InputStreamReader;
11-
1218
public final class KrishnamurthyNumber {
19+
1320
private KrishnamurthyNumber() {
1421
}
1522

16-
// returns True if the number is a Krishnamurthy number and False if it is not.
17-
18-
public static boolean isKMurthy(int n) {
19-
// initialising the variable s that will store the sum of the factorials of the digits to 0
20-
int s = 0;
21-
// storing the number n in a temporary variable tmp
23+
/**
24+
* Checks if a number is a Krishnamurthy number.
25+
*
26+
* @param n The number to check
27+
* @return true if the number is a Krishnamurthy number, false otherwise
28+
*/
29+
public static boolean isKrishnamurthy(int n) {
2230
int tmp = n;
31+
int s = 0;
2332

24-
// Krishnamurthy numbers are positive
2533
if (n <= 0) {
2634
return false;
27-
} // checking if the number is a Krishnamurthy number
28-
else {
35+
} else {
2936
while (n != 0) {
3037
// initialising the variable fact that will store the factorials of the digits
3138
int fact = 1;
@@ -43,15 +50,4 @@ public static boolean isKMurthy(int n) {
4350
return tmp == s;
4451
}
4552
}
46-
47-
public static void main(String[] args) throws IOException {
48-
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
49-
System.out.println("Enter a number to check if it is a Krishnamurthy number: ");
50-
int n = Integer.parseInt(br.readLine());
51-
if (isKMurthy(n)) {
52-
System.out.println(n + " is a Krishnamurthy number.");
53-
} else {
54-
System.out.println(n + " is NOT a Krishnamurthy number.");
55-
}
56-
}
5753
}

src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java

Lines changed: 37 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,37 +3,54 @@
33
import com.thealgorithms.datastructures.Node;
44
import java.util.ArrayDeque;
55
import java.util.ArrayList;
6+
import java.util.HashSet;
67
import java.util.List;
78
import java.util.Optional;
89
import java.util.Queue;
10+
import java.util.Set;
911

1012
/**
11-
* @author: caos321
12-
* @date: 31 October 2021 (Sunday)
13-
* @wiki: https://en.wikipedia.org/wiki/Breadth-first_search
13+
* Breadth-First Search implementation for tree/graph traversal.
14+
* @author caos321
15+
* @co-author @manishraj27
16+
* @see <a href="https://en.wikipedia.org/wiki/Breadth-first_search">Breadth-first search</a>
1417
*/
1518
public class BreadthFirstSearch<T> {
16-
1719
private final List<T> visited = new ArrayList<>();
20+
private final Set<T> visitedSet = new HashSet<>();
1821

19-
public Optional<Node<T>> search(final Node<T> node, final T value) {
20-
if (node == null) {
22+
/**
23+
* Performs a breadth-first search to find a node with the given value.
24+
*
25+
* @param root The root node to start the search from
26+
* @param value The value to search for
27+
* @return Optional containing the found node, or empty if not found
28+
*/
29+
public Optional<Node<T>> search(final Node<T> root, final T value) {
30+
if (root == null) {
2131
return Optional.empty();
2232
}
23-
if (node.getValue().equals(value)) {
24-
// add root node to visited
25-
visited.add(value);
26-
return Optional.of(node);
27-
}
28-
visited.add(node.getValue());
2933

30-
Queue<Node<T>> queue = new ArrayDeque<>(node.getChildren());
34+
visited.add(root.getValue());
35+
visitedSet.add(root.getValue());
36+
37+
if (root.getValue() == value) {
38+
return Optional.of(root);
39+
}
3140

41+
Queue<Node<T>> queue = new ArrayDeque<>(root.getChildren());
3242
while (!queue.isEmpty()) {
3343
final Node<T> current = queue.poll();
34-
visited.add(current.getValue());
44+
T currentValue = current.getValue();
45+
46+
if (visitedSet.contains(currentValue)) {
47+
continue;
48+
}
49+
50+
visited.add(currentValue);
51+
visitedSet.add(currentValue);
3552

36-
if (current.getValue().equals(value)) {
53+
if (currentValue == value || (value != null && value.equals(currentValue))) {
3754
return Optional.of(current);
3855
}
3956

@@ -43,6 +60,11 @@ public Optional<Node<T>> search(final Node<T> node, final T value) {
4360
return Optional.empty();
4461
}
4562

63+
/**
64+
* Returns the list of nodes in the order they were visited.
65+
*
66+
* @return List containing the visited nodes
67+
*/
4668
public List<T> getVisited() {
4769
return visited;
4870
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.thealgorithms.sorts;
2+
3+
public class AdaptiveMergeSort implements SortAlgorithm {
4+
@SuppressWarnings("unchecked")
5+
public <T extends Comparable<T>> T[] sort(T[] array) {
6+
if (array.length <= 1) {
7+
return array;
8+
}
9+
T[] aux = array.clone();
10+
sort(array, aux, 0, array.length - 1);
11+
return array;
12+
}
13+
14+
private <T extends Comparable<T>> void sort(T[] array, T[] aux, int low, int high) {
15+
if (low >= high) {
16+
return;
17+
}
18+
int mid = low + (high - low) / 2;
19+
sort(array, aux, low, mid);
20+
sort(array, aux, mid + 1, high);
21+
merge(array, aux, low, mid, high);
22+
}
23+
24+
private <T extends Comparable<T>> void merge(T[] array, T[] aux, int low, int mid, int high) {
25+
System.arraycopy(array, low, aux, low, high - low + 1);
26+
int i = low;
27+
int j = mid + 1;
28+
for (int k = low; k <= high; k++) {
29+
if (i > mid) {
30+
array[k] = aux[j++];
31+
} else if (j > high) {
32+
array[k] = aux[i++];
33+
} else if (aux[j].compareTo(aux[i]) < 0) {
34+
array[k] = aux[j++];
35+
} else {
36+
array[k] = aux[i++];
37+
}
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)