repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Prime/MillerRabinPrimalityCheck.java
src/main/java/com/thealgorithms/maths/Prime/MillerRabinPrimalityCheck.java
package com.thealgorithms.maths.Prime; import java.util.Random; public final class MillerRabinPrimalityCheck { private MillerRabinPrimalityCheck() { } /** * Check whether the given number is prime or not * MillerRabin algorithm is probabilistic. There is also an altered version which is deterministic. * https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test * https://cp-algorithms.com/algebra/primality_tests.html * * @param n Whole number which is tested on primality * @param k Number of iterations * If n is composite then running k iterations of the Miller–Rabin * test will declare n probably prime with a probability at most 4^(−k) * @return true or false whether the given number is probably prime or not */ public static boolean millerRabin(long n, int k) { // returns true if n is probably prime, else returns false. if (n < 4) { return n == 2 || n == 3; } int s = 0; long d = n - 1; while ((d & 1) == 0) { d >>= 1; s++; } Random rnd = new Random(); for (int i = 0; i < k; i++) { long a = 2 + rnd.nextLong(n) % (n - 3); if (checkComposite(n, a, d, s)) { return false; } } return true; } public static boolean deterministicMillerRabin(long n) { // returns true if n is prime, else returns false. if (n < 2) { return false; } int r = 0; long d = n - 1; while ((d & 1) == 0) { d >>= 1; r++; } for (int a : new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) { if (n == a) { return true; } if (checkComposite(n, a, d, r)) { return false; } } return true; } /** * Check if number n is composite (probabilistic) * * @param n Whole number which is tested for compositeness * @param a Random number (prime base) to check if it holds certain equality * @param d Number which holds this equation: 'n - 1 = 2^s * d' * @param s Number of twos in (n - 1) factorization * * @return true or false whether the numbers hold the equation or not * the equations are described on the websites mentioned at the beginning of the class */ private static boolean checkComposite(long n, long a, long d, int s) { long x = powerModP(a, d, n); if (x == 1 || x == n - 1) { return false; } for (int r = 1; r < s; r++) { x = powerModP(x, 2, n); if (x == n - 1) { return false; } } return true; } private static long powerModP(long x, long y, long p) { long res = 1; // Initialize result x = x % p; // Update x if it is more than or equal to p if (x == 0) { return 0; // In case x is divisible by p; } while (y > 0) { // If y is odd, multiply x with result if ((y & 1) == 1) { res = multiplyModP(res, x, p); } // y must be even now y = y >> 1; // y = y/2 x = multiplyModP(x, x, p); } return res; } private static long multiplyModP(long a, long b, long p) { long aHi = a >> 24; long aLo = a & ((1 << 24) - 1); long bHi = b >> 24; long bLo = b & ((1 << 24) - 1); long result = ((((aHi * bHi << 16) % p) << 16) % p) << 16; result += ((aLo * bHi + aHi * bLo) << 24) + aLo * bLo; return result % p; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Prime/MobiusFunction.java
src/main/java/com/thealgorithms/maths/Prime/MobiusFunction.java
package com.thealgorithms.maths.Prime; /* * Java program for mobius function * For any positive integer n, define μ(n) as the sum of the primitive nth roots of unity. * It has values in {−1, 0, 1} depending on the factorization of n into prime factors: * μ(n) = +1 if n is a square-free positive integer with an even number of prime factors. * μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. * μ(n) = 0 if n has a squared prime factor. * Wikipedia: https://en.wikipedia.org/wiki/M%C3%B6bius_function * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) * * */ public final class MobiusFunction { private MobiusFunction() { } /** * This method returns μ(n) of given number n * * @param number Integer value which μ(n) is to be calculated * @return 1 when number is less than or equals 1 * or number has even number of prime factors * 0 when number has repeated prime factor * -1 when number has odd number of prime factors */ public static int mobius(int number) { if (number <= 0) { // throw exception when number is less than or is zero throw new IllegalArgumentException("Number must be greater than zero."); } if (number == 1) { // return 1 if number passed is less or is 1 return 1; } int primeFactorCount = 0; for (int i = 1; i <= number; i++) { // find prime factors of number if (number % i == 0 && PrimeCheck.isPrime(i)) { // check if number is divisible by square of prime factor if (number % (i * i) == 0) { // if number is divisible by square of prime factor return 0; } /*increment primeFactorCount by 1 if number is not divisible by square of found prime factor*/ primeFactorCount++; } } return (primeFactorCount % 2 == 0) ? 1 : -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Prime/PrimeCheck.java
src/main/java/com/thealgorithms/maths/Prime/PrimeCheck.java
package com.thealgorithms.maths.Prime; import java.util.Scanner; public final class PrimeCheck { private PrimeCheck() { } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int n = scanner.nextInt(); if (isPrime(n)) { System.out.println("algo1 verify that " + n + " is a prime number"); } else { System.out.println("algo1 verify that " + n + " is not a prime number"); } if (fermatPrimeChecking(n, 20)) { System.out.println("algo2 verify that " + n + " is a prime number"); } else { System.out.println("algo2 verify that " + n + " is not a prime number"); } scanner.close(); } /** * * * Checks if a number is prime or not * * @param n the number * @return {@code true} if {@code n} is prime */ public static boolean isPrime(int n) { if (n == 2) { return true; } if (n < 2 || n % 2 == 0) { return false; } for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) { if (n % i == 0) { return false; } } return true; } /** * * * Checks if a number is prime or not * * @param n the number * @return {@code true} if {@code n} is prime */ public static boolean fermatPrimeChecking(int n, int iteration) { long a; int up = n - 2; int down = 2; for (int i = 0; i < iteration; i++) { a = (long) Math.floor(Math.random() * (up - down + 1) + down); if (modPow(a, n - 1, n) != 1) { return false; } } return true; } /** * * * @param a basis * @param b exponent * @param c modulo * @return (a^b) mod c */ private static long modPow(long a, long b, long c) { long res = 1; for (int i = 0; i < b; i++) { res *= a; res %= c; } return res % c; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/randomized/RandomizedClosestPair.java
src/main/java/com/thealgorithms/randomized/RandomizedClosestPair.java
package com.thealgorithms.randomized; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; /** * Randomized Closest Pair of Points Algorithm * * Use Case: * - Efficiently finds the closest pair of points in a 2D plane. * - Applicable in computational geometry, clustering, and graphics. * * Time Complexity: * - Expected: O(n log n) using randomized divide and conquer * * @see <a href="https://en.wikipedia.org/wiki/Closest_pair_of_points_problem">Closest Pair of Points - Wikipedia</a> */ public final class RandomizedClosestPair { // Prevent instantiation of utility class private RandomizedClosestPair() { throw new UnsupportedOperationException("Utility class"); } public static class Point { public final double x; public final double y; public Point(double x, double y) { this.x = x; this.y = y; } } public static double findClosestPairDistance(Point[] points) { List<Point> shuffled = new ArrayList<>(Arrays.asList(points)); Collections.shuffle(shuffled, new Random()); Point[] px = shuffled.toArray(new Point[0]); Arrays.sort(px, Comparator.comparingDouble(p -> p.x)); Point[] py = px.clone(); Arrays.sort(py, Comparator.comparingDouble(p -> p.y)); return closestPair(px, py); } private static double closestPair(Point[] px, Point[] py) { int n = px.length; if (n <= 3) { return bruteForce(px); } int mid = n / 2; Point midPoint = px[mid]; Point[] qx = Arrays.copyOfRange(px, 0, mid); Point[] rx = Arrays.copyOfRange(px, mid, n); List<Point> qy = new ArrayList<>(); List<Point> ry = new ArrayList<>(); for (Point p : py) { if (p.x <= midPoint.x) { qy.add(p); } else { ry.add(p); } } double d1 = closestPair(qx, qy.toArray(new Point[0])); double d2 = closestPair(rx, ry.toArray(new Point[0])); double d = Math.min(d1, d2); List<Point> strip = new ArrayList<>(); for (Point p : py) { if (Math.abs(p.x - midPoint.x) < d) { strip.add(p); } } return Math.min(d, stripClosest(strip, d)); } private static double bruteForce(Point[] points) { double min = Double.POSITIVE_INFINITY; for (int i = 0; i < points.length; i++) { for (int j = i + 1; j < points.length; j++) { min = Math.min(min, distance(points[i], points[j])); } } return min; } private static double stripClosest(List<Point> strip, double d) { double min = d; int n = strip.size(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n && (strip.get(j).y - strip.get(i).y) < min; j++) { min = Math.min(min, distance(strip.get(i), strip.get(j))); } } return min; } private static double distance(Point p1, Point p2) { return Math.hypot(p1.x - p2.x, p1.y - p2.y); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/randomized/MonteCarloIntegration.java
src/main/java/com/thealgorithms/randomized/MonteCarloIntegration.java
package com.thealgorithms.randomized; import java.util.Random; import java.util.function.Function; /** * A demonstration of the Monte Carlo integration algorithm in Java. * * <p>This class estimates the value of definite integrals using randomized sampling, * also known as the Monte Carlo method. It is particularly effective for: * <ul> * <li>Functions that are difficult or impossible to integrate analytically</li> * <li>High-dimensional integrals where traditional methods are inefficient</li> * <li>Simulation and probabilistic analysis tasks</li> * </ul> * * <p>The core idea is to sample random points uniformly from the integration domain, * evaluate the function at those points, and compute the scaled average to estimate the integral. * * <p>For a one-dimensional integral over [a, b], the approximation is the function range (b-a), * multiplied by the function average result for a random sample. * See more: <a href="https://en.wikipedia.org/wiki/Monte_Carlo_integration">Monte Carlo Integration</a> * * @author: MuhammadEzzatHBK */ public final class MonteCarloIntegration { private MonteCarloIntegration() { } /** * Approximates the definite integral of a given function over a specified * interval using the Monte Carlo method with a fixed random seed for * reproducibility. * * @param fx the function to integrate * @param a the lower bound of the interval * @param b the upper bound of the interval * @param n the number of random samples to use * @param seed the seed for the random number generator * @return the approximate value of the integral */ public static double approximate(Function<Double, Double> fx, double a, double b, int n, long seed) { return doApproximate(fx, a, b, n, new Random(seed)); } /** * Approximates the definite integral of a given function over a specified * interval using the Monte Carlo method with a random seed based on the * current system time for more randomness. * * @param fx the function to integrate * @param a the lower bound of the interval * @param b the upper bound of the interval * @param n the number of random samples to use * @return the approximate value of the integral */ public static double approximate(Function<Double, Double> fx, double a, double b, int n) { return doApproximate(fx, a, b, n, new Random(System.currentTimeMillis())); } private static double doApproximate(Function<Double, Double> fx, double a, double b, int n, Random generator) { if (!validate(fx, a, b, n)) { throw new IllegalArgumentException("Invalid input parameters"); } double total = 0.0; double interval = b - a; int pairs = n / 2; for (int i = 0; i < pairs; i++) { double u = generator.nextDouble(); double x1 = a + u * interval; double x2 = a + (1.0 - u) * interval; total += fx.apply(x1); total += fx.apply(x2); } if ((n & 1) == 1) { double x = a + generator.nextDouble() * interval; total += fx.apply(x); } return interval * total / n; } private static boolean validate(Function<Double, Double> fx, double a, double b, int n) { boolean isFunctionValid = fx != null; boolean isIntervalValid = a < b; boolean isSampleSizeValid = n > 0; return isFunctionValid && isIntervalValid && isSampleSizeValid; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/randomized/KargerMinCut.java
src/main/java/com/thealgorithms/randomized/KargerMinCut.java
package com.thealgorithms.randomized; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; /** * Implementation of Karger's Minimum Cut algorithm. * * <p>Karger's algorithm is a randomized algorithm to compute the minimum cut of a connected graph. * A minimum cut is the smallest set of edges that, if removed, would split the graph into two * disconnected components. * * <p>The algorithm works by repeatedly contracting random edges in the graph until only two * nodes remain. The edges between these two nodes represent a cut. By running the algorithm * multiple times and keeping track of the smallest cut found, the probability of finding the * true minimum cut increases. * * <p>Key steps of the algorithm: * <ol> * <li>Randomly select an edge and contract it, merging the two nodes into one.</li> * <li>Repeat the contraction process until only two nodes remain.</li> * <li>Count the edges between the two remaining nodes to determine the cut size.</li> * <li>Repeat the process multiple times to improve the likelihood of finding the true minimum cut.</li> * </ol> * <p> * See more: <a href="https://en.wikipedia.org/wiki/Karger%27s_algorithm">Karger's algorithm</a> * * @author MuhammadEzzatHBK */ public final class KargerMinCut { /** * Output of the Karger algorithm. * * @param first The first set of nodes in the cut. * @param second The second set of nodes in the cut. * @param minCut The size of the minimum cut. */ public record KargerOutput(Set<Integer> first, Set<Integer> second, int minCut) { } private KargerMinCut() { } public static KargerOutput findMinCut(Collection<Integer> nodeSet, List<int[]> edges) { return findMinCut(nodeSet, edges, 100); } /** * Finds the minimum cut of a graph using Karger's algorithm. * * @param nodeSet: Input graph nodes * @param edges: Input graph edges * @param iterations: Iterations to run the algorithms for, more iterations = more accuracy * @return A KargerOutput object containing the two sets of nodes and the size of the minimum cut. */ public static KargerOutput findMinCut(Collection<Integer> nodeSet, List<int[]> edges, int iterations) { Graph graph = new Graph(nodeSet, edges); KargerOutput minCut = new KargerOutput(new HashSet<>(), new HashSet<>(), Integer.MAX_VALUE); KargerOutput output; // Run the algorithm multiple times to increase the probability of finding for (int i = 0; i < iterations; i++) { Graph clone = graph.copy(); output = clone.findMinCut(); if (output.minCut < minCut.minCut) { minCut = output; } } return minCut; } private static class DisjointSetUnion { private final int[] parent; int setCount; DisjointSetUnion(int size) { parent = new int[size]; for (int i = 0; i < size; i++) { parent[i] = i; } setCount = size; } int find(int i) { // If it's not its own parent, then it's not the root of its set if (parent[i] != i) { // Recursively find the root of its parent // and update i's parent to point directly to the root (path compression) parent[i] = find(parent[i]); } // Return the root (representative) of the set return parent[i]; } void union(int u, int v) { // Find the root of each node int rootU = find(u); int rootV = find(v); // If they belong to different sets, merge them if (rootU != rootV) { // Make rootV point to rootU — merge the two sets parent[rootV] = rootU; // Reduce the count of disjoint sets by 1 setCount--; } } boolean inSameSet(int u, int v) { return find(u) == find(v); } /* This is a verbosity method, it's not a part of the core algorithm, But it helps us provide more useful output. */ Set<Integer> getAnySet() { int aRoot = find(0); // Get one of the two roots Set<Integer> set = new HashSet<>(); for (int i = 0; i < parent.length; i++) { if (find(i) == aRoot) { set.add(i); } } return set; } } private static class Graph { private final List<Integer> nodes; private final List<int[]> edges; Graph(Collection<Integer> nodeSet, List<int[]> edges) { this.nodes = new ArrayList<>(nodeSet); this.edges = new ArrayList<>(); for (int[] e : edges) { this.edges.add(new int[] {e[0], e[1]}); } } Graph copy() { return new Graph(this.nodes, this.edges); } KargerOutput findMinCut() { DisjointSetUnion dsu = new DisjointSetUnion(nodes.size()); List<int[]> workingEdges = new ArrayList<>(edges); Random rand = new Random(); while (dsu.setCount > 2) { int[] e = workingEdges.get(rand.nextInt(workingEdges.size())); if (!dsu.inSameSet(e[0], e[1])) { dsu.union(e[0], e[1]); } } int cutEdges = 0; for (int[] e : edges) { if (!dsu.inSameSet(e[0], e[1])) { cutEdges++; } } return collectResult(dsu, cutEdges); } /* This is a verbosity method, it's not a part of the core algorithm, But it helps us provide more useful output. */ private KargerOutput collectResult(DisjointSetUnion dsu, int cutEdges) { Set<Integer> firstIndices = dsu.getAnySet(); Set<Integer> firstSet = new HashSet<>(); Set<Integer> secondSet = new HashSet<>(); for (int i = 0; i < nodes.size(); i++) { if (firstIndices.contains(i)) { firstSet.add(nodes.get(i)); } else { secondSet.add(nodes.get(i)); } } return new KargerOutput(firstSet, secondSet, cutEdges); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/randomized/RandomizedMatrixMultiplicationVerification.java
src/main/java/com/thealgorithms/randomized/RandomizedMatrixMultiplicationVerification.java
package com.thealgorithms.randomized; import java.util.Random; public final class RandomizedMatrixMultiplicationVerification { private RandomizedMatrixMultiplicationVerification() { // Prevent instantiation of utility class } /** * Verifies whether A × B == C using Freivalds' algorithm. * @param A Left matrix * @param B Right matrix * @param C Product matrix to verify * @param iterations Number of randomized checks * @return true if likely A×B == C; false if definitely not */ public static boolean verify(int[][] a, int[][] b, int[][] c, int iterations) { int n = a.length; Random random = new Random(); for (int iter = 0; iter < iterations; iter++) { // Step 1: Generate random 0/1 vector int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = random.nextInt(2); } // Step 2: Compute br = b × r int[] br = new int[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { br[i] += b[i][j] * r[j]; } } // Step 3: Compute a(br) int[] abr = new int[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { abr[i] += a[i][j] * br[j]; } } // Step 4: Compute cr = c × r int[] cr = new int[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cr[i] += c[i][j] * r[j]; } } // Step 5: Compare abr and cr for (int i = 0; i < n; i++) { if (abr[i] != cr[i]) { return false; } } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/randomized/ReservoirSampling.java
src/main/java/com/thealgorithms/randomized/ReservoirSampling.java
package com.thealgorithms.randomized; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Reservoir Sampling Algorithm * * Use Case: * - Efficient for selecting k random items from a stream of unknown size * - Used in streaming systems, big data, and memory-limited environments * * Time Complexity: O(n) * Space Complexity: O(k) * * @author Michael Alexander Montoya (@cureprotocols) * @see <a href="https://en.wikipedia.org/wiki/Reservoir_sampling">Reservoir Sampling - Wikipedia</a> */ public final class ReservoirSampling { // Prevent instantiation of utility class private ReservoirSampling() { throw new UnsupportedOperationException("Utility class"); } /** * Selects k random elements from a stream using reservoir sampling. * * @param stream The input stream as an array of integers. * @param sampleSize The number of elements to sample. * @return A list containing k randomly selected elements. */ public static List<Integer> sample(int[] stream, int sampleSize) { if (sampleSize > stream.length) { throw new IllegalArgumentException("Sample size cannot exceed stream size."); } List<Integer> reservoir = new ArrayList<>(sampleSize); Random rand = new Random(); for (int i = 0; i < stream.length; i++) { if (i < sampleSize) { reservoir.add(stream[i]); } else { int j = rand.nextInt(i + 1); if (j < sampleSize) { reservoir.set(j, stream[i]); } } } return reservoir; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/randomized/RandomizedQuickSort.java
src/main/java/com/thealgorithms/randomized/RandomizedQuickSort.java
package com.thealgorithms.randomized; /** * This class implements the Randomized QuickSort algorithm. * It selects a pivot randomly to improve performance on sorted or nearly sorted data. * @author Vibhu Khera */ public final class RandomizedQuickSort { private RandomizedQuickSort() { throw new UnsupportedOperationException("Utility class"); } /** * Sorts the array using the randomized quicksort algorithm. * * @param arr the array to sort * @param low the starting index of the array * @param high the ending index of the array */ public static void randomizedQuickSort(int[] arr, int low, int high) { if (low < high) { int pivotIndex = partition(arr, low, high); randomizedQuickSort(arr, low, pivotIndex - 1); randomizedQuickSort(arr, pivotIndex + 1, high); } } /** * Partitions the array around a pivot chosen randomly. * * @param arr the array to partition * @param low the starting index * @param high the ending index * @return the index of the pivot after partitioning */ private static int partition(int[] arr, int low, int high) { int pivotIndex = low + (int) (Math.random() * (high - low + 1)); int pivotValue = arr[pivotIndex]; swap(arr, pivotIndex, high); // Move pivot to end int storeIndex = low; for (int i = low; i < high; i++) { if (arr[i] < pivotValue) { swap(arr, storeIndex, i); storeIndex++; } } swap(arr, storeIndex, high); // Move pivot to its final place return storeIndex; } /** * Swaps two elements in the array, only if the indices are different. * * @param arr the array in which elements are to be swapped * @param i the first index * @param j the second index */ private static void swap(int[] arr, int i, int j) { // Skip if indices are the same if (i == j) { return; } int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/recursion/DiceThrower.java
src/main/java/com/thealgorithms/recursion/DiceThrower.java
package com.thealgorithms.recursion; import java.util.ArrayList; import java.util.List; /** * DiceThrower - Generates all possible dice roll combinations that sum to a target * * This algorithm uses recursive backtracking to find all combinations of dice rolls * (faces 1-6) that sum to a given target value. * * Example: If target = 4, possible combinations include: * - "1111" (1+1+1+1 = 4) * - "13" (1+3 = 4) * - "22" (2+2 = 4) * - "4" (4 = 4) * * @author BEASTSHRIRAM * @see <a href="https://en.wikipedia.org/wiki/Backtracking">Backtracking Algorithm</a> */ public final class DiceThrower { private DiceThrower() { // Utility class } /** * Returns all possible dice roll combinations that sum to the target * * @param target the target sum to achieve with dice rolls * @return list of all possible combinations as strings */ public static List<String> getDiceCombinations(int target) { if (target < 0) { throw new IllegalArgumentException("Target must be non-negative"); } return generateCombinations("", target); } /** * Prints all possible dice roll combinations that sum to the target * * @param target the target sum to achieve with dice rolls */ public static void printDiceCombinations(int target) { if (target < 0) { throw new IllegalArgumentException("Target must be non-negative"); } printCombinations("", target); } /** * Recursive helper method to generate all combinations * * @param current the current combination being built * @param remaining the remaining sum needed * @return list of all combinations from this state */ private static List<String> generateCombinations(String current, int remaining) { List<String> combinations = new ArrayList<>(); // Base case: if remaining sum is 0, we found a valid combination if (remaining == 0) { combinations.add(current); return combinations; } // Try all possible dice faces (1-6), but not more than remaining sum for (int face = 1; face <= 6 && face <= remaining; face++) { List<String> subCombinations = generateCombinations(current + face, remaining - face); combinations.addAll(subCombinations); } return combinations; } /** * Recursive helper method to print all combinations * * @param current the current combination being built * @param remaining the remaining sum needed */ private static void printCombinations(String current, int remaining) { // Base case: if remaining sum is 0, we found a valid combination if (remaining == 0) { System.out.println(current); return; } // Try all possible dice faces (1-6), but not more than remaining sum for (int face = 1; face <= 6 && face <= remaining; face++) { printCombinations(current + face, remaining - face); } } /** * Demo method to show usage * * @param args command line arguments */ public static void main(String[] args) { int target = 4; System.out.println("All dice combinations that sum to " + target + ":"); List<String> combinations = getDiceCombinations(target); for (String combination : combinations) { System.out.println(combination); } System.out.println("\nTotal combinations: " + combinations.size()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/recursion/FactorialRecursion.java
src/main/java/com/thealgorithms/recursion/FactorialRecursion.java
package com.thealgorithms.recursion; public final class FactorialRecursion { private FactorialRecursion() { } /** * Recursive FactorialRecursion Method * * @param n The number to factorial * @return The factorial of the number */ public static long factorial(int n) { if (n < 0) { throw new IllegalArgumentException("number is negative"); } return n == 0 || n == 1 ? 1 : n * factorial(n - 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/recursion/GenerateSubsets.java
src/main/java/com/thealgorithms/recursion/GenerateSubsets.java
package com.thealgorithms.recursion; import java.util.ArrayList; import java.util.List; /** * Utility class to generate all subsets (power set) of a given string using recursion. * * <p>For example, the string "ab" will produce: ["ab", "a", "b", ""] */ public final class GenerateSubsets { private GenerateSubsets() { } /** * Generates all subsets (power set) of the given string using recursion. * * @param str the input string to generate subsets for * @return a list of all subsets of the input string */ public static List<String> subsetRecursion(String str) { return generateSubsets("", str); } /** * Recursive helper method to generate subsets by including or excluding characters. * * @param current the current prefix being built * @param remaining the remaining string to process * @return list of subsets formed from current and remaining */ private static List<String> generateSubsets(String current, String remaining) { if (remaining.isEmpty()) { List<String> result = new ArrayList<>(); result.add(current); return result; } char ch = remaining.charAt(0); String next = remaining.substring(1); // Include the character List<String> withChar = generateSubsets(current + ch, next); // Exclude the character List<String> withoutChar = generateSubsets(current, next); withChar.addAll(withoutChar); return withChar; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/recursion/FibonacciSeries.java
src/main/java/com/thealgorithms/recursion/FibonacciSeries.java
package com.thealgorithms.recursion; /* The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting with 0 and 1. NUMBER 0 1 2 3 4 5 6 7 8 9 10 ... FIBONACCI 0 1 1 2 3 5 8 13 21 34 55 ... */ public final class FibonacciSeries { private FibonacciSeries() { throw new UnsupportedOperationException("Utility class"); } public static int fibonacci(int n) { if (n < 0) { throw new IllegalArgumentException("n must be a non-negative integer"); } if (n <= 1) { return n; } return fibonacci(n - 1) + fibonacci(n - 2); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/recursion/SylvesterSequence.java
src/main/java/com/thealgorithms/recursion/SylvesterSequence.java
package com.thealgorithms.recursion; import java.math.BigInteger; /** * A utility class for calculating numbers in Sylvester's sequence. * * <p>Sylvester's sequence is a sequence of integers where each term is calculated * using the formula: * <pre> * a(n) = a(n-1) * (a(n-1) - 1) + 1 * </pre> * with the first term being 2. * * <p>This class is final and cannot be instantiated. * * @see <a href="https://en.wikipedia.org/wiki/Sylvester_sequence">Wikipedia: Sylvester sequence</a> */ public final class SylvesterSequence { // Private constructor to prevent instantiation private SylvesterSequence() { } /** * Calculates the nth number in Sylvester's sequence. * * <p>The sequence is defined recursively, with the first term being 2: * <pre> * a(1) = 2 * a(n) = a(n-1) * (a(n-1) - 1) + 1 for n > 1 * </pre> * * @param n the position in the sequence (must be greater than 0) * @return the nth number in Sylvester's sequence * @throws IllegalArgumentException if n is less than or equal to 0 */ public static BigInteger sylvester(int n) { if (n <= 0) { throw new IllegalArgumentException("sylvester() does not accept negative numbers or zero."); } if (n == 1) { return BigInteger.valueOf(2); } else { BigInteger prev = sylvester(n - 1); // Sylvester sequence formula: a(n) = a(n-1) * (a(n-1) - 1) + 1 return prev.multiply(prev.subtract(BigInteger.ONE)).add(BigInteger.ONE); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/io/BufferedReader.java
src/main/java/com/thealgorithms/io/BufferedReader.java
package com.thealgorithms.io; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * Mimics the actions of the Original buffered reader * implements other actions, such as peek(n) to lookahead, * block() to read a chunk of size {BUFFER SIZE} * <p> * Author: Kumaraswamy B.G (Xoma Dev) */ public class BufferedReader { private static final int DEFAULT_BUFFER_SIZE = 5; /** * The maximum number of bytes the buffer can hold. * Value is changed when encountered Eof to not * cause overflow read of 0 bytes */ private int bufferSize; private final byte[] buffer; /** * posRead -> indicates the next byte to read */ private int posRead = 0; private int bufferPos = 0; private boolean foundEof = false; private InputStream input; public BufferedReader(byte[] input) throws IOException { this(new ByteArrayInputStream(input)); } public BufferedReader(InputStream input) throws IOException { this(input, DEFAULT_BUFFER_SIZE); } public BufferedReader(InputStream input, int bufferSize) throws IOException { this.input = input; if (input.available() == -1) { throw new IOException("Empty or already closed stream provided"); } this.bufferSize = bufferSize; buffer = new byte[bufferSize]; } /** * Reads a single byte from the stream */ public int read() throws IOException { if (needsRefill()) { if (foundEof) { return -1; } // the buffer is empty, or the buffer has // been completely read and needs to be refilled refill(); } return buffer[posRead++] & 0xff; // read and un-sign it } /** * Number of bytes not yet been read */ public int available() throws IOException { int available = input.available(); if (needsRefill()) { // since the block is already empty, // we have no responsibility yet return available; } return bufferPos - posRead + available; } /** * Returns the next character */ public int peek() throws IOException { return peek(1); } /** * Peeks and returns a value located at next {n} */ public int peek(int n) throws IOException { int available = available(); if (n >= available) { throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n)); } pushRefreshData(); if (n >= bufferSize) { throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize)); } return buffer[n]; } /** * Removes the already read bytes from the buffer * in-order to make space for new bytes to be filled up. * <p> * This may also do the job to read first time data (the whole buffer is empty) */ private void pushRefreshData() throws IOException { for (int i = posRead, j = 0; i < bufferSize; i++, j++) { buffer[j] = buffer[i]; } bufferPos -= posRead; posRead = 0; // fill out the spaces that we've // emptied justRefill(); } /** * Reads one complete block of size {bufferSize} * if found eof, the total length of an array will * be that of what's available * * @return a completed block */ public byte[] readBlock() throws IOException { pushRefreshData(); byte[] cloned = new byte[bufferSize]; // arraycopy() function is better than clone() if (bufferPos >= 0) { System.arraycopy(buffer, 0, cloned, 0, // important to note that, bufferSize does not stay constant // once the class is defined. See justRefill() function bufferSize); } // we assume that already a chunk // has been read refill(); return cloned; } private boolean needsRefill() { return bufferPos == 0 || posRead == bufferSize; } private void refill() throws IOException { posRead = 0; bufferPos = 0; justRefill(); } private void justRefill() throws IOException { assertStreamOpen(); // try to fill in the maximum we can until // we reach EOF while (bufferPos < bufferSize) { int read = input.read(); if (read == -1) { // reached end-of-file, no more data left // to be read foundEof = true; // rewrite the BUFFER_SIZE, to know that we've reached // EOF when requested refill bufferSize = bufferPos; } buffer[bufferPos++] = (byte) read; } } private void assertStreamOpen() { if (input == null) { throw new IllegalStateException("Input Stream already closed!"); } } public void close() throws IOException { if (input != null) { try { input.close(); } finally { input = null; } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/tree/HeavyLightDecomposition.java
src/main/java/com/thealgorithms/tree/HeavyLightDecomposition.java
package com.thealgorithms.tree; import java.util.ArrayList; import java.util.List; /** * Heavy-Light Decomposition (HLD) implementation in Java. * HLD is used to efficiently handle path queries on trees, such as maximum, * sum, or updates. It decomposes the tree into heavy and light chains, * enabling queries in O(log N) time. * Wikipedia Reference: https://en.wikipedia.org/wiki/Heavy-light_decomposition * Author: Nithin U. * Github: https://github.com/NithinU2802 */ public class HeavyLightDecomposition { private List<List<Integer>> tree; private int[] parent; private int[] depth; private int[] subtreeSize; private int[] chainHead; private int[] position; private int[] nodeValue; private int[] segmentTree; private int positionIndex; public HeavyLightDecomposition(int n) { tree = new ArrayList<>(); for (int i = 0; i <= n; i++) { tree.add(new ArrayList<>()); } parent = new int[n + 1]; depth = new int[n + 1]; subtreeSize = new int[n + 1]; chainHead = new int[n + 1]; position = new int[n + 1]; nodeValue = new int[n + 1]; segmentTree = new int[4 * (n + 1)]; for (int i = 0; i <= n; i++) { chainHead[i] = -1; } positionIndex = 0; } public int getPosition(int index) { return position[index]; } public int getPositionIndex() { return positionIndex; } public void addEdge(int u, int v) { tree.get(u).add(v); tree.get(v).add(u); } private void dfsSize(int node, int parentNode) { parent[node] = parentNode; subtreeSize[node] = 1; for (int child : tree.get(node)) { if (child != parentNode) { depth[child] = depth[node] + 1; dfsSize(child, node); subtreeSize[node] += subtreeSize[child]; } } } private void decompose(int node, int head) { chainHead[node] = head; position[node] = positionIndex++; int heavyChild = -1; int maxSubtreeSize = -1; for (int child : tree.get(node)) { if (child != parent[node] && subtreeSize[child] > maxSubtreeSize) { heavyChild = child; maxSubtreeSize = subtreeSize[child]; } } if (heavyChild != -1) { decompose(heavyChild, head); } for (int child : tree.get(node)) { if (child != parent[node] && child != heavyChild) { decompose(child, child); } } } private void buildSegmentTree(int node, int start, int end) { if (start == end) { segmentTree[node] = nodeValue[start]; return; } int mid = (start + end) / 2; buildSegmentTree(2 * node, start, mid); buildSegmentTree(2 * node + 1, mid + 1, end); segmentTree[node] = Math.max(segmentTree[2 * node], segmentTree[2 * node + 1]); } public void updateSegmentTree(int node, int start, int end, int index, int value) { if (start == end) { segmentTree[node] = value; return; } int mid = (start + end) / 2; if (index <= mid) { updateSegmentTree(2 * node, start, mid, index, value); } else { updateSegmentTree(2 * node + 1, mid + 1, end, index, value); } segmentTree[node] = Math.max(segmentTree[2 * node], segmentTree[2 * node + 1]); } public int querySegmentTree(int node, int start, int end, int left, int right) { if (left > end || right < start) { return Integer.MIN_VALUE; } if (left <= start && end <= right) { return segmentTree[node]; } int mid = (start + end) / 2; int leftQuery = querySegmentTree(2 * node, start, mid, left, right); int rightQuery = querySegmentTree(2 * node + 1, mid + 1, end, left, right); return Math.max(leftQuery, rightQuery); } public int queryMaxInPath(int u, int v) { int result = Integer.MIN_VALUE; while (chainHead[u] != chainHead[v]) { if (depth[chainHead[u]] < depth[chainHead[v]]) { int temp = u; u = v; v = temp; } result = Math.max(result, querySegmentTree(1, 0, positionIndex - 1, position[chainHead[u]], position[u])); u = parent[chainHead[u]]; } if (depth[u] > depth[v]) { int temp = u; u = v; v = temp; } result = Math.max(result, querySegmentTree(1, 0, positionIndex - 1, position[u], position[v])); return result; } public void initialize(int root, int[] values) { dfsSize(root, -1); decompose(root, root); for (int i = 0; i < values.length; i++) { nodeValue[position[i]] = values[i]; } buildSegmentTree(1, 0, positionIndex - 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/JumpSearch.java
src/main/java/com/thealgorithms/searches/JumpSearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * An implementation of the Jump Search algorithm. * * <p> * Jump Search is an algorithm for searching sorted arrays. It works by dividing the array * into blocks of a fixed size (the block size is typically the square root of the array length) * and jumping ahead by this block size to find a range where the target element may be located. * Once the range is found, a linear search is performed within that block. * * <p> * The Jump Search algorithm is particularly effective for large sorted arrays where the cost of * performing a linear search on the entire array would be prohibitive. * * <p> * Worst-case performance: O(√N)<br> * Best-case performance: O(1)<br> * Average performance: O(√N)<br> * Worst-case space complexity: O(1) * * <p> * This class implements the {@link SearchAlgorithm} interface, providing a generic search method * for any comparable type. */ public class JumpSearch implements SearchAlgorithm { /** * Jump Search algorithm implementation. * * @param array the sorted array containing elements * @param key the element to be searched * @return the index of {@code key} if found, otherwise -1 */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { int length = array.length; int blockSize = (int) Math.sqrt(length); int limit = blockSize; // Jumping ahead to find the block where the key may be located while (limit < length && key.compareTo(array[limit]) > 0) { limit = Math.min(limit + blockSize, length - 1); } // Perform linear search within the identified block for (int i = limit - blockSize; i <= limit && i < length; i++) { if (array[i].equals(key)) { return i; } } return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java
src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java
package com.thealgorithms.searches; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Random; /** * Monte Carlo Tree Search (MCTS) is a heuristic search algorithm used in * decition taking problems especially games. * * See more: https://en.wikipedia.org/wiki/Monte_Carlo_tree_search, * https://www.baeldung.com/java-monte-carlo-tree-search */ public class MonteCarloTreeSearch { public class Node { Node parent; ArrayList<Node> childNodes; boolean isPlayersTurn; // True if it is the player's turn. boolean playerWon; // True if the player won; false if the opponent won. int score; int visitCount; public Node() { } public Node(Node parent, boolean isPlayersTurn) { this.parent = parent; childNodes = new ArrayList<>(); this.isPlayersTurn = isPlayersTurn; playerWon = false; score = 0; visitCount = 0; } } static final int WIN_SCORE = 10; static final int TIME_LIMIT = 500; // Time the algorithm will be running for (in milliseconds). /** * Explores a game tree using Monte Carlo Tree Search (MCTS) and returns the * most promising node. * * @param rootNode Root node of the game tree. * @return The most promising child of the root node. */ public Node monteCarloTreeSearch(Node rootNode) { Node winnerNode; double timeLimit; // Expand the root node. addChildNodes(rootNode, 10); timeLimit = System.currentTimeMillis() + TIME_LIMIT; // Explore the tree until the time limit is reached. while (System.currentTimeMillis() < timeLimit) { Node promisingNode; // Get a promising node using UCT. promisingNode = getPromisingNode(rootNode); // Expand the promising node. if (promisingNode.childNodes.size() == 0) { addChildNodes(promisingNode, 10); } simulateRandomPlay(promisingNode); } winnerNode = getWinnerNode(rootNode); printScores(rootNode); System.out.format("%nThe optimal node is: %02d%n", rootNode.childNodes.indexOf(winnerNode) + 1); return winnerNode; } public void addChildNodes(Node node, int childCount) { for (int i = 0; i < childCount; i++) { node.childNodes.add(new Node(node, !node.isPlayersTurn)); } } /** * Uses UCT to find a promising child node to be explored. * * UCT: Upper Confidence bounds applied to Trees. * * @param rootNode Root node of the tree. * @return The most promising node according to UCT. */ public Node getPromisingNode(Node rootNode) { Node promisingNode = rootNode; // Iterate until a node that hasn't been expanded is found. while (promisingNode.childNodes.size() != 0) { double uctIndex = Double.MIN_VALUE; int nodeIndex = 0; // Iterate through child nodes and pick the most promising one // using UCT (Upper Confidence bounds applied to Trees). for (int i = 0; i < promisingNode.childNodes.size(); i++) { Node childNode = promisingNode.childNodes.get(i); double uctTemp; // If child node has never been visited // it will have the highest uct value. if (childNode.visitCount == 0) { nodeIndex = i; break; } uctTemp = ((double) childNode.score / childNode.visitCount) + 1.41 * Math.sqrt(Math.log(promisingNode.visitCount) / (double) childNode.visitCount); if (uctTemp > uctIndex) { uctIndex = uctTemp; nodeIndex = i; } } promisingNode = promisingNode.childNodes.get(nodeIndex); } return promisingNode; } /** * Simulates a random play from a nodes current state and back propagates * the result. * * @param promisingNode Node that will be simulated. */ public void simulateRandomPlay(Node promisingNode) { Random rand = new Random(); Node tempNode = promisingNode; boolean isPlayerWinner; // The following line randomly determines whether the simulated play is a win or loss. // To use the MCTS algorithm correctly this should be a simulation of the nodes' current // state of the game until it finishes (if possible) and use an evaluation function to // determine how good or bad the play was. // e.g. Play tic tac toe choosing random squares until the game ends. promisingNode.playerWon = (rand.nextInt(6) == 0); isPlayerWinner = promisingNode.playerWon; // Back propagation of the random play. while (tempNode != null) { tempNode.visitCount++; // Add wining scores to bouth player and opponent depending on the turn. if ((tempNode.isPlayersTurn && isPlayerWinner) || (!tempNode.isPlayersTurn && !isPlayerWinner)) { tempNode.score += WIN_SCORE; } tempNode = tempNode.parent; } } public Node getWinnerNode(Node rootNode) { return Collections.max(rootNode.childNodes, Comparator.comparing(c -> c.score)); } public void printScores(Node rootNode) { System.out.println("N.\tScore\t\tVisits"); for (int i = 0; i < rootNode.childNodes.size(); i++) { System.out.printf("%02d\t%d\t\t%d%n", i + 1, rootNode.childNodes.get(i).score, rootNode.childNodes.get(i).visitCount); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/QuickSelect.java
src/main/java/com/thealgorithms/searches/QuickSelect.java
package com.thealgorithms.searches; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; /** * An implementation of the Quickselect algorithm as described * <a href="https://en.wikipedia.org/wiki/Median_of_medians">here</a>. */ public final class QuickSelect { private QuickSelect() { } /** * Selects the {@code n}-th largest element of {@code list}, i.e. the element that would * be at index n if the list was sorted. * <p> * Calling this function might change the order of elements in {@code list}. * * @param list the list of elements * @param n the index * @param <T> the type of list elements * @return the n-th largest element in the list * @throws IndexOutOfBoundsException if n is less than 0 or greater or equal to * the number of elements in the list * @throws IllegalArgumentException if the list is empty * @throws NullPointerException if {@code list} is null */ public static <T extends Comparable<T>> T select(List<T> list, int n) { Objects.requireNonNull(list, "The list of elements must not be null."); if (list.isEmpty()) { String msg = "The list of elements must not be empty."; throw new IllegalArgumentException(msg); } if (n < 0) { String msg = "The index must not be negative."; throw new IndexOutOfBoundsException(msg); } if (n >= list.size()) { String msg = "The index must be less than the number of elements."; throw new IndexOutOfBoundsException(msg); } int index = selectIndex(list, n); return list.get(index); } private static <T extends Comparable<T>> int selectIndex(List<T> list, int n) { return selectIndex(list, 0, list.size() - 1, n); } private static <T extends Comparable<T>> int selectIndex(List<T> list, int left, int right, int n) { while (true) { if (left == right) { return left; } int pivotIndex = pivot(list, left, right); pivotIndex = partition(list, left, right, pivotIndex, n); if (n == pivotIndex) { return n; } else if (n < pivotIndex) { right = pivotIndex - 1; } else { left = pivotIndex + 1; } } } private static <T extends Comparable<T>> int partition(List<T> list, int left, int right, int pivotIndex, int n) { T pivotValue = list.get(pivotIndex); Collections.swap(list, pivotIndex, right); int storeIndex = left; for (int i = left; i < right; i++) { if (list.get(i).compareTo(pivotValue) < 0) { Collections.swap(list, storeIndex, i); storeIndex++; } } int storeIndexEq = storeIndex; for (int i = storeIndex; i < right; i++) { if (list.get(i).compareTo(pivotValue) == 0) { Collections.swap(list, storeIndexEq, i); storeIndexEq++; } } Collections.swap(list, right, storeIndexEq); return (n < storeIndex) ? storeIndex : Math.min(n, storeIndexEq); } private static <T extends Comparable<T>> int pivot(List<T> list, int left, int right) { if (right - left < 5) { return partition5(list, left, right); } for (int i = left; i < right; i += 5) { int subRight = i + 4; if (subRight > right) { subRight = right; } int median5 = partition5(list, i, subRight); int rightIndex = left + (i - left) / 5; Collections.swap(list, median5, rightIndex); } int mid = (right - left) / 10 + left + 1; int rightIndex = left + (right - left) / 5; return selectIndex(list, left, rightIndex, mid); } private static <T extends Comparable<T>> int partition5(List<T> list, int left, int right) { List<T> ts = list.subList(left, right); ts.sort(Comparator.naturalOrder()); return (left + right) >>> 1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java
src/main/java/com/thealgorithms/searches/DepthFirstSearch.java
package com.thealgorithms.searches; import com.thealgorithms.datastructures.Node; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * @author: caos321 * @date: 31 October 2021 (Sunday) * @wiki: https://en.wikipedia.org/wiki/Depth-first_search */ public class DepthFirstSearch<T> { private final List<T> visited = new ArrayList<>(); public Optional<Node<T>> recursiveSearch(final Node<T> node, final Integer value) { if (node == null) { return Optional.empty(); } visited.add(node.getValue()); if (node.getValue().equals(value)) { return Optional.of(node); } return node.getChildren().stream().map(v -> recursiveSearch(v, value)).flatMap(Optional::stream).findAny(); } public List<T> getVisited() { return visited; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/LinearSearch.java
src/main/java/com/thealgorithms/searches/LinearSearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * Linear search is the easiest search algorithm It works with sorted and * unsorted arrays (an binary search works only with sorted array) This * algorithm just compares all elements of an array to find a value * * <p> * Worst-case performance O(n) Best-case performance O(1) Average performance * O(n) Worst-case space complexity * * @author Varun Upadhyay (https://github.com/varunu28) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see BinarySearch * @see SearchAlgorithm */ public class LinearSearch implements SearchAlgorithm { /** * Generic Linear search method * * @param array List to be searched * @param value Key being searched for * @return Location of the key */ @Override public <T extends Comparable<T>> int find(T[] array, T value) { for (int i = 0; i < array.length; i++) { if (array[i].compareTo(value) == 0) { return i; } } return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/UnionFind.java
src/main/java/com/thealgorithms/searches/UnionFind.java
package com.thealgorithms.searches; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * The Union-Find data structure, also known as Disjoint Set Union (DSU), * is a data structure that tracks a set of elements partitioned into * disjoint (non-overlapping) subsets. It supports two main operations: * * 1. **Find**: Determine which subset a particular element is in. * 2. **Union**: Join two subsets into a single subset. * * This implementation uses path compression in the `find` operation * and union by rank in the `union` operation for efficiency. */ public class UnionFind { private final int[] p; // Parent array private final int[] r; // Rank array /** * Initializes a Union-Find data structure with n elements. * Each element is its own parent initially. * * @param n the number of elements */ public UnionFind(int n) { p = new int[n]; r = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; } } /** * Finds the root of the set containing the element i. * Uses path compression to flatten the structure. * * @param i the element to find * @return the root of the set */ public int find(int i) { int parent = p[i]; if (i == parent) { return i; } // Path compression final int result = find(parent); p[i] = result; return result; } /** * Unites the sets containing elements x and y. * Uses union by rank to attach the smaller tree under the larger tree. * * @param x the first element * @param y the second element */ public void union(int x, int y) { int r0 = find(x); int r1 = find(y); if (r1 == r0) { return; } // Union by rank if (r[r0] > r[r1]) { p[r1] = r0; } else if (r[r1] > r[r0]) { p[r0] = r1; } else { p[r1] = r0; r[r0]++; } } /** * Counts the number of disjoint sets. * * @return the number of disjoint sets */ public int count() { List<Integer> parents = new ArrayList<>(); for (int i = 0; i < p.length; i++) { int root = find(i); if (!parents.contains(root)) { parents.add(root); } } return parents.size(); } @Override public String toString() { return "p " + Arrays.toString(p) + " r " + Arrays.toString(r) + "\n"; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java
src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java
package com.thealgorithms.searches; public final class SortOrderAgnosticBinarySearch { private SortOrderAgnosticBinarySearch() { } public static int find(int[] arr, int key) { int start = 0; int end = arr.length - 1; boolean arrDescending = arr[start] > arr[end]; // checking for Array is in ascending order or descending order. while (start <= end) { int mid = end - start / 2; if (arr[mid] == key) { return mid; } if (arrDescending) { // boolean is true then our array is in descending order if (key < arr[mid]) { start = mid + 1; } else { end = mid - 1; } } else { // otherwise our array is in ascending order if (key > arr[mid]) { start = mid + 1; } else { end = mid - 1; } } } return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
package com.thealgorithms.searches; // URL: https://www.geeksforgeeks.org/order-agnostic-binary-search/ /* Order Agnostic Binary Search is an algorithm where we do not know whether the given sorted array is ascending or descending order. We declare a boolean variable to find whether the array is ascending order. In the while loop, we use the two pointer method (start and end) to get the middle element. if the middle element is equal to our target element, then that is the answer. If not, then we check if the array is ascending or descending order. Depending upon the condition, respective statements will be executed and we will get our answer. */ public final class OrderAgnosticBinarySearch { private OrderAgnosticBinarySearch() { } static int binSearchAlgo(int[] arr, int start, int end, int target) { // Checking whether the given array is ascending order boolean ascOrd = arr[start] < arr[end]; while (start <= end) { int middle = start + (end - start) / 2; // Check if the desired element is present at the middle position if (arr[middle] == target) { return middle; // returns the index of the middle element } if (ascOrd) { // Ascending order if (arr[middle] < target) { start = middle + 1; } else { end = middle - 1; } } else { // Descending order if (arr[middle] > target) { start = middle + 1; } else { end = middle - 1; } } } // Element is not present return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java
src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.MatrixSearchAlgorithm; /** * The search is for any array which is sorted row and column-wise too. For ex : * {{10, 20, 30, 40}, * {15, 25, 35, 45}, * {18, 28, 38, 48}, * {21, 31, 41, 51}} * * This array is sorted in both row and column manner. * In this two pointers are taken, the first points to the 0th row and the second one points to end * column, and then the element corresponding to the pointers placed in the array is compared with * the target that either its equal, greater or smaller than the target. If the element is equal to * the target, the coordinates of that element is returned i.e. an array of the two pointers will * be returned, else if the target is greater than corresponding element then the pointer pointing * to the 0th row will be incremented by 1, else if the target is lesser than the corresponding * element then the pointer pointing to the end column will be decremented by 1. And if the element * doesn't exist in the array, an array * {-1, -1} will be returned. */ public class RowColumnWiseSorted2dArrayBinarySearch implements MatrixSearchAlgorithm { @Override public <T extends Comparable<T>> int[] find(T[][] matrix, T key) { return search(matrix, key); } public static <T extends Comparable<T>> int[] search(T[][] matrix, T target) { int rowPointer = 0; // The pointer at 0th row int colPointer = matrix[0].length - 1; // The pointer at end column while (rowPointer < matrix.length && colPointer >= 0) { int comp = target.compareTo(matrix[rowPointer][colPointer]); if (comp == 0) { return new int[] {rowPointer, colPointer}; } else if (comp > 0) { rowPointer++; // Incrementing the row pointer if the target is greater } else { colPointer--; // Decrementing the column pointer if the target is lesser } } return new int[] {-1, -1}; // The not found condition } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java
src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * Binary search is one of the most popular algorithms This class represents * iterative version {@link BinarySearch} Iterative binary search is likely to * have lower constant factors because it doesn't involve the overhead of * manipulating the call stack. But in java the recursive version can be * optimized by the compiler to this version. * * <p> * Worst-case performance O(log n) Best-case performance O(1) Average * performance O(log n) Worst-case space complexity O(1) * * @author Gabriele La Greca : https://github.com/thegabriele97 * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm * @see BinarySearch */ public final class IterativeBinarySearch implements SearchAlgorithm { /** * This method implements an iterative version of binary search algorithm * * @param array a sorted array * @param key the key to search in array * @return the index of key in the array or -1 if not found */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { int l; int r; int k; int cmp; l = 0; r = array.length - 1; while (l <= r) { k = (l + r) >>> 1; cmp = key.compareTo(array[k]); if (cmp == 0) { return k; } else if (cmp < 0) { r = --k; } else { l = ++k; } } return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/LinearSearchThread.java
src/main/java/com/thealgorithms/searches/LinearSearchThread.java
package com.thealgorithms.searches; /** * LinearSearchThread is a multithreaded implementation of the linear search algorithm. * It creates multiple threads to search for a specific number in an array. * * <p> * The class generates an array of random integers, prompts the user to enter a number to search for, * and divides the array into four segments, each handled by a separate thread. * The threads run concurrently and search for the specified number within their designated segments. * Finally, it consolidates the results to determine if the number was found. * </p> * * <p> * Example usage: * 1. The program will output the generated array. * 2. The user will be prompted to input a number to search for. * 3. The program will display whether the number was found in the array. * </p> */ public final class LinearSearchThread { private LinearSearchThread() { } } /** * The Searcher class extends Thread and is responsible for searching for a specific * number in a segment of an array. */ class Searcher extends Thread { private final int[] arr; // The array to search in private final int left; // Starting index of the segment private final int right; // Ending index of the segment private final int x; // The number to search for private boolean found; // Result flag /** * Constructor to initialize the Searcher. * * @param arr The array to search in * @param left The starting index of the segment * @param right The ending index of the segment * @param x The number to search for */ Searcher(int[] arr, int left, int right, int x) { this.arr = arr; this.left = left; this.right = right; this.x = x; } /** * The run method for the thread, performing the linear search in its segment. */ @Override public void run() { int k = left; found = false; while (k < right && !found) { if (arr[k++] == x) { found = true; } } } /** * Returns whether the number was found in the segment. * * @return true if the number was found, false otherwise */ boolean getResult() { return found; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/LowerBound.java
src/main/java/com/thealgorithms/searches/LowerBound.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * The LowerBound method is used to return an index pointing to the first * element in the range [first, last) which has a value not less than val, i.e. * the index of the next smallest number just greater than or equal to that * number. If there are multiple values that are equal to val it returns the * index of the first such value. * * <p> * This is an extension of BinarySearch. * * <p> * Worst-case performance O(log n) Best-case performance O(1) Average * performance O(log n) Worst-case space complexity O(1) * * @author Pratik Padalia (https://github.com/15pratik) * @see SearchAlgorithm * @see BinarySearch */ class LowerBound implements SearchAlgorithm { /** * @param array is an array where the LowerBound value is to be found * @param key is an element for which the LowerBound is to be found * @param <T> is any comparable type * @return index of the LowerBound element */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { return search(array, key, 0, array.length - 1); } /** * This method implements the Generic Binary Search * * @param array The array to make the binary search * @param key The number you are looking for * @param left The lower bound * @param right The upper bound * @return the location of the key */ private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) { if (right <= left) { return left; } // find median int median = (left + right) >>> 1; int comp = key.compareTo(array[median]); if (comp == 0) { return median; } else if (comp < 0) { // median position can be a possible solution return search(array, key, left, median); } else { // key we are looking is greater, so we must look on the right of median position return search(array, key, median + 1, right); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/BoyerMoore.java
src/main/java/com/thealgorithms/searches/BoyerMoore.java
package com.thealgorithms.searches; /** * Boyer-Moore string search algorithm. * Efficient algorithm for substring search. * https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm */ public class BoyerMoore { private final int radix; // Radix (number of possible characters) private final int[] right; // Bad character rule table private final String pattern; public BoyerMoore(String pat) { this.pattern = pat; this.radix = 256; this.right = new int[radix]; for (int c = 0; c < radix; c++) { right[c] = -1; } for (int j = 0; j < pat.length(); j++) { right[pat.charAt(j)] = j; } } public int search(String text) { if (pattern.isEmpty()) { return 0; } int m = pattern.length(); int n = text.length(); int skip; for (int i = 0; i <= n - m; i += skip) { skip = 0; for (int j = m - 1; j >= 0; j--) { char txtChar = text.charAt(i + j); char patChar = pattern.charAt(j); if (patChar != txtChar) { skip = Math.max(1, j - right[txtChar]); break; } } if (skip == 0) { return i; // Match found } } return -1; // No match } public static int staticSearch(String text, String pattern) { return new BoyerMoore(pattern).search(text); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java
src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * Binary search is one of the most popular algorithms The algorithm finds the * position of a target value within a sorted array * * <p> * Worst-case performance O(log n) Best-case performance O(1) Average * performance O(log n) Worst-case space complexity O(1) * * @author D Sunil (https://github.com/sunilnitdgp) * @see SearchAlgorithm */ public class PerfectBinarySearch<T> implements SearchAlgorithm { /** * @param array is an array where the element should be found * @param key is an element which should be found * @param <T> is any comparable type * @return index of the element */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { return search(array, key, 0, array.length - 1); } /** * This method implements the Generic Binary Search iteratively. * * @param array The array to make the binary search * @param key The number you are looking for * @return the location of the key, or -1 if not found */ private static <T extends Comparable<T>> int search(T[] array, T key, int left, int right) { while (left <= right) { int median = (left + right) >>> 1; int comp = key.compareTo(array[median]); if (comp == 0) { return median; // Key found } if (comp < 0) { right = median - 1; // Adjust the right bound } else { left = median + 1; // Adjust the left bound } } return -1; // Key not found } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java
src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java
package com.thealgorithms.searches; import java.util.Scanner; /* Problem Statement: Given an array, find out how many times it has to been rotated from its initial sorted position. Input-Output: Eg. [11,12,15,18,2,5,6,8] It has been rotated: 4 times (One rotation means putting the first element to the end) Note: The array cannot contain duplicates Logic: The position of the minimum element will give the number of times the array has been rotated from its initial sorted position. Eg. For [2,5,6,8,11,12,15,18], 1 rotation gives [5,6,8,11,12,15,18,2], 2 rotations [6,8,11,12,15,18,2,5] and so on. Finding the minimum element will take O(N) time but, we can use Binary Search to find the minimum element, we can reduce the complexity to O(log N). If we look at the rotated array, to identify the minimum element (say a[i]), we observe that a[i-1]>a[i]<a[i+1]. Some other test cases: 1. [1,2,3,4] Number of rotations: 0 or 4(Both valid) 2. [15,17,2,3,5] Number of rotations: 3 */ final class HowManyTimesRotated { private HowManyTimesRotated() { } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } System.out.println("The array has been rotated " + rotated(a) + " times"); sc.close(); } public static int rotated(int[] a) { int low = 0; int high = a.length - 1; int mid = 0; // low + (high-low)/2 = (low + high)/2 while (low <= high) { mid = low + (high - low) / 2; if (a[mid] < a[mid - 1] && a[mid] < a[mid + 1]) { break; } else if (a[mid] > a[mid - 1] && a[mid] < a[mid + 1]) { high = mid + 1; } else if (a[mid] > a[mid - 1] && a[mid] > a[mid + 1]) { low = mid - 1; } } return mid; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java
src/main/java/com/thealgorithms/searches/SaddlebackSearch.java
package com.thealgorithms.searches; /** * Program to perform Saddleback Search Given a sorted 2D array(elements are * sorted across every row and column, assuming ascending order) of size n*m we * can search a given element in O(n+m) * * <p> * we start from bottom left corner if the current element is greater than the * given element then we move up else we move right Sample Input: 5 5 * ->Dimensions -10 -5 -3 4 9 -6 -2 0 5 10 -4 -1 1 6 12 2 3 7 8 13 100 120 130 * 140 150 140 ->element to be searched output: 4 3 // first value is row, * second one is column * * @author Nishita Aggarwal */ public final class SaddlebackSearch { private SaddlebackSearch() { } /** * This method performs Saddleback Search * * @param arr The **Sorted** array in which we will search the element. * @param row the current row. * @param col the current column. * @param key the element that we want to search for. * @throws IllegalArgumentException if the array is empty. * @return The index(row and column) of the element if found. Else returns * -1 -1. */ static int[] find(int[][] arr, int row, int col, int key) { if (arr.length == 0) { throw new IllegalArgumentException("Array is empty"); } // array to store the answer row and column int[] ans = {-1, -1}; if (row < 0 || col >= arr[row].length) { return ans; } if (arr[row][col] == key) { ans[0] = row; ans[1] = col; return ans; } // if the current element is greater than the given element then we move up else if (arr[row][col] > key) { return find(arr, row - 1, col, key); } // else we move right return find(arr, row, col + 1, key); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java
src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java
// Code by Pronay Debnath // Created:- 1/10/2023 // File Name should be RecursiveBinarySearch.java // Explanation:- https://www.tutorialspoint.com/java-program-for-binary-search-recursive package com.thealgorithms.searches; import java.util.Scanner; // Create a SearchAlgorithm class with a generic type abstract class SearchAlgorithm<T extends Comparable<T>> { // Abstract find method to be implemented by subclasses public abstract int find(T[] arr, T target); } public class RecursiveBinarySearch<T extends Comparable<T>> extends SearchAlgorithm<T> { // Override the find method as required @Override public int find(T[] arr, T target) { // Call the recursive binary search function return binsear(arr, 0, arr.length - 1, target); } // Recursive binary search function public int binsear(T[] arr, int left, int right, T target) { if (right >= left) { int mid = left + (right - left) / 2; // Compare the element at the middle with the target int comparison = arr[mid].compareTo(target); // If the element is equal to the target, return its index if (comparison == 0) { return mid; } // If the element is greater than the target, search in the left subarray if (comparison > 0) { return binsear(arr, left, mid - 1, target); } // Otherwise, search in the right subarray return binsear(arr, mid + 1, right, target); } // Element is not present in the array return -1; } public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { // User inputs System.out.print("Enter the number of elements in the array: "); int n = sc.nextInt(); Integer[] a = new Integer[n]; // You can change the array type as needed System.out.println("Enter the elements in sorted order:"); for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } System.out.print("Enter the target element to search for: "); int t = sc.nextInt(); RecursiveBinarySearch<Integer> searcher = new RecursiveBinarySearch<>(); int res = searcher.find(a, t); if (res == -1) { System.out.println("Element not found in the array."); } else { System.out.println("Element found at index " + res); } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java
src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java
package com.thealgorithms.searches; public class SearchInARowAndColWiseSortedMatrix { /** * Search a key in row and column wise sorted matrix * * @param matrix matrix to be searched * @param value Key being searched for * @author Sadiul Hakim : https://github.com/sadiul-hakim */ public int[] search(int[][] matrix, int value) { int n = matrix.length; // This variable iterates over rows int i = 0; // This variable iterates over columns int j = n - 1; int[] result = {-1, -1}; while (i < n && j >= 0) { if (matrix[i][j] == value) { result[0] = i; result[1] = j; return result; } if (value > matrix[i][j]) { i++; } else { j--; } } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java
src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java
package com.thealgorithms.searches; /** * This class provides a method to search for a target value in a 2D sorted * array. * The search is performed using a combination of binary search on rows and * columns. * The 2D array must be strictly sorted in both rows and columns. * * The algorithm works by: * 1. Performing a binary search on the middle column of the 2D array. * 2. Depending on the value found, it eliminates rows above or below the middle * element. * 3. After finding or eliminating rows, it further applies binary search in the * relevant columns. */ public final class BinarySearch2dArray { private BinarySearch2dArray() { } /** * Performs a binary search on a 2D sorted array to find the target value. * The array must be sorted in ascending order in both rows and columns. * * @param arr The 2D array to search in. * @param target The value to search for. * @return An array containing the row and column indices of the target, or [-1, * -1] if the target is not found. */ static int[] binarySearch(int[][] arr, int target) { int rowCount = arr.length; int colCount = arr[0].length; // Edge case: If there's only one row, search that row directly. if (rowCount == 1) { return binarySearch(arr, target, 0, 0, colCount); } // Set initial boundaries for binary search on rows. int startRow = 0; int endRow = rowCount - 1; int midCol = colCount / 2; // Middle column index for comparison. // Perform binary search on rows based on the middle column. while (startRow < endRow - 1) { int midRow = startRow + (endRow - startRow) / 2; // If the middle element matches the target, return its position. if (arr[midRow][midCol] == target) { return new int[] {midRow, midCol}; } // If the middle element is smaller than the target, discard the upper half. else if (arr[midRow][midCol] < target) { startRow = midRow; } // If the middle element is larger than the target, discard the lower half. else { endRow = midRow; } } // If the target wasn't found during the row search, check the middle column of // startRow and endRow. if (arr[startRow][midCol] == target) { return new int[] {startRow, midCol}; } if (arr[endRow][midCol] == target) { return new int[] {endRow, midCol}; } // If target is smaller than the element in the left of startRow, perform a // binary search on the left of startRow. if (target <= arr[startRow][midCol - 1]) { return binarySearch(arr, target, startRow, 0, midCol - 1); } // If target is between midCol and the last column of startRow, perform a binary // search on that part of the row. if (target >= arr[startRow][midCol + 1] && target <= arr[startRow][colCount - 1]) { return binarySearch(arr, target, startRow, midCol + 1, colCount - 1); } // If target is smaller than the element in the left of endRow, perform a binary // search on the left of endRow. if (target <= arr[endRow][midCol - 1]) { return binarySearch(arr, target, endRow, 0, midCol - 1); } else { // Otherwise, search on the right of endRow. return binarySearch(arr, target, endRow, midCol + 1, colCount - 1); } } /** * Performs a binary search on a specific row of the 2D array. * * @param arr The 2D array to search in. * @param target The value to search for. * @param row The row index where the target will be searched. * @param colStart The starting column index for the search. * @param colEnd The ending column index for the search. * @return An array containing the row and column indices of the target, or [-1, * -1] if the target is not found. */ static int[] binarySearch(int[][] arr, int target, int row, int colStart, int colEnd) { // Perform binary search within the specified column range. while (colStart <= colEnd) { int midIndex = colStart + (colEnd - colStart) / 2; // If the middle element matches the target, return its position. if (arr[row][midIndex] == target) { return new int[] {row, midIndex}; } // If the middle element is smaller than the target, move to the right half. else if (arr[row][midIndex] < target) { colStart = midIndex + 1; } // If the middle element is larger than the target, move to the left half. else { colEnd = midIndex - 1; } } return new int[] {-1, -1}; // Target not found } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/SentinelLinearSearch.java
src/main/java/com/thealgorithms/searches/SentinelLinearSearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * Sentinel Linear Search is a variation of linear search that eliminates the * need to check the array bounds in each iteration by placing the search key * at the end of the array as a sentinel value. * * <p> * The algorithm works by: * 1. Storing the last element of the array * 2. Placing the search key at the last position (sentinel) * 3. Searching from the beginning without bound checking * 4. If found before the last position, return the index * 5. If found at the last position, check if it was originally there * * <p> * Time Complexity: * - Best case: O(1) - when the element is at the first position * - Average case: O(n) - when the element is in the middle * - Worst case: O(n) - when the element is not present * * <p> * Space Complexity: O(1) - only uses constant extra space * * <p> * Advantages over regular linear search: * - Reduces the number of comparisons by eliminating bound checking * - Slightly more efficient in practice due to fewer conditional checks * * @author TheAlgorithms Contributors * @see LinearSearch * @see SearchAlgorithm */ public class SentinelLinearSearch implements SearchAlgorithm { /** * Performs sentinel linear search on the given array. * * @param array the array to search in * @param key the element to search for * @param <T> the type of elements in the array, must be Comparable * @return the index of the first occurrence of the key, or -1 if not found * @throws IllegalArgumentException if the array is null */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { if (array == null) { throw new IllegalArgumentException("Array cannot be null"); } if (array.length == 0) { return -1; } if (key == null) { return findNull(array); } // Store the last element T lastElement = array[array.length - 1]; // Place the sentinel (search key) at the end array[array.length - 1] = key; int i = 0; // Search without bound checking since sentinel guarantees we'll find the key while (array[i].compareTo(key) != 0) { i++; } // Restore the original last element array[array.length - 1] = lastElement; // Check if we found the key before the sentinel position // or if the original last element was the key we were looking for if (i < array.length - 1 || (lastElement != null && lastElement.compareTo(key) == 0)) { return i; } return -1; // Key not found } /** * Helper method to find null values in the array. * * @param array the array to search in * @param <T> the type of elements in the array * @return the index of the first null element, or -1 if not found */ private <T extends Comparable<T>> int findNull(T[] array) { for (int i = 0; i < array.length; i++) { if (array[i] == null) { return i; } } return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/InterpolationSearch.java
src/main/java/com/thealgorithms/searches/InterpolationSearch.java
package com.thealgorithms.searches; /** * InterpolationSearch is an algorithm that searches for a target value within a sorted array * by estimating the position based on the values at the corners of the current search range. * * <p> * The performance of this algorithm can vary: * - Worst-case performance: O(n) * - Best-case performance: O(1) * - Average performance: O(log(log(n))) if the elements are uniformly distributed; otherwise O(n) * - Worst-case space complexity: O(1) * </p> * * <p> * This search algorithm requires the input array to be sorted. * </p> * * @author Podshivalov Nikita (https://github.com/nikitap492) */ class InterpolationSearch { /** * Finds the index of the specified key in a sorted array using interpolation search. * * @param array The sorted array to search. * @param key The value to search for. * @return The index of the key if found, otherwise -1. */ public int find(int[] array, int key) { // Find indexes of two corners int start = 0; int end = (array.length - 1); // Since array is sorted, an element present // in array must be in range defined by corner while (start <= end && key >= array[start] && key <= array[end]) { // Probing the position with keeping // uniform distribution in mind. int pos = start + (((end - start) / (array[end] - array[start])) * (key - array[start])); // Condition of target found if (array[pos] == key) { return pos; } // If key is larger, key is in upper part if (array[pos] < key) { start = pos + 1; } // If key is smaller, x is in lower part else { end = pos - 1; } } return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java
src/main/java/com/thealgorithms/searches/BreadthFirstSearch.java
package com.thealgorithms.searches; import com.thealgorithms.datastructures.Node; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Queue; import java.util.Set; /** * Breadth-First Search implementation for tree/graph traversal. * @author caos321 * @co-author @manishraj27 * @see <a href="https://en.wikipedia.org/wiki/Breadth-first_search">Breadth-first search</a> */ public class BreadthFirstSearch<T> { private final List<T> visited = new ArrayList<>(); private final Set<T> visitedSet = new HashSet<>(); /** * Performs a breadth-first search to find a node with the given value. * * @param root The root node to start the search from * @param value The value to search for * @return Optional containing the found node, or empty if not found */ public Optional<Node<T>> search(final Node<T> root, final T value) { if (root == null) { return Optional.empty(); } visited.add(root.getValue()); visitedSet.add(root.getValue()); if (root.getValue() == value) { return Optional.of(root); } Queue<Node<T>> queue = new ArrayDeque<>(root.getChildren()); while (!queue.isEmpty()) { final Node<T> current = queue.poll(); T currentValue = current.getValue(); if (visitedSet.contains(currentValue)) { continue; } visited.add(currentValue); visitedSet.add(currentValue); if (currentValue == value || (value != null && value.equals(currentValue))) { return Optional.of(current); } queue.addAll(current.getChildren()); } return Optional.empty(); } /** * Returns the list of nodes in the order they were visited. * * @return List containing the visited nodes */ public List<T> getVisited() { return visited; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/TernarySearch.java
src/main/java/com/thealgorithms/searches/TernarySearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * A ternary search algorithm is a technique in computer science for finding the * minimum or maximum of a unimodal function The algorithm determines either * that the minimum or maximum cannot be in the first third of the domain or * that it cannot be in the last third of the domain, then repeats on the * remaining third. * * <p> * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average * performance Θ(log3(N)) Worst-case space complexity O(1) * * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm * @see IterativeBinarySearch */ public class TernarySearch implements SearchAlgorithm { /** * @param arr The **Sorted** array in which we will search the element. * @param value The value that we want to search for. * @return The index of the element if found. Else returns -1. */ @Override public <T extends Comparable<T>> int find(T[] arr, T value) { return ternarySearch(arr, value, 0, arr.length - 1); } /** * @param arr The **Sorted** array in which we will search the element. * @param key The value that we want to search for. * @param start The starting index from which we will start Searching. * @param end The ending index till which we will Search. * @return Returns the index of the Element if found. Else returns -1. */ private <T extends Comparable<T>> int ternarySearch(T[] arr, T key, int start, int end) { if (start > end) { return -1; } /* First boundary: add 1/3 of length to start */ int mid1 = start + (end - start) / 3; /* Second boundary: add 2/3 of length to start */ int mid2 = start + 2 * (end - start) / 3; if (key.compareTo(arr[mid1]) == 0) { return mid1; } else if (key.compareTo(arr[mid2]) == 0) { return mid2; } /* Search the first (1/3) rd part of the array.*/ else if (key.compareTo(arr[mid1]) < 0) { return ternarySearch(arr, key, start, --mid1); } /* Search 3rd (1/3)rd part of the array */ else if (key.compareTo(arr[mid2]) > 0) { return ternarySearch(arr, key, ++mid2, end); } /* Search middle (1/3)rd part of the array */ else { return ternarySearch(arr, key, mid1, mid2); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java
src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * An iterative implementation of the Ternary Search algorithm. * * <p> * Ternary search is a divide-and-conquer algorithm that splits the array into three parts * instead of two, as in binary search. This implementation is iterative, reducing the overhead * associated with recursive function calls. However, the recursive version can also be optimized * by the Java compiler to resemble the iterative version, resulting in similar performance. * * <p> * Worst-case performance: Θ(log3(N))<br> * Best-case performance: O(1)<br> * Average performance: Θ(log3(N))<br> * Worst-case space complexity: O(1) * * <p> * This class implements the {@link SearchAlgorithm} interface, providing a generic search method * for any comparable type. * * @see SearchAlgorithm * @see TernarySearch * @since 2018-04-13 */ public class IterativeTernarySearch implements SearchAlgorithm { @Override public <T extends Comparable<T>> int find(T[] array, T key) { if (array == null || array.length == 0 || key == null) { return -1; } if (array.length == 1) { return array[0].compareTo(key) == 0 ? 0 : -1; } int left = 0; int right = array.length - 1; while (right > left) { int leftCmp = array[left].compareTo(key); int rightCmp = array[right].compareTo(key); if (leftCmp == 0) { return left; } if (rightCmp == 0) { return right; } int leftThird = left + (right - left) / 3 + 1; int rightThird = right - (right - left) / 3 - 1; if (array[leftThird].compareTo(key) <= 0) { left = leftThird; } else { right = rightThird; } } return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java
src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java
package com.thealgorithms.searches; /** * Given an integer x, find the square root of x. If x is not a perfect square, * then return floor(√x). * <p> * For example, if x = 5, The answer should be 2 which is the floor value of √5. * <p> * The approach that will be used for solving the above problem is not going to * be a straight forward Math.sqrt(). Instead we will be using Binary Search to * find the square root of a number in the most optimised way. * * @author sahil */ public final class SquareRootBinarySearch { private SquareRootBinarySearch() { } /** * This function calculates the floor of square root of a number. We use * Binary Search algorithm to calculate the square root in a more optimised * way. * * @param num Number * @return answer */ static long squareRoot(long num) { if (num == 0 || num == 1) { return num; } long l = 1; long r = num; long ans = 0; while (l <= r) { long mid = l + (r - l) / 2; if (mid == num / mid) { return mid; } else if (mid < num / mid) { ans = mid; l = mid + 1; } else { r = mid - 1; } } return ans; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/RandomSearch.java
src/main/java/com/thealgorithms/searches/RandomSearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.HashSet; import java.util.Random; import java.util.Set; /** * A Random Search algorithm that randomly selects an index and checks if the * value at that index matches the target. It repeats the process until it * finds the target or checks all elements. * * <p> * Time Complexity: O(n) in the worst case. * </p> * * @author Hardvan */ public class RandomSearch implements SearchAlgorithm { private final Random random = new Random(); /** * Finds the index of a given element using random search. * * @param array Array to search through * @param key Element to search for * @return Index of the element if found, -1 otherwise */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { Set<Integer> visitedIndices = new HashSet<>(); int size = array.length; while (visitedIndices.size() < size) { int randomIndex = random.nextInt(size); if (array[randomIndex].compareTo(key) == 0) { return randomIndex; } visitedIndices.add(randomIndex); } return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/FibonacciSearch.java
src/main/java/com/thealgorithms/searches/FibonacciSearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * FibonacciSearch is a search algorithm that finds the position of a target value in * a sorted array using Fibonacci numbers. * * <p> * The time complexity for this search algorithm is O(log n). * The space complexity for this search algorithm is O(1). * </p> * * <p> * Note: This algorithm requires that the input array be sorted. * </p> */ @SuppressWarnings({"rawtypes", "unchecked"}) public class FibonacciSearch implements SearchAlgorithm { /** * Finds the index of the specified key in a sorted array using Fibonacci search. * * @param array The sorted array to search. * @param key The element to search for. * @param <T> The type of the elements in the array, which must be comparable. * @throws IllegalArgumentException if the input array is not sorted or empty, or if the key is null. * @return The index of the key if found, otherwise -1. */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { if (array.length == 0) { throw new IllegalArgumentException("Input array must not be empty."); } if (!isSorted(array)) { throw new IllegalArgumentException("Input array must be sorted."); } if (key == null) { throw new IllegalArgumentException("Key must not be null."); } int fibMinus1 = 1; int fibMinus2 = 0; int fibNumber = fibMinus1 + fibMinus2; int n = array.length; while (fibNumber < n) { fibMinus2 = fibMinus1; fibMinus1 = fibNumber; fibNumber = fibMinus2 + fibMinus1; } int offset = -1; while (fibNumber > 1) { int i = Math.min(offset + fibMinus2, n - 1); if (array[i].compareTo(key) < 0) { fibNumber = fibMinus1; fibMinus1 = fibMinus2; fibMinus2 = fibNumber - fibMinus1; offset = i; } else if (array[i].compareTo(key) > 0) { fibNumber = fibMinus2; fibMinus1 = fibMinus1 - fibMinus2; fibMinus2 = fibNumber - fibMinus1; } else { return i; } } if (fibMinus1 == 1 && array[offset + 1] == key) { return offset + 1; } return -1; } private boolean isSorted(Comparable[] array) { for (int i = 1; i < array.length; i++) { if (array[i - 1].compareTo(array[i]) > 0) { return false; } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/ExponentialSearch.java
src/main/java/com/thealgorithms/searches/ExponentialSearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; import java.util.Arrays; /** * ExponentialSearch is an algorithm that efficiently finds the position of a target * value within a sorted array. It works by expanding the range to find the bounds * where the target might exist and then using binary search within that range. * * <p> * Worst-case time complexity: O(log n) * Best-case time complexity: O(1) when the element is found at the first position. * Average time complexity: O(log n) * Worst-case space complexity: O(1) * </p> * * <p> * Note: This algorithm requires that the input array be sorted. * </p> */ class ExponentialSearch implements SearchAlgorithm { /** * Finds the index of the specified key in a sorted array using exponential search. * * @param array The sorted array to search. * @param key The element to search for. * @param <T> The type of the elements in the array, which must be comparable. * @return The index of the key if found, otherwise -1. */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { if (array.length == 0) { return -1; } if (array[0].equals(key)) { return 0; } if (array[array.length - 1].equals(key)) { return array.length - 1; } int range = 1; while (range < array.length && array[range].compareTo(key) < 0) { range = range * 2; } return Arrays.binarySearch(array, range / 2, Math.min(range, array.length), key); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/KMPSearch.java
src/main/java/com/thealgorithms/searches/KMPSearch.java
package com.thealgorithms.searches; class KMPSearch { int kmpSearch(String pat, String txt) { int m = pat.length(); int n = txt.length(); // create lps[] that will hold the longest // prefix suffix values for pattern int[] lps = new int[m]; int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] // array) computeLPSArray(pat, m, lps); int i = 0; // index for txt[] while ((n - i) >= (m - j)) { if (pat.charAt(j) == txt.charAt(i)) { j++; i++; } if (j == m) { System.out.println("Found pattern " + "at index " + (i - j)); int index = (i - j); j = lps[j - 1]; return index; } // mismatch after j matches else if (i < n && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) { j = lps[j - 1]; } else { i = i + 1; } } } System.out.println("No pattern found"); return -1; } void computeLPSArray(String pat, int m, int[] lps) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to m-1 while (i < m) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else { // (pat[i] != pat[len]) // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; // Also, note that we do not increment // i here } else { // if (len == 0) lps[i] = len; i++; } } } } } // This code has been contributed by Amit Khandelwal.
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java
src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java
package com.thealgorithms.searches; // Implementation of Rabin Karp Algorithm public final class RabinKarpAlgorithm { private RabinKarpAlgorithm() { } private static final int ALPHABET_SIZE = 256; public static int search(String pattern, String text, int primeNumber) { int index = -1; // -1 here represents not found int patternLength = pattern.length(); int textLength = text.length(); int hashForPattern = 0; int hashForText = 0; int h = 1; // The value of h would be "pow(d, patternLength-1)%primeNumber" for (int i = 0; i < patternLength - 1; i++) { h = (h * ALPHABET_SIZE) % primeNumber; } // Calculate the hash value of pattern and first // window of text for (int i = 0; i < patternLength; i++) { hashForPattern = (ALPHABET_SIZE * hashForPattern + pattern.charAt(i)) % primeNumber; hashForText = (ALPHABET_SIZE * hashForText + text.charAt(i)) % primeNumber; } // Slide the pattern over text one by one for (int i = 0; i <= textLength - patternLength; i++) { /* Check the hash values of current window of text and pattern. If the hash values match then only check for characters one by one*/ int j = 0; if (hashForPattern == hashForText) { /* Check for characters one by one */ for (j = 0; j < patternLength; j++) { if (text.charAt(i + j) != pattern.charAt(j)) { break; } } // if hashForPattern == hashForText and pattern[0...patternLength-1] = text[i, i+1, ...i+patternLength-1] if (j == patternLength) { index = i; return index; } } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if (i < textLength - patternLength) { hashForText = (ALPHABET_SIZE * (hashForText - text.charAt(i) * h) + text.charAt(i + patternLength)) % primeNumber; // handling negative hashForText if (hashForText < 0) { hashForText = (hashForText + primeNumber); } } } return index; // return -1 if pattern does not found } } // This code is contributed by nuclode
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/UpperBound.java
src/main/java/com/thealgorithms/searches/UpperBound.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * The UpperBound method is used to return an index pointing to the first * element in the range [first, last) which has a value greater than val, or the * last index if no such element exists i.e. the index of the next smallest * number just greater than that number. If there are multiple values that are * equal to val it returns the index of the first such value. * * <p> * This is an extension of BinarySearch. * * <p> * Worst-case performance O(log n) Best-case performance O(1) Average * performance O(log n) Worst-case space complexity O(1) * * @author Pratik Padalia (https://github.com/15pratik) * @see SearchAlgorithm * @see BinarySearch */ class UpperBound implements SearchAlgorithm { /** * @param array is an array where the UpperBound value is to be found * @param key is an element for which the UpperBound is to be found * @param <T> is any comparable type * @return index of the UpperBound element */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { return search(array, key, 0, array.length - 1); } /** * This method implements the Generic Binary Search * * @param array The array to make the binary search * @param key The number you are looking for * @param left The lower bound * @param right The upper bound * @return the location of the key */ private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) { if (right <= left) { return left; } // find median int median = (left + right) >>> 1; int comp = key.compareTo(array[median]); if (comp < 0) { // key is smaller, median position can be a possible solution return search(array, key, left, median); } else { // key we are looking is greater, so we must look on the right of median position return search(array, key, median + 1, right); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/BM25InvertedIndex.java
src/main/java/com/thealgorithms/searches/BM25InvertedIndex.java
package com.thealgorithms.searches; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * Inverted Index implementation with BM25 Scoring for movie search. * This class supports adding movie documents and searching for terms * within those documents using the BM25 algorithm. * @author Prayas Kumar (https://github.com/prayas7102) */ class Movie { int docId; // Unique identifier for the movie String name; // Movie name double imdbRating; // IMDb rating of the movie int releaseYear; // Year the movie was released String content; // Full text content (could be the description or script) /** * Constructor for the Movie class. * @param docId Unique identifier for the movie. * @param name Name of the movie. * @param imdbRating IMDb rating of the movie. * @param releaseYear Release year of the movie. * @param content Content or description of the movie. */ Movie(int docId, String name, double imdbRating, int releaseYear, String content) { this.docId = docId; this.name = name; this.imdbRating = imdbRating; this.releaseYear = releaseYear; this.content = content; } /** * Get all the words from the movie's name and content. * Converts the name and content to lowercase and splits on non-word characters. * @return Array of words from the movie name and content. */ public String[] getWords() { return (name + " " + content).toLowerCase().split("\\W+"); } @Override public String toString() { return "Movie{" + "docId=" + docId + ", name='" + name + '\'' + ", imdbRating=" + imdbRating + ", releaseYear=" + releaseYear + '}'; } } class SearchResult { int docId; // Unique identifier of the movie document double relevanceScore; // Relevance score based on the BM25 algorithm /** * Constructor for SearchResult class. * @param docId Document ID (movie) for this search result. * @param relevanceScore The relevance score based on BM25 scoring. */ SearchResult(int docId, double relevanceScore) { this.docId = docId; this.relevanceScore = relevanceScore; } public int getDocId() { return docId; } @Override public String toString() { return "SearchResult{" + "docId=" + docId + ", relevanceScore=" + relevanceScore + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SearchResult that = (SearchResult) o; return docId == that.docId && Double.compare(that.relevanceScore, relevanceScore) == 0; } @Override public int hashCode() { return Objects.hash(docId, relevanceScore); } public double getRelevanceScore() { return this.relevanceScore; } } public final class BM25InvertedIndex { private Map<String, Map<Integer, Integer>> index; // Inverted index mapping terms to document id and frequency private Map<Integer, Movie> movies; // Mapping of movie document IDs to Movie objects private int totalDocuments; // Total number of movies/documents private double avgDocumentLength; // Average length of documents (number of words) private static final double K = 1.5; // BM25 tuning parameter, controls term frequency saturation private static final double B = 0.75; // BM25 tuning parameter, controls length normalization /** * Constructor for BM25InvertedIndex. * Initializes the inverted index and movie storage. */ BM25InvertedIndex() { index = new HashMap<>(); movies = new HashMap<>(); totalDocuments = 0; avgDocumentLength = 0.0; } /** * Add a movie to the index. * @param docId Unique identifier for the movie. * @param name Name of the movie. * @param imdbRating IMDb rating of the movie. * @param releaseYear Release year of the movie. * @param content Content or description of the movie. */ public void addMovie(int docId, String name, double imdbRating, int releaseYear, String content) { Movie movie = new Movie(docId, name, imdbRating, releaseYear, content); movies.put(docId, movie); totalDocuments++; // Get words (terms) from the movie's name and content String[] terms = movie.getWords(); int docLength = terms.length; // Update the average document length avgDocumentLength = (avgDocumentLength * (totalDocuments - 1) + docLength) / totalDocuments; // Update the inverted index for (String term : terms) { // Create a new entry if the term is not yet in the index index.putIfAbsent(term, new HashMap<>()); // Get the list of documents containing the term Map<Integer, Integer> docList = index.get(term); if (docList == null) { docList = new HashMap<>(); index.put(term, docList); // Ensure docList is added to the index } // Increment the term frequency in this document docList.put(docId, docList.getOrDefault(docId, 0) + 1); } } public int getMoviesLength() { return movies.size(); } /** * Search for documents containing a term using BM25 scoring. * @param term The search term. * @return A list of search results sorted by relevance score. */ public List<SearchResult> search(String term) { term = term.toLowerCase(); // Normalize search term if (!index.containsKey(term)) { return new ArrayList<>(); // Return empty list if term not found } Map<Integer, Integer> termDocs = index.get(term); // Documents containing the term List<SearchResult> results = new ArrayList<>(); // Compute IDF for the search term double idf = computeIDF(termDocs.size()); // Calculate relevance scores for all documents containing the term for (Map.Entry<Integer, Integer> entry : termDocs.entrySet()) { int docId = entry.getKey(); int termFrequency = entry.getValue(); Movie movie = movies.get(docId); if (movie == null) { continue; // Skip this document if movie doesn't exist } double docLength = movie.getWords().length; // Compute BM25 relevance score double score = computeBM25Score(termFrequency, docLength, idf); results.add(new SearchResult(docId, score)); } // Sort the results by relevance score in descending order results.sort((r1, r2) -> Double.compare(r2.relevanceScore, r1.relevanceScore)); return results; } /** * Compute the BM25 score for a given term and document. * @param termFrequency The frequency of the term in the document. * @param docLength The length of the document. * @param idf The inverse document frequency of the term. * @return The BM25 relevance score for the term in the document. */ private double computeBM25Score(int termFrequency, double docLength, double idf) { double numerator = termFrequency * (K + 1); double denominator = termFrequency + K * (1 - B + B * (docLength / avgDocumentLength)); return idf * (numerator / denominator); } /** * Compute the inverse document frequency (IDF) of a term. * The IDF measures the importance of a term across the entire document set. * @param docFrequency The number of documents that contain the term. * @return The inverse document frequency (IDF) value. */ private double computeIDF(int docFrequency) { // Total number of documents in the index return Math.log((totalDocuments - docFrequency + 0.5) / (docFrequency + 0.5) + 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/searches/BinarySearch.java
src/main/java/com/thealgorithms/searches/BinarySearch.java
package com.thealgorithms.searches; import com.thealgorithms.devutils.searches.SearchAlgorithm; /** * Binary search is one of the most popular algorithms The algorithm finds the * position of a target value within a sorted array * * <p> * Worst-case performance O(log n) Best-case performance O(1) Average * performance O(log n) Worst-case space complexity O(1) * * @author Varun Upadhyay (https://github.com/varunu28) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SearchAlgorithm * @see IterativeBinarySearch */ class BinarySearch implements SearchAlgorithm { /** * @param array is an array where the element should be found * @param key is an element which should be found * @param <T> is any comparable type * @return index of the element */ @Override public <T extends Comparable<T>> int find(T[] array, T key) { return search(array, key, 0, array.length - 1); } /** * This method implements the Generic Binary Search * * @param array The array to make the binary search * @param key The number you are looking for * @param left The lower bound * @param right The upper bound * @return the location of the key */ private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) { if (right < left) { return -1; // this means that the key not found } // find median int median = (left + right) >>> 1; int comp = key.compareTo(array[median]); if (comp == 0) { return median; } else if (comp < 0) { return search(array, key, left, median - 1); } else { return search(array, key, median + 1, right); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java
src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java
package com.thealgorithms.others; import java.util.Stack; /** * This implements Queue using two Stacks. * * <p> * Big O Runtime: insert(): O(1) remove(): O(1) amortized isEmpty(): O(1) * * <p> * A queue data structure functions the same as a real world queue. The elements * that are added first are the first to be removed. New elements are added to * the back/rear of the queue. * * @author sahilb2 (https://www.github.com/sahilb2) */ public class QueueUsingTwoStacks { private final Stack<Object> inStack; private final Stack<Object> outStack; /** * Constructor */ public QueueUsingTwoStacks() { this.inStack = new Stack<>(); this.outStack = new Stack<>(); } /** * Inserts an element at the rear of the queue * * @param x element to be added */ public void insert(Object x) { // Insert element into inStack this.inStack.push(x); } /** * Remove an element from the front of the queue * * @return the new front of the queue */ public Object remove() { if (this.outStack.isEmpty()) { // Move all elements from inStack to outStack (preserving the order) while (!this.inStack.isEmpty()) { this.outStack.push(this.inStack.pop()); } } return this.outStack.pop(); } /** * Peek at the element from the front of the queue * * @return the front element of the queue */ public Object peekFront() { if (this.outStack.isEmpty()) { // Move all elements from inStack to outStack (preserving the order) while (!this.inStack.isEmpty()) { this.outStack.push(this.inStack.pop()); } } return this.outStack.peek(); } /** * Peek at the element from the back of the queue * * @return the back element of the queue */ public Object peekBack() { return this.inStack.peek(); } /** * Returns true if the queue is empty * * @return true if the queue is empty */ public boolean isEmpty() { return (this.inStack.isEmpty() && this.outStack.isEmpty()); } /** * Returns true if the inStack is empty. * * @return true if the inStack is empty. */ public boolean isInStackEmpty() { return (inStack.isEmpty()); } /** * Returns true if the outStack is empty. * * @return true if the outStack is empty. */ public boolean isOutStackEmpty() { return (outStack.isEmpty()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/BrianKernighanAlgorithm.java
src/main/java/com/thealgorithms/others/BrianKernighanAlgorithm.java
package com.thealgorithms.others; import java.util.Scanner; /** * @author Nishita Aggarwal * <p> * Brian Kernighan’s Algorithm * <p> * algorithm to count the number of set bits in a given number * <p> * Subtraction of 1 from a number toggles all the bits (from right to left) till * the rightmost set bit(including the rightmost set bit). So if we subtract a * number by 1 and do bitwise & with itself i.e. (n & (n-1)), we unset the * rightmost set bit. * <p> * If we do n & (n-1) in a loop and count the no of times loop executes we get * the set bit count. * <p> * <p> * Time Complexity: O(logn) */ public final class BrianKernighanAlgorithm { private BrianKernighanAlgorithm() { } /** * @param num: number in which we count the set bits * @return int: Number of set bits */ static int countSetBits(int num) { int cnt = 0; while (num != 0) { num = num & (num - 1); cnt++; } return cnt; } /** * @param args : command line arguments */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); int setBitCount = countSetBits(num); System.out.println(setBitCount); sc.close(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java
src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java
package com.thealgorithms.others; import java.util.Arrays; import java.util.Random; /** * MiniMax is an algorithm used in artificial intelligence and game theory for * minimizing the possible loss for the worst case scenario. It is commonly used * in two-player turn-based games such as Tic-Tac-Toe, Chess, and Checkers. * * <p> * The algorithm simulates all possible moves in a game tree and chooses the * move that minimizes the maximum possible loss. The algorithm assumes both * players play optimally. * * <p> * Time Complexity: O(b^d) where b is the branching factor and d is the depth * <p> * Space Complexity: O(d) for the recursive call stack * * <p> * See more: * <ul> * <li><a href="https://en.wikipedia.org/wiki/Minimax">Wikipedia - Minimax</a> * <li><a href= * "https://www.geeksforgeeks.org/minimax-algorithm-in-game-theory-set-1-introduction/"> * GeeksforGeeks - Minimax Algorithm</a> * </ul> * * @author aitofi (https://github.com/aitorfi) */ public final class MiniMaxAlgorithm { private static final Random RANDOM = new Random(); /** * Game tree represented as an int array containing scores. Each array * element is a leaf node. The array length must be a power of 2. */ private int[] scores; /** * The height of the game tree, calculated as log2(scores.length). */ private int height; /** * Initializes the MiniMaxAlgorithm with 8 random leaf nodes (2^3 = 8). * Each score is a random integer between 1 and 99 inclusive. */ public MiniMaxAlgorithm() { this(getRandomScores(3, 99)); } /** * Initializes the MiniMaxAlgorithm with the provided scores. * * @param scores An array of scores representing leaf nodes. The length must be * a power of 2. * @throws IllegalArgumentException if the scores array length is not a power of * 2 */ public MiniMaxAlgorithm(int[] scores) { if (!isPowerOfTwo(scores.length)) { throw new IllegalArgumentException("The number of scores must be a power of 2."); } this.scores = Arrays.copyOf(scores, scores.length); this.height = log2(scores.length); } /** * Demonstrates the MiniMax algorithm with a random game tree. * * @param args Command line arguments (not used) */ public static void main(String[] args) { MiniMaxAlgorithm miniMaxAlgorithm = new MiniMaxAlgorithm(); boolean isMaximizer = true; // Specifies the player that goes first. int bestScore; bestScore = miniMaxAlgorithm.miniMax(0, isMaximizer, 0, true); System.out.println(); System.out.println(Arrays.toString(miniMaxAlgorithm.getScores())); System.out.println("The best score for " + (isMaximizer ? "Maximizer" : "Minimizer") + " is " + bestScore); } /** * Returns the optimal score assuming that both players play their best. * * <p> * This method recursively evaluates the game tree using the minimax algorithm. * At each level, the maximizer tries to maximize the score while the minimizer * tries to minimize it. * * @param depth The current depth in the game tree (0 at root). * @param isMaximizer True if it is the maximizer's turn; false for minimizer. * @param index Index of the current node in the game tree. * @param verbose True to print each player's choice during evaluation. * @return The optimal score for the player that made the first move. */ public int miniMax(int depth, boolean isMaximizer, int index, boolean verbose) { int bestScore; int score1; int score2; if (depth == height) { // Leaf node reached. return scores[index]; } score1 = miniMax(depth + 1, !isMaximizer, index * 2, verbose); score2 = miniMax(depth + 1, !isMaximizer, (index * 2) + 1, verbose); if (isMaximizer) { // Maximizer player wants to get the maximum possible score. bestScore = Math.max(score1, score2); } else { // Minimizer player wants to get the minimum possible score. bestScore = Math.min(score1, score2); } // Leaf nodes can be sequentially inspected by // recursively multiplying (0 * 2) and ((0 * 2) + 1): // (0 x 2) = 0; ((0 x 2) + 1) = 1 // (1 x 2) = 2; ((1 x 2) + 1) = 3 // (2 x 2) = 4; ((2 x 2) + 1) = 5 ... if (verbose) { System.out.printf("From %02d and %02d, %s chooses %02d%n", score1, score2, (isMaximizer ? "Maximizer" : "Minimizer"), bestScore); } return bestScore; } /** * Returns an array of random numbers whose length is a power of 2. * * @param size The power of 2 that will determine the length of the array * (array length = 2^size). * @param maxScore The maximum possible score (scores will be between 1 and * maxScore inclusive). * @return An array of random numbers with length 2^size. */ public static int[] getRandomScores(int size, int maxScore) { int[] randomScores = new int[(int) Math.pow(2, size)]; for (int i = 0; i < randomScores.length; i++) { randomScores[i] = RANDOM.nextInt(maxScore) + 1; } return randomScores; } /** * Calculates the logarithm base 2 of a number. * * @param n The number to calculate log2 for (must be a power of 2). * @return The log2 of n. */ private int log2(int n) { return (n == 1) ? 0 : log2(n / 2) + 1; } /** * Checks if a number is a power of 2. * * @param n The number to check. * @return True if n is a power of 2, false otherwise. */ private boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; } /** * Sets the scores array for the game tree. * * @param scores The array of scores. Length must be a power of 2. * @throws IllegalArgumentException if the scores array length is not a power of * 2 */ public void setScores(int[] scores) { if (!isPowerOfTwo(scores.length)) { throw new IllegalArgumentException("The number of scores must be a power of 2."); } this.scores = Arrays.copyOf(scores, scores.length); height = log2(this.scores.length); } /** * Returns a copy of the scores array. * * @return A copy of the scores array. */ public int[] getScores() { return Arrays.copyOf(scores, scores.length); } /** * Returns the height of the game tree. * * @return The height of the game tree (log2 of the number of leaf nodes). */ public int getHeight() { return height; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java
src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java
package com.thealgorithms.others; /** * * * A pseudorandom number generator. * * @author Tobias Carryer * @date October 10, 2017 */ public class LinearCongruentialGenerator { private final double a; private final double c; private final double m; private double previousValue; /** * * * These parameters are saved and used when nextNumber() is called. The * current timestamp in milliseconds is used as the seed. * * @param multiplier * @param increment * @param modulo The maximum number that can be generated (exclusive). A * common value is 2^32. */ public LinearCongruentialGenerator(double multiplier, double increment, double modulo) { this(System.currentTimeMillis(), multiplier, increment, modulo); } /** * * * These parameters are saved and used when nextNumber() is called. * * @param seed * @param multiplier * @param increment * @param modulo The maximum number that can be generated (exclusive). A * common value is 2^32. */ public LinearCongruentialGenerator(double seed, double multiplier, double increment, double modulo) { this.previousValue = seed; this.a = multiplier; this.c = increment; this.m = modulo; } /** * The smallest number that can be generated is zero. The largest number * that can be generated is modulo-1. modulo is set in the constructor. * * @return a pseudorandom number. */ public double nextNumber() { previousValue = (a * previousValue + c) % m; return previousValue; } public static void main(String[] args) { // Show the LCG in action. // Decisive proof that the LCG works could be made by adding each number // generated to a Set while checking for duplicates. LinearCongruentialGenerator lcg = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0)); for (int i = 0; i < 512; i++) { System.out.println(lcg.nextNumber()); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
package com.thealgorithms.others; import java.util.ArrayList; import java.util.List; /** * Utility class for finding the lowest base in which a given integer is a * palindrome. * <p> * A number is a palindrome in a given base if its representation in that base * reads the same * forwards and backwards. For example, 15 in base 2 is 1111, which is * palindromic. * This class provides methods to check palindromic properties and find the * smallest base * where a number becomes palindromic. * </p> * <p> * Example: The number 15 in base 2 is represented as [1,1,1,1], which is * palindromic. * The number 10 in base 3 is represented as [1,0,1], which is also palindromic. * </p> * * @see <a href="https://oeis.org/A016026">OEIS A016026 - Smallest base in which * n is palindromic</a> * @author TheAlgorithms Contributors */ public final class LowestBasePalindrome { private LowestBasePalindrome() { } /** * Validates the base, ensuring it is greater than 1. * * @param base the base to be checked * @throws IllegalArgumentException if the base is less than or equal to 1 */ private static void checkBase(int base) { if (base <= 1) { throw new IllegalArgumentException("Base must be greater than 1."); } } /** * Validates the number, ensuring it is non-negative. * * @param number the number to be checked * @throws IllegalArgumentException if the number is negative */ private static void checkNumber(int number) { if (number < 0) { throw new IllegalArgumentException("Number must be non-negative."); } } /** * Computes the digits of a given number in a specified base. * <p> * The digits are returned in reverse order (least significant digit first). * For example, the number 13 in base 2 produces [1,0,1,1] representing 1101 in * binary. * </p> * * @param number the number to be converted (must be non-negative) * @param base the base to be used for the conversion (must be greater than 1) * @return a list of digits representing the number in the given base, with the * least significant digit at the beginning of the list * @throws IllegalArgumentException if the number is negative or the base is * less than 2 */ public static List<Integer> computeDigitsInBase(int number, int base) { checkNumber(number); checkBase(base); List<Integer> digits = new ArrayList<>(); while (number > 0) { digits.add(number % base); number /= base; } return digits; } /** * Checks if a list of integers is palindromic. * <p> * A list is palindromic if it reads the same forwards and backwards. * For example, [1,2,1] is palindromic, but [1,2,3] is not. * </p> * * @param list the list of integers to be checked * @return {@code true} if the list is a palindrome, {@code false} otherwise */ public static boolean isPalindromic(List<Integer> list) { int size = list.size(); for (int i = 0; i < size / 2; i++) { if (!list.get(i).equals(list.get(size - 1 - i))) { return false; } } return true; } /** * Checks if the representation of a given number in a specified base is * palindromic. * <p> * This method first validates the input, then applies optimization: if the * number * ends with 0 in the given base (i.e., divisible by the base), it cannot be * palindromic * as palindromes cannot start with 0. * </p> * <p> * Examples: * - 101 in base 10 is palindromic (101) * - 15 in base 2 is palindromic (1111) * - 10 in base 3 is palindromic (101) * </p> * * @param number the number to be checked (must be non-negative) * @param base the base in which the number will be represented (must be * greater than 1) * @return {@code true} if the number is palindromic in the specified base, * {@code false} otherwise * @throws IllegalArgumentException if the number is negative or the base is * less than 2 */ public static boolean isPalindromicInBase(int number, int base) { checkNumber(number); checkBase(base); if (number <= 1) { return true; } if (number % base == 0) { // If the last digit of the number in the given base is 0, it can't be // palindromic return false; } return isPalindromic(computeDigitsInBase(number, base)); } /** * Finds the smallest base in which the representation of a given number is * palindromic. * <p> * This method iteratively checks bases starting from 2 until it finds one where * the number is palindromic. For any number n ≥ 2, the number is always * palindromic * in base n-1 (represented as [1, 1]), so this algorithm is guaranteed to * terminate. * </p> * <p> * Time Complexity: O(n * log(n)) in the worst case, where we check each base * and * convert the number to that base. * </p> * <p> * Examples: * - lowestBasePalindrome(15) returns 2 (15 in base 2 is 1111) * - lowestBasePalindrome(10) returns 3 (10 in base 3 is 101) * - lowestBasePalindrome(11) returns 10 (11 in base 10 is 11) * </p> * * @param number the number to be checked (must be non-negative) * @return the smallest base in which the number is a palindrome (base ≥ 2) * @throws IllegalArgumentException if the number is negative */ public static int lowestBasePalindrome(int number) { checkNumber(number); int base = 2; while (!isPalindromicInBase(number, base)) { base++; } return base; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/CRC32.java
src/main/java/com/thealgorithms/others/CRC32.java
package com.thealgorithms.others; import java.util.BitSet; /** * Generates a crc32 checksum for a given string or byte array */ public final class CRC32 { private CRC32() { } public static void main(String[] args) { System.out.println(Integer.toHexString(crc32("Hello World"))); } public static int crc32(String str) { return crc32(str.getBytes()); } public static int crc32(byte[] data) { BitSet bitSet = BitSet.valueOf(data); int crc32 = 0xFFFFFFFF; // initial value for (int i = 0; i < data.length * 8; i++) { if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) { crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial } else { crc32 = (crc32 << 1); } } crc32 = Integer.reverse(crc32); // result reflect return crc32 ^ 0xFFFFFFFF; // final xor value } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java
src/main/java/com/thealgorithms/others/InsertDeleteInArray.java
package com.thealgorithms.others; import java.util.Arrays; import java.util.Scanner; /** * Utility class for performing insert and delete operations on arrays. * <p> * This class demonstrates how to insert an element at a specific position and * delete an element from a specific position in an integer array. Since arrays * in Java have fixed size, insertion creates a new array with increased size, * and deletion shifts elements to fill the gap. * </p> * * <p> * <strong>Time Complexity:</strong> * </p> * <ul> * <li>Insert: O(n) - requires copying elements to new array</li> * <li>Delete: O(n) - requires shifting elements</li> * </ul> * * <p> * <strong>Space Complexity:</strong> * </p> * <ul> * <li>Insert: O(n) - new array of size n+1</li> * <li>Delete: O(1) - in-place modification (excluding result array)</li> * </ul> * * @author TheAlgorithms community * @see <a href="https://en.wikipedia.org/wiki/Array_(data_structure)">Array * Data Structure</a> */ public final class InsertDeleteInArray { private InsertDeleteInArray() { } /** * Inserts an element at the specified position in the array. * <p> * Creates a new array with size = original array size + 1. * Elements at positions &lt;= insertPos retain their positions, * while elements at positions &gt; insertPos are shifted right by one position. * </p> * * @param array the original array * @param element the element to be inserted * @param position the index at which the element should be inserted (0-based) * @return a new array with the element inserted at the specified position * @throws IllegalArgumentException if position is negative or greater than * array length * @throws IllegalArgumentException if array is null */ public static int[] insertElement(int[] array, int element, int position) { if (array == null) { throw new IllegalArgumentException("Array cannot be null"); } if (position < 0 || position > array.length) { throw new IllegalArgumentException("Position must be between 0 and " + array.length); } int[] newArray = new int[array.length + 1]; // Copy elements before insertion position System.arraycopy(array, 0, newArray, 0, position); // Insert the new element newArray[position] = element; // Copy remaining elements after insertion position System.arraycopy(array, position, newArray, position + 1, array.length - position); return newArray; } /** * Deletes an element at the specified position from the array. * <p> * Creates a new array with size = original array size - 1. * Elements after the deletion position are shifted left by one position. * </p> * * @param array the original array * @param position the index of the element to be deleted (0-based) * @return a new array with the element at the specified position removed * @throws IllegalArgumentException if position is negative or greater than or * equal to array length * @throws IllegalArgumentException if array is null or empty */ public static int[] deleteElement(int[] array, int position) { if (array == null) { throw new IllegalArgumentException("Array cannot be null"); } if (array.length == 0) { throw new IllegalArgumentException("Array is empty"); } if (position < 0 || position >= array.length) { throw new IllegalArgumentException("Position must be between 0 and " + (array.length - 1)); } int[] newArray = new int[array.length - 1]; // Copy elements before deletion position System.arraycopy(array, 0, newArray, 0, position); // Copy elements after deletion position System.arraycopy(array, position + 1, newArray, position, array.length - position - 1); return newArray; } /** * Main method demonstrating insert and delete operations on an array. * <p> * This method interactively: * <ol> * <li>Takes array size and elements as input</li> * <li>Inserts a new element at a specified position</li> * <li>Deletes an element from a specified position</li> * <li>Displays the array after each operation</li> * </ol> * </p> * * @param args command line arguments (not used) */ public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { // Input: array size and elements System.out.println("Enter the size of the array:"); int size = scanner.nextInt(); if (size <= 0) { System.out.println("Array size must be positive"); return; } int[] array = new int[size]; System.out.println("Enter " + size + " elements:"); for (int i = 0; i < size; i++) { array[i] = scanner.nextInt(); } System.out.println("Original array: " + Arrays.toString(array)); // Insert operation System.out.println("\nEnter the index at which the element should be inserted (0-" + size + "):"); int insertPos = scanner.nextInt(); System.out.println("Enter the element to be inserted:"); int elementToInsert = scanner.nextInt(); try { array = insertElement(array, elementToInsert, insertPos); System.out.println("Array after insertion: " + Arrays.toString(array)); } catch (IllegalArgumentException e) { System.out.println("Error during insertion: " + e.getMessage()); return; } // Delete operation System.out.println("\nEnter the index at which element is to be deleted (0-" + (array.length - 1) + "):"); int deletePos = scanner.nextInt(); try { array = deleteElement(array, deletePos); System.out.println("Array after deletion: " + Arrays.toString(array)); } catch (IllegalArgumentException e) { System.out.println("Error during deletion: " + e.getMessage()); } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/CRC16.java
src/main/java/com/thealgorithms/others/CRC16.java
package com.thealgorithms.others; /** * Generates a crc16 checksum for a given string */ public final class CRC16 { private CRC16() { } public static void main(String[] args) { System.out.println(crc16("Hello World!")); } public static String crc16(String message) { int crc = 0xFFFF; // initial value int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12) byte[] bytes = message.getBytes(); for (byte b : bytes) { for (int i = 0; i < 8; i++) { boolean bit = ((b >> (7 - i) & 1) == 1); boolean c15 = ((crc >> 15 & 1) == 1); crc <<= 1; if (c15 ^ bit) { crc ^= polynomial; } } } crc &= 0xffff; return Integer.toHexString(crc).toUpperCase(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/MosAlgorithm.java
src/main/java/com/thealgorithms/others/MosAlgorithm.java
package com.thealgorithms.others; import java.util.Arrays; import java.util.Comparator; /** * Mo's Algorithm (Square Root Decomposition) for offline range queries * * Mo's Algorithm is used to answer range queries efficiently when: * 1. Queries can be processed offline (all queries known beforehand) * 2. We can efficiently add/remove elements from current range * 3. The problem has optimal substructure for range operations * * Time Complexity: O((N + Q) * sqrt(N)) where N = array size, Q = number of queries * Space Complexity: O(N + Q) * * @see <a href="https://www.geeksforgeeks.org/dsa/mos-algorithm-query-square-root-decomposition-set-1-introduction/">Mo's Algorithm</a> * @author BEASTSHRIRAM */ public final class MosAlgorithm { /** * Query structure to store range queries */ public static class Query { public final int left; public final int right; public final int index; // Original index of query public int result; // Result of the query public Query(int left, int right, int index) { this.left = left; this.right = right; this.index = index; this.result = 0; } } private MosAlgorithm() { // Utility class } /** * Solves range sum queries using Mo's Algorithm * * @param arr the input array * @param queries array of queries to process * @return array of results corresponding to each query */ public static int[] solveRangeSumQueries(int[] arr, Query[] queries) { if (arr == null || queries == null || arr.length == 0) { return new int[0]; } int n = arr.length; int blockSize = (int) Math.sqrt(n); // Sort queries using Mo's ordering Arrays.sort(queries, new MoComparator(blockSize)); // Initialize variables for current range int currentLeft = 0; int currentRight = -1; int currentSum = 0; // Process each query for (Query query : queries) { // Expand or shrink the current range to match query range // Expand right boundary while (currentRight < query.right) { currentRight++; currentSum += arr[currentRight]; } // Shrink right boundary while (currentRight > query.right) { currentSum -= arr[currentRight]; currentRight--; } // Expand left boundary while (currentLeft < query.left) { currentSum -= arr[currentLeft]; currentLeft++; } // Shrink left boundary while (currentLeft > query.left) { currentLeft--; currentSum += arr[currentLeft]; } // Store the result query.result = currentSum; } // Extract results in original query order int[] results = new int[queries.length]; for (Query query : queries) { results[query.index] = query.result; } return results; } /** * Solves range frequency queries using Mo's Algorithm * Example: Count occurrences of a specific value in range [L, R] * * @param arr the input array * @param queries array of queries to process * @param targetValue the value to count in each range * @return array of results corresponding to each query */ public static int[] solveRangeFrequencyQueries(int[] arr, Query[] queries, int targetValue) { if (arr == null || queries == null || arr.length == 0) { return new int[0]; } int n = arr.length; int blockSize = (int) Math.sqrt(n); // Sort queries using Mo's ordering Arrays.sort(queries, new MoComparator(blockSize)); // Initialize variables for current range int currentLeft = 0; int currentRight = -1; int currentCount = 0; // Process each query for (Query query : queries) { // Expand right boundary while (currentRight < query.right) { currentRight++; if (arr[currentRight] == targetValue) { currentCount++; } } // Shrink right boundary while (currentRight > query.right) { if (arr[currentRight] == targetValue) { currentCount--; } currentRight--; } // Expand left boundary while (currentLeft < query.left) { if (arr[currentLeft] == targetValue) { currentCount--; } currentLeft++; } // Shrink left boundary while (currentLeft > query.left) { currentLeft--; if (arr[currentLeft] == targetValue) { currentCount++; } } // Store the result query.result = currentCount; } // Extract results in original query order int[] results = new int[queries.length]; for (Query query : queries) { results[query.index] = query.result; } return results; } /** * Comparator for Mo's Algorithm query ordering * Queries are sorted by block of left endpoint, then by right endpoint */ private static class MoComparator implements Comparator<Query> { private final int blockSize; MoComparator(int blockSize) { this.blockSize = blockSize; } @Override public int compare(Query a, Query b) { int blockA = a.left / blockSize; int blockB = b.left / blockSize; if (blockA != blockB) { return Integer.compare(blockA, blockB); } // For odd blocks, sort right in ascending order // For even blocks, sort right in descending order (optimization) if ((blockA & 1) == 1) { return Integer.compare(a.right, b.right); } else { return Integer.compare(b.right, a.right); } } } /** * Demo method showing usage of Mo's Algorithm * * @param args command line arguments */ public static void main(String[] args) { // Example: Range sum queries int[] arr = {1, 3, 5, 2, 7, 6, 3, 1, 4, 8}; Query[] queries = { new Query(0, 2, 0), // Sum of elements from index 0 to 2: 1+3+5 = 9 new Query(1, 4, 1), // Sum of elements from index 1 to 4: 3+5+2+7 = 17 new Query(2, 6, 2), // Sum of elements from index 2 to 6: 5+2+7+6+3 = 23 new Query(3, 8, 3) // Sum of elements from index 3 to 8: 2+7+6+3+1+4 = 23 }; System.out.println("Array: " + Arrays.toString(arr)); System.out.println("Range Sum Queries:"); // Store original queries for display Query[] originalQueries = new Query[queries.length]; for (int i = 0; i < queries.length; i++) { originalQueries[i] = new Query(queries[i].left, queries[i].right, queries[i].index); } int[] results = solveRangeSumQueries(arr, queries); for (int i = 0; i < originalQueries.length; i++) { System.out.printf("Query %d: Sum of range [%d, %d] = %d%n", i, originalQueries[i].left, originalQueries[i].right, results[i]); } // Example: Range frequency queries System.out.println("\nRange Frequency Queries (count of value 3):"); Query[] freqQueries = { new Query(0, 5, 0), // Count of 3 in range [0, 5]: 1 occurrence new Query(2, 8, 1), // Count of 3 in range [2, 8]: 2 occurrences new Query(6, 9, 2) // Count of 3 in range [6, 9]: 1 occurrence }; // Store original frequency queries for display Query[] originalFreqQueries = new Query[freqQueries.length]; for (int i = 0; i < freqQueries.length; i++) { originalFreqQueries[i] = new Query(freqQueries[i].left, freqQueries[i].right, freqQueries[i].index); } int[] freqResults = solveRangeFrequencyQueries(arr, freqQueries, 3); for (int i = 0; i < originalFreqQueries.length; i++) { System.out.printf("Query %d: Count of 3 in range [%d, %d] = %d%n", i, originalFreqQueries[i].left, originalFreqQueries[i].right, freqResults[i]); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/Huffman.java
src/main/java/com/thealgorithms/others/Huffman.java
package com.thealgorithms.others; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; /** * Node class representing a node in the Huffman tree. * Each node contains a character, its frequency, and references to left and * right children. */ class HuffmanNode { int data; char c; HuffmanNode left; HuffmanNode right; /** * Constructor for HuffmanNode. * * @param c the character stored in this node * @param data the frequency of the character */ HuffmanNode(char c, int data) { this.c = c; this.data = data; this.left = null; this.right = null; } /** * Default constructor for HuffmanNode. */ HuffmanNode() { this.left = null; this.right = null; } } /** * Comparator class for comparing HuffmanNode objects based on their frequency * data. * Used to maintain min-heap property in the priority queue. */ class HuffmanComparator implements Comparator<HuffmanNode> { @Override public int compare(HuffmanNode x, HuffmanNode y) { return Integer.compare(x.data, y.data); } } /** * Implementation of Huffman Coding algorithm for data compression. * Huffman Coding is a greedy algorithm that assigns variable-length codes to * characters * based on their frequency of occurrence. Characters with higher frequency get * shorter codes. * * <p> * Time Complexity: O(n log n) where n is the number of unique characters * Space Complexity: O(n) * * @see <a href="https://en.wikipedia.org/wiki/Huffman_coding">Huffman * Coding</a> */ public final class Huffman { private Huffman() { } /** * Builds a Huffman tree from the given character array and their frequencies. * * @param charArray array of characters * @param charFreq array of frequencies corresponding to the characters * @return root node of the Huffman tree * @throws IllegalArgumentException if arrays are null, empty, or have different * lengths */ public static HuffmanNode buildHuffmanTree(char[] charArray, int[] charFreq) { if (charArray == null || charFreq == null) { throw new IllegalArgumentException("Character array and frequency array cannot be null"); } if (charArray.length == 0 || charFreq.length == 0) { throw new IllegalArgumentException("Character array and frequency array cannot be empty"); } if (charArray.length != charFreq.length) { throw new IllegalArgumentException("Character array and frequency array must have the same length"); } int n = charArray.length; PriorityQueue<HuffmanNode> priorityQueue = new PriorityQueue<>(n, new HuffmanComparator()); // Create leaf nodes and add to priority queue for (int i = 0; i < n; i++) { if (charFreq[i] < 0) { throw new IllegalArgumentException("Frequencies must be non-negative"); } HuffmanNode node = new HuffmanNode(charArray[i], charFreq[i]); priorityQueue.add(node); } // Build the Huffman tree while (priorityQueue.size() > 1) { HuffmanNode left = priorityQueue.poll(); HuffmanNode right = priorityQueue.poll(); HuffmanNode parent = new HuffmanNode(); parent.data = left.data + right.data; parent.c = '-'; parent.left = left; parent.right = right; priorityQueue.add(parent); } return priorityQueue.poll(); } /** * Generates Huffman codes for all characters in the tree. * * @param root root node of the Huffman tree * @return map of characters to their Huffman codes */ public static Map<Character, String> generateCodes(HuffmanNode root) { Map<Character, String> huffmanCodes = new HashMap<>(); if (root != null) { generateCodesHelper(root, "", huffmanCodes); } return huffmanCodes; } /** * Helper method to recursively generate Huffman codes by traversing the tree. * * @param node current node in the tree * @param code current code being built * @param huffmanCodes map to store character-to-code mappings */ private static void generateCodesHelper(HuffmanNode node, String code, Map<Character, String> huffmanCodes) { if (node == null) { return; } // If it's a leaf node, store the code if (node.left == null && node.right == null && Character.isLetter(node.c)) { huffmanCodes.put(node.c, code.isEmpty() ? "0" : code); return; } // Traverse left with '0' and right with '1' if (node.left != null) { generateCodesHelper(node.left, code + "0", huffmanCodes); } if (node.right != null) { generateCodesHelper(node.right, code + "1", huffmanCodes); } } /** * Prints Huffman codes for all characters in the tree. * This method is kept for backward compatibility and demonstration purposes. * * @param root root node of the Huffman tree * @param code current code being built (initially empty string) */ public static void printCode(HuffmanNode root, String code) { if (root == null) { return; } // If it's a leaf node, print the code if (root.left == null && root.right == null && Character.isLetter(root.c)) { System.out.println(root.c + ":" + code); return; } // Traverse left with '0' and right with '1' if (root.left != null) { printCode(root.left, code + "0"); } if (root.right != null) { printCode(root.right, code + "1"); } } /** * Demonstrates the Huffman coding algorithm with sample data. * * @param args command line arguments (not used) */ public static void main(String[] args) { // Sample characters and their frequencies char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'}; int[] charFreq = {5, 9, 12, 13, 16, 45}; System.out.println("Characters: a, b, c, d, e, f"); System.out.println("Frequencies: 5, 9, 12, 13, 16, 45"); System.out.println("\nHuffman Codes:"); // Build Huffman tree HuffmanNode root = buildHuffmanTree(charArray, charFreq); // Generate and print Huffman codes Map<Character, String> codes = generateCodes(root); for (Map.Entry<Character, String> entry : codes.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/SkylineProblem.java
src/main/java/com/thealgorithms/others/SkylineProblem.java
package com.thealgorithms.others; import java.util.ArrayList; /** * The {@code SkylineProblem} class is used to solve the skyline problem using a * divide-and-conquer approach. * It reads input for building data, processes it to find the skyline, and * prints the skyline. */ public class SkylineProblem { Building[] building; int count; /** * Adds a building with the given left, height, and right values to the * buildings list. * * @param left The left x-coordinate of the building. * @param height The height of the building. * @param right The right x-coordinate of the building. */ public void add(int left, int height, int right) { building[count++] = new Building(left, height, right); } /** * Computes the skyline for a range of buildings using the divide-and-conquer * strategy. * * @param start The starting index of the buildings to process. * @param end The ending index of the buildings to process. * @return A list of {@link Skyline} objects representing the computed skyline. */ public ArrayList<Skyline> findSkyline(int start, int end) { // Base case: only one building, return its skyline. if (start == end) { ArrayList<Skyline> list = new ArrayList<>(); list.add(new Skyline(building[start].left, building[start].height)); list.add(new Skyline(building[end].right, 0)); // Add the end of the building return list; } int mid = (start + end) / 2; ArrayList<Skyline> sky1 = this.findSkyline(start, mid); // Find the skyline of the left half ArrayList<Skyline> sky2 = this.findSkyline(mid + 1, end); // Find the skyline of the right half return this.mergeSkyline(sky1, sky2); // Merge the two skylines } /** * Merges two skylines (sky1 and sky2) into one combined skyline. * * @param sky1 The first skyline list. * @param sky2 The second skyline list. * @return A list of {@link Skyline} objects representing the merged skyline. */ public ArrayList<Skyline> mergeSkyline(ArrayList<Skyline> sky1, ArrayList<Skyline> sky2) { int currentH1 = 0; int currentH2 = 0; ArrayList<Skyline> skyline = new ArrayList<>(); int maxH = 0; // Merge the two skylines while (!sky1.isEmpty() && !sky2.isEmpty()) { if (sky1.get(0).coordinates < sky2.get(0).coordinates) { int currentX = sky1.get(0).coordinates; currentH1 = sky1.get(0).height; if (currentH1 < currentH2) { sky1.remove(0); if (maxH != currentH2) { skyline.add(new Skyline(currentX, currentH2)); } } else { maxH = currentH1; sky1.remove(0); skyline.add(new Skyline(currentX, currentH1)); } } else { int currentX = sky2.get(0).coordinates; currentH2 = sky2.get(0).height; if (currentH2 < currentH1) { sky2.remove(0); if (maxH != currentH1) { skyline.add(new Skyline(currentX, currentH1)); } } else { maxH = currentH2; sky2.remove(0); skyline.add(new Skyline(currentX, currentH2)); } } } // Add any remaining points from sky1 or sky2 while (!sky1.isEmpty()) { skyline.add(sky1.get(0)); sky1.remove(0); } while (!sky2.isEmpty()) { skyline.add(sky2.get(0)); sky2.remove(0); } return skyline; } /** * A class representing a point in the skyline with its x-coordinate and height. */ public class Skyline { public int coordinates; public int height; /** * Constructor for the {@code Skyline} class. * * @param coordinates The x-coordinate of the skyline point. * @param height The height of the skyline at the given coordinate. */ public Skyline(int coordinates, int height) { this.coordinates = coordinates; this.height = height; } } /** * A class representing a building with its left, height, and right * x-coordinates. */ public class Building { public int left; public int height; public int right; /** * Constructor for the {@code Building} class. * * @param left The left x-coordinate of the building. * @param height The height of the building. * @param right The right x-coordinate of the building. */ public Building(int left, int height, int right) { this.left = left; this.height = height; this.right = right; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java
src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java
package com.thealgorithms.others; // Java Program to implement Auto-Complete // Feature using Trie class Trieac { // Alphabet size (# of symbols) public static final int ALPHABET_SIZE = 26; // Trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isWordEnd is true if the node represents // end of a word boolean isWordEnd; } // Returns new trie node (initialized to NULLs) static TrieNode getNode() { TrieNode pNode = new TrieNode(); pNode.isWordEnd = false; for (int i = 0; i < ALPHABET_SIZE; i++) { pNode.children[i] = null; } return pNode; } // If not present, inserts key into trie. If the // key is prefix of trie node, just marks leaf node static void insert(TrieNode root, final String key) { TrieNode pCrawl = root; for (int level = 0; level < key.length(); level++) { int index = (key.charAt(level) - 'a'); if (pCrawl.children[index] == null) { pCrawl.children[index] = getNode(); } pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isWordEnd = true; } // Returns true if key presents in trie, else false boolean search(TrieNode root, final String key) { int length = key.length(); TrieNode pCrawl = root; for (int level = 0; level < length; level++) { int index = (key.charAt(level) - 'a'); if (pCrawl.children[index] == null) { pCrawl = pCrawl.children[index]; } } return (pCrawl != null && pCrawl.isWordEnd); } // Returns 0 if current node has a child // If all children are NULL, return 1. static boolean isLastNode(TrieNode root) { for (int i = 0; i < ALPHABET_SIZE; i++) { if (root.children[i] != null) { return false; } } return true; } // Recursive function to print auto-suggestions // for given node. static void suggestionsRec(TrieNode root, String currPrefix) { // found a string in Trie with the given prefix if (root.isWordEnd) { System.out.println(currPrefix); } // All children struct node pointers are NULL if (isLastNode(root)) { return; } for (int i = 0; i < ALPHABET_SIZE; i++) { if (root.children[i] != null) { // append current character to currPrefix string currPrefix += (char) (97 + i); // recur over the rest suggestionsRec(root.children[i], currPrefix); } } } // Function to print suggestions for // given query prefix. static int printAutoSuggestions(TrieNode root, final String query) { TrieNode pCrawl = root; // Check if prefix is present and find the // the node (of last level) with last character // of given string. int level; int n = query.length(); for (level = 0; level < n; level++) { int index = (query.charAt(level) - 'a'); // no string in the Trie has this prefix if (pCrawl.children[index] == null) { return 0; } pCrawl = pCrawl.children[index]; } // If prefix is present as a word. boolean isWord = (pCrawl.isWordEnd); // If prefix is last node of tree (has no // children) boolean isLast = isLastNode(pCrawl); // If prefix is present as a word, but // there is no subtree below the last // matching node. if (isWord && isLast) { System.out.println(query); return -1; } // If there are nodes below the last // matching character. if (!isLast) { String prefix = query; suggestionsRec(pCrawl, prefix); return 1; } return 0; } // Driver code public static void main(String[] args) { TrieNode root = getNode(); insert(root, "hello"); insert(root, "dog"); insert(root, "hell"); insert(root, "cat"); insert(root, "a"); insert(root, "hel"); insert(root, "help"); insert(root, "helps"); insert(root, "helping"); int comp = printAutoSuggestions(root, "hel"); if (comp == -1) { System.out.println("No other strings found " + "with this prefix\n"); } else if (comp == 0) { System.out.println("No string found with" + " this prefix\n"); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/LineSweep.java
src/main/java/com/thealgorithms/others/LineSweep.java
package com.thealgorithms.others; import java.util.Arrays; import java.util.Comparator; /** * The Line Sweep algorithm is used to solve range problems efficiently. It works by: * 1. Sorting a list of ranges by their start values in non-decreasing order. * 2. Sweeping through the number line (x-axis) while updating a count for each point based on the ranges. * * An overlapping range is defined as: * - (StartA <= EndB) AND (EndA >= StartB) * * References: * - https://en.wikipedia.org/wiki/Sweep_line_algorithm * - https://en.wikipedia.org/wiki/De_Morgan%27s_laws */ public final class LineSweep { private LineSweep() { } /** * Finds the maximum endpoint from a list of ranges. * * @param ranges a 2D array where each element is a range represented by [start, end] * @return the maximum endpoint among all ranges */ public static int findMaximumEndPoint(int[][] ranges) { Arrays.sort(ranges, Comparator.comparingInt(range -> range[1])); return ranges[ranges.length - 1][1]; } /** * Determines if any of the given ranges overlap. * * @param ranges a 2D array where each element is a range represented by [start, end] * @return true if any ranges overlap, false otherwise */ public static boolean isOverlap(int[][] ranges) { if (ranges == null || ranges.length == 0) { return false; } int maximumEndPoint = findMaximumEndPoint(ranges); int[] numberLine = new int[maximumEndPoint + 2]; for (int[] range : ranges) { int start = range[0]; int end = range[1]; numberLine[start] += 1; numberLine[end + 1] -= 1; } int currentCount = 0; int maxOverlaps = 0; for (int count : numberLine) { currentCount += count; maxOverlaps = Math.max(maxOverlaps, currentCount); } return maxOverlaps > 1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/GaussLegendre.java
src/main/java/com/thealgorithms/others/GaussLegendre.java
package com.thealgorithms.others; /** * Gauss Legendre Algorithm ref * https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm * * @author AKS1996 */ public final class GaussLegendre { private GaussLegendre() { } public static void main(String[] args) { for (int i = 1; i <= 3; ++i) { System.out.println(pi(i)); } } static double pi(int l) { /* * l: No of loops to run */ double a = 1; double b = Math.pow(2, -0.5); double t = 0.25; double p = 1; for (int i = 0; i < l; ++i) { double[] temp = update(a, b, t, p); a = temp[0]; b = temp[1]; t = temp[2]; p = temp[3]; } return Math.pow(a + b, 2) / (4 * t); } static double[] update(double a, double b, double t, double p) { double[] values = new double[4]; values[0] = (a + b) / 2; values[1] = Math.sqrt(a * b); values[2] = t - p * Math.pow(a - values[0], 2); values[3] = 2 * p; return values; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/BoyerMoore.java
src/main/java/com/thealgorithms/others/BoyerMoore.java
package com.thealgorithms.others; import java.util.Optional; /** * Utility class implementing Boyer-Moore's Voting Algorithm to find the majority element * in an array. The majority element is defined as the element that appears more than n/2 times * in the array, where n is the length of the array. * * For more information on the algorithm, refer to: * https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm */ public final class BoyerMoore { private BoyerMoore() { } /** * Finds the majority element in the given array if it exists. * * @param array the input array * @return an Optional containing the majority element if it exists, otherwise an empty Optional */ public static Optional<Integer> findMajorityElement(int[] array) { if (array == null || array.length == 0) { return Optional.empty(); } int candidate = findCandidate(array); int count = countOccurrences(candidate, array); if (isMajority(count, array.length)) { return Optional.of(candidate); } return Optional.empty(); } /** * Identifies the potential majority candidate using Boyer-Moore's Voting Algorithm. * * @param array the input array * @return the candidate for the majority element */ private static int findCandidate(final int[] array) { int count = 0; int candidate = -1; for (int value : array) { if (count == 0) { candidate = value; } count += (value == candidate) ? 1 : -1; } return candidate; } /** * Counts the occurrences of the candidate element in the array. * * @param candidate the candidate element * @param array the input array * @return the number of times the candidate appears in the array */ private static int countOccurrences(final int candidate, final int[] array) { int count = 0; for (int value : array) { if (value == candidate) { count++; } } return count; } /** * Determines if the count of the candidate element is more than n/2, where n is the length of the array. * * @param count the number of occurrences of the candidate * @param totalCount the total number of elements in the array * @return true if the candidate is the majority element, false otherwise */ private static boolean isMajority(int count, int totalCount) { return 2 * count > totalCount; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/Damm.java
src/main/java/com/thealgorithms/others/Damm.java
package com.thealgorithms.others; import java.util.Objects; /** * Damm algorithm is a check digit algorithm that detects all single-digit * errors and all adjacent transposition errors. It was presented by H. Michael * Damm in 2004. Essential part of the algorithm is a quasigroup of order 10 * (i.e. having a 10 × 10 Latin square as the body of its operation table) with * the special feature of being weakly totally anti-symmetric. Damm revealed * several methods to create totally anti-symmetric quasigroups of order 10 and * gave some examples in his doctoral dissertation. * * @see <a href="https://en.wikipedia.org/wiki/Damm_algorithm">Wiki. Damm * algorithm</a> */ public final class Damm { private Damm() { } /** * Weakly totally anti-symmetric quasigroup of order 10. This table is not * the only possible realisation of weak totally anti-symmetric quasigroup * but the most common one (taken from Damm doctoral dissertation). All * zeros lay on the diagonal because it simplifies the check digit * calculation. */ private static final byte[][] DAMM_TABLE = { {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}, }; /** * Check input digits by Damm algorithm. * * @param digits input to check * @return true if check was successful, false otherwise * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static boolean dammCheck(String digits) { checkInput(digits); int[] numbers = toIntArray(digits); int checksum = 0; for (int number : numbers) { checksum = DAMM_TABLE[checksum][number]; } return checksum == 0; } /** * Calculate check digit for initial digits and add it tho the last * position. * * @param initialDigits initial value * @return digits with the checksum in the last position * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static String addDammChecksum(String initialDigits) { checkInput(initialDigits); int[] numbers = toIntArray(initialDigits); int checksum = 0; for (int number : numbers) { checksum = DAMM_TABLE[checksum][number]; } return initialDigits + checksum; } public static void main(String[] args) { System.out.println("Damm algorithm usage examples:"); var validInput = "5724"; var invalidInput = "5824"; checkAndPrint(validInput); checkAndPrint(invalidInput); System.out.println("\nCheck digit generation example:"); var input = "572"; generateAndPrint(input); } private static void checkAndPrint(String input) { String validationResult = Damm.dammCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addDammChecksum(input); System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } private static int[] toIntArray(String string) { return string.chars().map(i -> Character.digit(i, 10)).toArray(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/Dijkstra.java
src/main/java/com/thealgorithms/others/Dijkstra.java
package com.thealgorithms.others; import java.util.HashMap; import java.util.Map; import java.util.NavigableSet; import java.util.TreeSet; /** * Dijkstra's algorithm,is a graph search algorithm that solves the * single-source shortest path problem for a graph with nonnegative edge path * costs, producing a shortest path tree. * * <p> * NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph * consisting of 2 or more nodes, generally represented by an adjacency matrix * or list, and a start node. * * <p> * Original source of code: * https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java Also most of the * comments are from RosettaCode. */ public final class Dijkstra { private Dijkstra() { } private static final Graph.Edge[] GRAPH = { // Distance from node "a" to node "b" is 7. // In the current Graph there is no way to move the other way (e,g, from "b" to "a"), // a new edge would be needed for that new Graph.Edge("a", "b", 7), new Graph.Edge("a", "c", 9), new Graph.Edge("a", "f", 14), new Graph.Edge("b", "c", 10), new Graph.Edge("b", "d", 15), new Graph.Edge("c", "d", 11), new Graph.Edge("c", "f", 2), new Graph.Edge("d", "e", 6), new Graph.Edge("e", "f", 9), }; private static final String START = "a"; private static final String END = "e"; /** * main function Will run the code with "GRAPH" that was defined above. */ public static void main(String[] args) { Graph g = new Graph(GRAPH); g.dijkstra(START); g.printPath(END); // g.printAllPaths(); } } class Graph { // mapping of vertex names to Vertex objects, built from a set of Edges private final Map<String, Vertex> graph; /** * One edge of the graph (only used by Graph constructor) */ public static class Edge { public final String v1; public final String v2; public final int dist; Edge(String v1, String v2, int dist) { this.v1 = v1; this.v2 = v2; this.dist = dist; } } /** * One vertex of the graph, complete with mappings to neighbouring vertices */ public static class Vertex implements Comparable<Vertex> { public final String name; // MAX_VALUE assumed to be infinity public int dist = Integer.MAX_VALUE; public Vertex previous = null; public final Map<Vertex, Integer> neighbours = new HashMap<>(); Vertex(String name) { this.name = name; } private void printPath() { if (this == this.previous) { System.out.printf("%s", this.name); } else if (this.previous == null) { System.out.printf("%s(unreached)", this.name); } else { this.previous.printPath(); System.out.printf(" -> %s(%d)", this.name, this.dist); } } public int compareTo(Vertex other) { if (dist == other.dist) { return name.compareTo(other.name); } return Integer.compare(dist, other.dist); } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null || getClass() != object.getClass()) { return false; } if (!super.equals(object)) { return false; } Vertex vertex = (Vertex) object; if (dist != vertex.dist) { return false; } if (name != null ? !name.equals(vertex.name) : vertex.name != null) { return false; } if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) { return false; } return neighbours != null ? neighbours.equals(vertex.neighbours) : vertex.neighbours == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + dist; result = 31 * result + (previous != null ? previous.hashCode() : 0); result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0); return result; } @Override public String toString() { return "(" + name + ", " + dist + ")"; } } /** * Builds a graph from a set of edges */ Graph(Edge[] edges) { graph = new HashMap<>(edges.length); // one pass to find all vertices for (Edge e : edges) { if (!graph.containsKey(e.v1)) { graph.put(e.v1, new Vertex(e.v1)); } if (!graph.containsKey(e.v2)) { graph.put(e.v2, new Vertex(e.v2)); } } // another pass to set neighbouring vertices for (Edge e : edges) { graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an // undirected graph } } /** * Runs dijkstra using a specified source vertex */ public void dijkstra(String startName) { if (!graph.containsKey(startName)) { System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName); return; } final Vertex source = graph.get(startName); NavigableSet<Vertex> q = new TreeSet<>(); // set-up vertices for (Vertex v : graph.values()) { v.previous = v == source ? source : null; v.dist = v == source ? 0 : Integer.MAX_VALUE; q.add(v); } dijkstra(q); } /** * Implementation of dijkstra's algorithm using a binary heap. */ private void dijkstra(final NavigableSet<Vertex> q) { Vertex u; Vertex v; while (!q.isEmpty()) { // vertex with shortest distance (first iteration will return source) u = q.pollFirst(); if (u.dist == Integer.MAX_VALUE) { break; // we can ignore u (and any other remaining vertices) since they are // unreachable } // look at distances to each neighbour for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) { v = a.getKey(); // the neighbour in this iteration final int alternateDist = u.dist + a.getValue(); if (alternateDist < v.dist) { // shorter path to neighbour found q.remove(v); v.dist = alternateDist; v.previous = u; q.add(v); } } } } /** * Prints a path from the source to the specified vertex */ public void printPath(String endName) { if (!graph.containsKey(endName)) { System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName); return; } graph.get(endName).printPath(); System.out.println(); } /** * Prints the path from the source to every vertex (output order is not * guaranteed) */ public void printAllPaths() { for (Vertex v : graph.values()) { v.printPath(); System.out.println(); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/BFPRT.java
src/main/java/com/thealgorithms/others/BFPRT.java
package com.thealgorithms.others; /** * The BFPRT (Median of Medians) algorithm implementation. * It provides a way to find the k-th smallest element in an unsorted array * with an optimal worst-case time complexity of O(n). * This algorithm is used to find the k smallest numbers in an array. */ public final class BFPRT { private BFPRT() { } /** * Returns the k smallest elements from the array using the BFPRT algorithm. * * @param arr the input array * @param k the number of smallest elements to return * @return an array containing the k smallest elements, or null if k is invalid */ public static int[] getMinKNumsByBFPRT(int[] arr, int k) { if (k < 1 || k > arr.length) { return null; } int minKth = getMinKthByBFPRT(arr, k); int[] res = new int[k]; int index = 0; for (int value : arr) { if (value < minKth) { res[index++] = value; } } for (; index != res.length; index++) { res[index] = minKth; } return res; } /** * Returns the k-th smallest element from the array using the BFPRT algorithm. * * @param arr the input array * @param k the rank of the smallest element to find * @return the k-th smallest element */ public static int getMinKthByBFPRT(int[] arr, int k) { int[] copyArr = copyArray(arr); return bfprt(copyArr, 0, copyArr.length - 1, k - 1); } /** * Creates a copy of the input array. * * @param arr the input array * @return a copy of the array */ public static int[] copyArray(int[] arr) { int[] copyArr = new int[arr.length]; System.arraycopy(arr, 0, copyArr, 0, arr.length); return copyArr; } /** * BFPRT recursive method to find the k-th smallest element. * * @param arr the input array * @param begin the starting index * @param end the ending index * @param i the index of the desired smallest element * @return the k-th smallest element */ public static int bfprt(int[] arr, int begin, int end, int i) { if (begin == end) { return arr[begin]; } int pivot = medianOfMedians(arr, begin, end); int[] pivotRange = partition(arr, begin, end, pivot); if (i >= pivotRange[0] && i <= pivotRange[1]) { return arr[i]; } else if (i < pivotRange[0]) { return bfprt(arr, begin, pivotRange[0] - 1, i); } else { return bfprt(arr, pivotRange[1] + 1, end, i); } } /** * Finds the median of medians as the pivot element. * * @param arr the input array * @param begin the starting index * @param end the ending index * @return the median of medians */ public static int medianOfMedians(int[] arr, int begin, int end) { int num = end - begin + 1; int offset = num % 5 == 0 ? 0 : 1; int[] mArr = new int[num / 5 + offset]; for (int i = 0; i < mArr.length; i++) { mArr[i] = getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4)); } return bfprt(mArr, 0, mArr.length - 1, mArr.length / 2); } /** * Partitions the array around a pivot. * * @param arr the input array * @param begin the starting index * @param end the ending index * @param num the pivot element * @return the range where the pivot is located */ public static int[] partition(int[] arr, int begin, int end, int num) { int small = begin - 1; int cur = begin; int big = end + 1; while (cur != big) { if (arr[cur] < num) { swap(arr, ++small, cur++); } else if (arr[cur] > num) { swap(arr, --big, cur); } else { cur++; } } return new int[] {small + 1, big - 1}; } /** * Finds the median of the elements between the specified range. * * @param arr the input array * @param begin the starting index * @param end the ending index * @return the median of the specified range */ public static int getMedian(int[] arr, int begin, int end) { insertionSort(arr, begin, end); int sum = begin + end; int mid = sum / 2 + (sum % 2); return arr[mid]; } /** * Sorts a portion of the array using insertion sort. * * @param arr the input array * @param begin the starting index * @param end the ending index */ public static void insertionSort(int[] arr, int begin, int end) { if (arr == null || arr.length < 2) { return; } for (int i = begin + 1; i != end + 1; i++) { for (int j = i; j != begin; j--) { if (arr[j - 1] > arr[j]) { swap(arr, j - 1, j); } else { break; } } } } /** * Swaps two elements in an array. * * @param arr the input array * @param i the index of the first element * @param j the index of the second element */ public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/ArrayRightRotation.java
src/main/java/com/thealgorithms/others/ArrayRightRotation.java
package com.thealgorithms.others; /** * Provides a method to perform a right rotation on an array. * A left rotation operation shifts each element of the array * by a specified number of positions to the right. * * https://en.wikipedia.org/wiki/Right_rotation * */ public final class ArrayRightRotation { private ArrayRightRotation() { } /** * Performs a right rotation on the given array by the specified number of positions. * * @param arr the array to be rotated * @param k the number of positions to rotate the array to the left * @return a new array containing the elements of the input array rotated to the left */ public static int[] rotateRight(int[] arr, int k) { if (arr == null || arr.length == 0 || k < 0) { throw new IllegalArgumentException("Invalid input"); } int n = arr.length; k = k % n; // Handle cases where k is larger than the array length reverseArray(arr, 0, n - 1); reverseArray(arr, 0, k - 1); reverseArray(arr, k, n - 1); return arr; } /** * Performs reversing of a array * @param arr the array to be reversed * @param start starting position * @param end ending position */ private static void reverseArray(int[] arr, int start, int end) { while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/FloydTriangle.java
src/main/java/com/thealgorithms/others/FloydTriangle.java
package com.thealgorithms.others; import java.util.ArrayList; import java.util.List; final class FloydTriangle { private FloydTriangle() { } /** * Generates a Floyd Triangle with the specified number of rows. * * @param rows The number of rows in the triangle. * @return A List representing the Floyd Triangle. */ public static List<List<Integer>> generateFloydTriangle(int rows) { List<List<Integer>> triangle = new ArrayList<>(); int number = 1; for (int i = 0; i < rows; i++) { List<Integer> row = new ArrayList<>(); for (int j = 0; j <= i; j++) { row.add(number++); } triangle.add(row); } return triangle; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/Luhn.java
src/main/java/com/thealgorithms/others/Luhn.java
package com.thealgorithms.others; import java.util.Arrays; import java.util.Objects; /** * The Luhn algorithm or Luhn formula, also known as the "modulus 10" or "mod * 10" algorithm, named after its creator, IBM scientist Hans Peter Luhn, is a * simple checksum formula used to validate a variety of identification numbers. * * <p> * The algorithm is in the public domain and is in wide use today. It is * specified in ISO/IEC 7812-1. It is not intended to be a cryptographically * secure hash function; it was designed to protect against accidental errors, * not malicious attacks. Most credit cards and many government identification * numbers use the algorithm as a simple method of distinguishing valid numbers * from mistyped or otherwise incorrect numbers.</p> * * <p> * The Luhn algorithm will detect any single-digit error, as well as almost all * transpositions of adjacent digits. It will not, however, detect transposition * of the two-digit sequence 09 to 90 (or vice versa). It will detect most of * the possible twin errors (it will not detect 22 ↔ 55, 33 ↔ 66 or 44 ↔ * 77).</p> * * <p> * The check digit is computed as follows:</p> * <ol> * <li>Take the original number and starting from the rightmost digit moving * left, double the value of every second digit (including the rightmost * digit).</li> * <li>Replace the resulting value at each position with the sum of the digits * of this position's value or just subtract 9 from all numbers more or equal * then 10.</li> * <li>Sum up the resulting values from all positions (s).</li> * <li>The calculated check digit is equal to {@code 10 - s % 10}.</li> * </ol> * * @see <a href="https://en.wikipedia.org/wiki/Luhn_algorithm">Wiki</a> */ public final class Luhn { private Luhn() { } /** * Check input digits array by Luhn algorithm. Initial array doesn't change * while processing. * * @param digits array of digits from 0 to 9 * @return true if check was successful, false otherwise */ public static boolean luhnCheck(int[] digits) { int[] numbers = Arrays.copyOf(digits, digits.length); int sum = 0; for (int i = numbers.length - 1; i >= 0; i--) { if (i % 2 == 0) { int temp = numbers[i] * 2; if (temp > 9) { temp = temp - 9; } numbers[i] = temp; } sum += numbers[i]; } return sum % 10 == 0; } public static void main(String[] args) { System.out.println("Luhn algorithm usage examples:"); int[] validInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 7}; int[] invalidInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 4}; // typo in last // symbol checkAndPrint(validInput); checkAndPrint(invalidInput); System.out.println("\nBusiness examples:"); String validCardNumber = "5265 9251 6151 1412"; String invalidCardNumber = "4929 3231 3088 1896"; String illegalCardNumber = "4F15 BC06 3A88 76D5"; businessExample(validCardNumber); businessExample(invalidCardNumber); businessExample(illegalCardNumber); } private static void checkAndPrint(int[] input) { String validationResult = Luhn.luhnCheck(input) ? "valid" : "not valid"; System.out.println("Input " + Arrays.toString(input) + " is " + validationResult); } /* ======================== Business usage example ======================== */ /** * Object representation of credit card. */ private record CreditCard(int[] digits) { private static final int DIGITS_COUNT = 16; /** * @param cardNumber string representation of credit card number - 16 * digits. Can have spaces for digits separation * @return credit card object * @throws IllegalArgumentException if input string is not 16 digits or * if Luhn check was failed */ public static CreditCard fromString(String cardNumber) { Objects.requireNonNull(cardNumber); String trimmedCardNumber = cardNumber.replaceAll(" ", ""); if (trimmedCardNumber.length() != DIGITS_COUNT || !trimmedCardNumber.matches("\\d+")) { throw new IllegalArgumentException("{" + cardNumber + "} - is not a card number"); } int[] cardNumbers = toIntArray(trimmedCardNumber); boolean isValid = luhnCheck(cardNumbers); if (!isValid) { throw new IllegalArgumentException("Credit card number {" + cardNumber + "} - have a typo"); } return new CreditCard(cardNumbers); } /** * @return string representation separated by space every 4 digits. * Example: "5265 9251 6151 1412" */ public String number() { StringBuilder result = new StringBuilder(); for (int i = 0; i < DIGITS_COUNT; i++) { if (i % 4 == 0 && i != 0) { result.append(" "); } result.append(digits[i]); } return result.toString(); } @Override public String toString() { return String.format("%s {%s}", CreditCard.class.getSimpleName(), number()); } private static int[] toIntArray(String string) { return string.chars().map(i -> Character.digit(i, 10)).toArray(); } } private static void businessExample(String cardNumber) { try { System.out.println("Trying to create CreditCard object from valid card number: " + cardNumber); CreditCard creditCard = CreditCard.fromString(cardNumber); System.out.println("And business object is successfully created: " + creditCard + "\n"); } catch (IllegalArgumentException e) { System.out.println("And fail with exception message: " + e.getMessage() + "\n"); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/Conway.java
src/main/java/com/thealgorithms/others/Conway.java
package com.thealgorithms.others; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public final class Conway { private Conway() { } /* * This class will generate the conway sequence also known as the look and say sequence. * To generate a member of the sequence from the previous member, read off the digits of the *previous member, counting the number of digits in groups of the same digit. For example: 1 is *read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, one 1" *or 1211. 1211 is read off as "one 1, one 2, two 1s" or 111221. 111221 is read off as "three *1s, two 2s, one 1" or 312211. https://en.wikipedia.org/wiki/Look-and-say_sequence * */ private static final StringBuilder BUILDER = new StringBuilder(); protected static List<String> generateList(String originalString, int maxIteration) { List<String> numbers = new ArrayList<>(); for (int i = 0; i < maxIteration; i++) { originalString = generateNextElement(originalString); numbers.add(originalString); } return numbers; } public static String generateNextElement(String originalString) { BUILDER.setLength(0); String[] stp = originalString.split("(?<=(.))(?!\\1)"); Arrays.stream(stp).forEach(s -> BUILDER.append(s.length()).append(s.charAt(0))); return BUILDER.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/KochSnowflake.java
src/main/java/com/thealgorithms/others/KochSnowflake.java
package com.thealgorithms.others; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; /** * The Koch snowflake is a fractal curve and one of the earliest fractals to * have been described. The Koch snowflake can be built up iteratively, in a * sequence of stages. The first stage is an equilateral triangle, and each * successive stage is formed by adding outward bends to each side of the * previous stage, making smaller equilateral triangles. This can be achieved * through the following steps for each line: 1. divide the line segment into * three segments of equal length. 2. draw an equilateral triangle that has the * middle segment from step 1 as its base and points outward. 3. remove the line * segment that is the base of the triangle from step 2. (description adapted * from https://en.wikipedia.org/wiki/Koch_snowflake ) (for a more detailed * explanation and an implementation in the Processing language, see * https://natureofcode.com/book/chapter-8-fractals/ * #84-the-koch-curve-and-the-arraylist-technique ). */ public final class KochSnowflake { private KochSnowflake() { } public static void main(String[] args) { // Test Iterate-method ArrayList<Vector2> vectors = new ArrayList<Vector2>(); vectors.add(new Vector2(0, 0)); vectors.add(new Vector2(1, 0)); ArrayList<Vector2> result = iterate(vectors, 1); assert result.get(0).x == 0; assert result.get(0).y == 0; assert result.get(1).x == 1. / 3; assert result.get(1).y == 0; assert result.get(2).x == 1. / 2; assert result.get(2).y == Math.sin(Math.PI / 3) / 3; assert result.get(3).x == 2. / 3; assert result.get(3).y == 0; assert result.get(4).x == 1; assert result.get(4).y == 0; // Test GetKochSnowflake-method int imageWidth = 600; double offsetX = imageWidth / 10.; double offsetY = imageWidth / 3.7; BufferedImage image = getKochSnowflake(imageWidth, 5); // The background should be white assert image.getRGB(0, 0) == new Color(255, 255, 255).getRGB(); // The snowflake is drawn in black and this is the position of the first vector assert image.getRGB((int) offsetX, (int) offsetY) == new Color(0, 0, 0).getRGB(); // Save image try { ImageIO.write(image, "png", new File("KochSnowflake.png")); } catch (IOException e) { e.printStackTrace(); } } /** * Go through the number of iterations determined by the argument "steps". * Be careful with high values (above 5) since the time to calculate * increases exponentially. * * @param initialVectors The vectors composing the shape to which the * algorithm is applied. * @param steps The number of iterations. * @return The transformed vectors after the iteration-steps. */ public static ArrayList<Vector2> iterate(ArrayList<Vector2> initialVectors, int steps) { ArrayList<Vector2> vectors = initialVectors; for (int i = 0; i < steps; i++) { vectors = iterationStep(vectors); } return vectors; } /** * Method to render the Koch snowflake to a image. * * @param imageWidth The width of the rendered image. * @param steps The number of iterations. * @return The image of the rendered Koch snowflake. */ public static BufferedImage getKochSnowflake(int imageWidth, int steps) { if (imageWidth <= 0) { throw new IllegalArgumentException("imageWidth should be greater than zero"); } double offsetX = imageWidth / 10.; double offsetY = imageWidth / 3.7; Vector2 vector1 = new Vector2(offsetX, offsetY); Vector2 vector2 = new Vector2(imageWidth / 2.0, Math.sin(Math.PI / 3.0) * imageWidth * 0.8 + offsetY); Vector2 vector3 = new Vector2(imageWidth - offsetX, offsetY); ArrayList<Vector2> initialVectors = new ArrayList<Vector2>(); initialVectors.add(vector1); initialVectors.add(vector2); initialVectors.add(vector3); initialVectors.add(vector1); ArrayList<Vector2> vectors = iterate(initialVectors, steps); return getImage(vectors, imageWidth, imageWidth); } /** * Loops through each pair of adjacent vectors. Each line between two * adjacent vectors is divided into 4 segments by adding 3 additional * vectors in-between the original two vectors. The vector in the middle is * constructed through a 60 degree rotation so it is bent outwards. * * @param vectors The vectors composing the shape to which the algorithm is * applied. * @return The transformed vectors after the iteration-step. */ private static ArrayList<Vector2> iterationStep(List<Vector2> vectors) { ArrayList<Vector2> newVectors = new ArrayList<Vector2>(); for (int i = 0; i < vectors.size() - 1; i++) { Vector2 startVector = vectors.get(i); Vector2 endVector = vectors.get(i + 1); newVectors.add(startVector); Vector2 differenceVector = endVector.subtract(startVector).multiply(1. / 3); newVectors.add(startVector.add(differenceVector)); newVectors.add(startVector.add(differenceVector).add(differenceVector.rotate(60))); newVectors.add(startVector.add(differenceVector.multiply(2))); } newVectors.add(vectors.get(vectors.size() - 1)); return newVectors; } /** * Utility-method to render the Koch snowflake to an image. * * @param vectors The vectors defining the edges to be rendered. * @param imageWidth The width of the rendered image. * @param imageHeight The height of the rendered image. * @return The image of the rendered edges. */ private static BufferedImage getImage(ArrayList<Vector2> vectors, int imageWidth, int imageHeight) { BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); // Set the background white g2d.setBackground(Color.WHITE); g2d.fillRect(0, 0, imageWidth, imageHeight); // Draw the edges g2d.setColor(Color.BLACK); BasicStroke bs = new BasicStroke(1); g2d.setStroke(bs); for (int i = 0; i < vectors.size() - 1; i++) { int x1 = (int) vectors.get(i).x; int y1 = (int) vectors.get(i).y; int x2 = (int) vectors.get(i + 1).x; int y2 = (int) vectors.get(i + 1).y; g2d.drawLine(x1, y1, x2, y2); } return image; } /** * Inner class to handle the vector calculations. */ private static class Vector2 { double x; double y; Vector2(double x, double y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("[%f, %f]", this.x, this.y); } /** * Vector addition * * @param vector The vector to be added. * @return The sum-vector. */ public Vector2 add(Vector2 vector) { double x = this.x + vector.x; double y = this.y + vector.y; return new Vector2(x, y); } /** * Vector subtraction * * @param vector The vector to be subtracted. * @return The difference-vector. */ public Vector2 subtract(Vector2 vector) { double x = this.x - vector.x; double y = this.y - vector.y; return new Vector2(x, y); } /** * Vector scalar multiplication * * @param scalar The factor by which to multiply the vector. * @return The scaled vector. */ public Vector2 multiply(double scalar) { double x = this.x * scalar; double y = this.y * scalar; return new Vector2(x, y); } /** * Vector rotation (see https://en.wikipedia.org/wiki/Rotation_matrix) * * @param angleInDegrees The angle by which to rotate the vector. * @return The rotated vector. */ public Vector2 rotate(double angleInDegrees) { double radians = angleInDegrees * Math.PI / 180; double ca = Math.cos(radians); double sa = Math.sin(radians); double x = ca * this.x - sa * this.y; double y = sa * this.x + ca * this.y; return new Vector2(x, y); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/TwoPointers.java
src/main/java/com/thealgorithms/others/TwoPointers.java
package com.thealgorithms.others; /** * The two-pointer technique is a useful tool to utilize when searching for * pairs in a sorted array. * * <p> * Link: https://www.geeksforgeeks.org/two-pointers-technique/ */ public final class TwoPointers { private TwoPointers() { } /** * Checks whether there exists a pair of elements in a sorted array whose sum equals the specified key. * * @param arr a sorted array of integers in ascending order (must not be null) * @param key the target sum to find * @return {@code true} if there exists at least one pair whose sum equals {@code key}, {@code false} otherwise * @throws IllegalArgumentException if {@code arr} is {@code null} */ public static boolean isPairedSum(int[] arr, int key) { if (arr == null) { throw new IllegalArgumentException("Input array must not be null."); } int left = 0; int right = arr.length - 1; while (left < right) { int sum = arr[left] + arr[right]; if (sum == key) { return true; } if (sum < key) { left++; } else { right--; } } return false; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/BankersAlgorithm.java
src/main/java/com/thealgorithms/others/BankersAlgorithm.java
package com.thealgorithms.others; import java.util.Scanner; /** * This file contains an implementation of BANKER'S ALGORITHM Wikipedia: * https://en.wikipedia.org/wiki/Banker%27s_algorithm * * The algorithm for finding out whether or not a system is in a safe state can * be described as follows: 1. Let Work and Finish be vectors of length ‘m’ and * ‘n’ respectively. Initialize: Work= Available Finish [i]=false; for * i=1,2,……,n 2. Find an i such that both a) Finish [i]=false b) Need_i<=work * * if no such i exists goto step (4) 3. Work=Work + Allocation_i Finish[i]= true * goto step(2) 4. If Finish[i]=true for all i, then the system is in safe * state. * * Time Complexity: O(n*n*m) Space Complexity: O(n*m) where n = number of * processes and m = number of resources. * * @author AMRITESH ANAND (https://github.com/amritesh19) */ public final class BankersAlgorithm { private BankersAlgorithm() { } /** * This method finds the need of each process */ static void calculateNeed(int[][] needArray, int[][] maxArray, int[][] allocationArray, int totalProcess, int totalResources) { for (int i = 0; i < totalProcess; i++) { for (int j = 0; j < totalResources; j++) { needArray[i][j] = maxArray[i][j] - allocationArray[i][j]; } } } /** * This method find the system is in safe state or not * * @param processes[] int array of processes (0...n-1), size = n * @param availableArray[] int array of number of instances of each * resource, size = m * @param maxArray[][] int matrix(2-D array) of maximum demand of each * process in a system, size = n*m * @param allocationArray[][] int matrix(2-D array) of the number of * resources of each type currently allocated to each process, size = n*m * @param totalProcess number of total processes, n * @param totalResources number of total resources, m * * @return boolean if the system is in safe state or not */ static boolean checkSafeSystem(int[] processes, int[] availableArray, int[][] maxArray, int[][] allocationArray, int totalProcess, int totalResources) { int[][] needArray = new int[totalProcess][totalResources]; calculateNeed(needArray, maxArray, allocationArray, totalProcess, totalResources); boolean[] finishProcesses = new boolean[totalProcess]; int[] safeSequenceArray = new int[totalProcess]; int[] workArray = new int[totalResources]; System.arraycopy(availableArray, 0, workArray, 0, totalResources); int count = 0; // While all processes are not finished or system is not in safe state. while (count < totalProcess) { boolean foundSafeSystem = false; for (int m = 0; m < totalProcess; m++) { if (!finishProcesses[m]) { int j; for (j = 0; j < totalResources; j++) { if (needArray[m][j] > workArray[j]) { break; } } if (j == totalResources) { for (int k = 0; k < totalResources; k++) { workArray[k] += allocationArray[m][k]; } safeSequenceArray[count++] = m; finishProcesses[m] = true; foundSafeSystem = true; } } } // If we could not find a next process in safe sequence. if (!foundSafeSystem) { System.out.print("The system is not in the safe state because lack of resources"); return false; } } System.out.print("The system is in safe sequence and the sequence is as follows: "); for (int i = 0; i < totalProcess; i++) { System.out.print("P" + safeSequenceArray[i] + " "); } return true; } /** * This is main method of Banker's Algorithm */ public static void main(String[] args) { int numberOfProcesses; int numberOfResources; Scanner sc = new Scanner(System.in); System.out.println("Enter total number of processes"); numberOfProcesses = sc.nextInt(); System.out.println("Enter total number of resources"); numberOfResources = sc.nextInt(); int[] processes = new int[numberOfProcesses]; for (int i = 0; i < numberOfProcesses; i++) { processes[i] = i; } System.out.println("--Enter the availability of--"); int[] availableArray = new int[numberOfResources]; for (int i = 0; i < numberOfResources; i++) { System.out.println("resource " + i + ": "); availableArray[i] = sc.nextInt(); } System.out.println("--Enter the maximum matrix--"); int[][] maxArray = new int[numberOfProcesses][numberOfResources]; for (int i = 0; i < numberOfProcesses; i++) { System.out.println("For process " + i + ": "); for (int j = 0; j < numberOfResources; j++) { System.out.println("Enter the maximum instances of resource " + j); maxArray[i][j] = sc.nextInt(); } } System.out.println("--Enter the allocation matrix--"); int[][] allocationArray = new int[numberOfProcesses][numberOfResources]; for (int i = 0; i < numberOfProcesses; i++) { System.out.println("For process " + i + ": "); for (int j = 0; j < numberOfResources; j++) { System.out.println("Allocated instances of resource " + j); allocationArray[i][j] = sc.nextInt(); } } checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses, numberOfResources); sc.close(); } } /* Example: n = 5 m = 3 Process Allocation Max Available 0 1 2 0 1 2 0 1 2 0 0 1 0 7 5 3 3 3 2 1 2 0 0 3 2 2 2 3 0 2 9 0 2 3 2 1 1 2 2 2 4 0 0 2 4 3 3 Result: The system is in safe sequence and the sequence is as follows: P1, P3, P4, P0, P2 */
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/PerlinNoise.java
src/main/java/com/thealgorithms/others/PerlinNoise.java
package com.thealgorithms.others; import java.util.Random; import java.util.Scanner; /** * Utility for generating 2D value-noise blended across octaves (commonly known * as Perlin-like noise). * * <p> * The implementation follows the classic approach of: * <ol> * <li>Generate a base grid of random values in [0, 1).</li> * <li>For each octave k, compute a layer by bilinear interpolation of the base * grid * at period 2^k.</li> * <li>Blend all layers from coarse to fine using a geometric series of * amplitudes * controlled by {@code persistence}, then normalize to [0, 1].</li> * </ol> * * <p> * For background see: * <a href="http://devmag.org.za/2009/04/25/perlin-noise/">Perlin Noise</a>. * * <p> * Constraints and notes: * <ul> * <li>{@code width} and {@code height} should be positive.</li> * <li>{@code octaveCount} must be at least 1 (0 would lead to a division by * zero).</li> * <li>{@code persistence} should be in (0, 1], typical values around * 0.5–0.8.</li> * <li>Given the same seed and parameters, results are deterministic.</li> * </ul> */ public final class PerlinNoise { private PerlinNoise() { } /** * Generate a 2D array of blended noise values normalized to [0, 1]. * * @param width width of the noise array (columns) * @param height height of the noise array (rows) * @param octaveCount number of octaves (layers) to blend; must be >= 1 * @param persistence per-octave amplitude multiplier in (0, 1] * @param seed seed for the random base grid * @return a {@code width x height} array containing blended noise values in [0, * 1] */ static float[][] generatePerlinNoise(int width, int height, int octaveCount, float persistence, long seed) { if (width <= 0 || height <= 0) { throw new IllegalArgumentException("width and height must be > 0"); } if (octaveCount < 1) { throw new IllegalArgumentException("octaveCount must be >= 1"); } if (!(persistence > 0f && persistence <= 1f)) { // using > to exclude 0 and NaN throw new IllegalArgumentException("persistence must be in (0, 1]"); } final float[][] base = createBaseGrid(width, height, seed); final float[][][] layers = createLayers(base, width, height, octaveCount); return blendAndNormalize(layers, width, height, persistence); } /** Create the base random lattice values in [0,1). */ static float[][] createBaseGrid(int width, int height, long seed) { final float[][] base = new float[width][height]; Random random = new Random(seed); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { base[x][y] = random.nextFloat(); } } return base; } /** Pre-compute each octave layer at increasing frequency. */ static float[][][] createLayers(float[][] base, int width, int height, int octaveCount) { final float[][][] noiseLayers = new float[octaveCount][][]; for (int octave = 0; octave < octaveCount; octave++) { noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave); } return noiseLayers; } /** Blend layers using geometric amplitudes and normalize to [0,1]. */ static float[][] blendAndNormalize(float[][][] layers, int width, int height, float persistence) { final int octaveCount = layers.length; final float[][] out = new float[width][height]; float amplitude = 1f; float totalAmplitude = 0f; for (int octave = octaveCount - 1; octave >= 0; octave--) { amplitude *= persistence; totalAmplitude += amplitude; final float[][] layer = layers[octave]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { out[x][y] += layer[x][y] * amplitude; } } } if (totalAmplitude <= 0f || Float.isInfinite(totalAmplitude) || Float.isNaN(totalAmplitude)) { throw new IllegalStateException("Invalid totalAmplitude computed during normalization"); } final float invTotal = 1f / totalAmplitude; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { out[x][y] *= invTotal; } } return out; } /** * Generate a single octave layer by bilinear interpolation of a base grid at a * given octave (period = 2^octave). * * @param base base random float array of size {@code width x height} * @param width width of noise array * @param height height of noise array * @param octave current octave (0 for period 1, 1 for period 2, ...) * @return float array containing the octave's interpolated values */ static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) { float[][] perlinNoiseLayer = new float[width][height]; // Calculate period (wavelength) for different shapes. int period = 1 << octave; // 2^k float frequency = 1f / period; // 1/2^k for (int x = 0; x < width; x++) { // Calculate the horizontal sampling indices. int x0 = (x / period) * period; int x1 = (x0 + period) % width; float horizontalBlend = (x - x0) * frequency; for (int y = 0; y < height; y++) { // Calculate the vertical sampling indices. int y0 = (y / period) * period; int y1 = (y0 + period) % height; float verticalBlend = (y - y0) * frequency; // Blend top corners. float top = interpolate(base[x0][y0], base[x1][y0], horizontalBlend); // Blend bottom corners. float bottom = interpolate(base[x0][y1], base[x1][y1], horizontalBlend); // Blend top and bottom interpolation to get the final value for this cell. perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend); } } return perlinNoiseLayer; } /** * Linear interpolation between two values. * * @param a value at alpha = 0 * @param b value at alpha = 1 * @param alpha interpolation factor in [0, 1] * @return interpolated value {@code (1 - alpha) * a + alpha * b} */ static float interpolate(float a, float b, float alpha) { return a * (1 - alpha) + alpha * b; } /** * Small demo that prints a text representation of the noise using a provided * character set. */ public static void main(String[] args) { Scanner in = new Scanner(System.in); final int width; final int height; final int octaveCount; final float persistence; final long seed; final String charset; final float[][] perlinNoise; System.out.println("Width (int): "); width = in.nextInt(); System.out.println("Height (int): "); height = in.nextInt(); System.out.println("Octave count (int): "); octaveCount = in.nextInt(); System.out.println("Persistence (float): "); persistence = in.nextFloat(); System.out.println("Seed (long): "); seed = in.nextLong(); System.out.println("Charset (String): "); charset = in.next(); perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed); final char[] chars = charset.toCharArray(); final int length = chars.length; final float step = 1f / length; // Output based on charset thresholds. for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { float value = step; float noiseValue = perlinNoise[x][y]; for (char c : chars) { if (noiseValue <= value) { System.out.print(c); break; } value += step; } } System.out.println(); } in.close(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java
src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java
package com.thealgorithms.others; import java.util.HashMap; import java.util.Map; /** * Algorithm to find the maximum sum of a subarray of size K with all distinct * elements. * * This implementation uses a sliding window approach with a hash map to * efficiently * track element frequencies within the current window. The algorithm maintains * a window * of size K and slides it across the array, ensuring all elements in the window * are distinct. * * Time Complexity: O(n) where n is the length of the input array * Space Complexity: O(k) for storing elements in the hash map * * @see <a href="https://en.wikipedia.org/wiki/Streaming_algorithm">Streaming * Algorithm</a> * @see <a href="https://en.wikipedia.org/wiki/Sliding_window_protocol">Sliding * Window</a> * @author Swarga-codes (https://github.com/Swarga-codes) */ public final class MaximumSumOfDistinctSubarraysWithLengthK { private MaximumSumOfDistinctSubarraysWithLengthK() { } /** * Finds the maximum sum of a subarray of size K consisting of distinct * elements. * * The algorithm uses a sliding window technique with a frequency map to track * the count of each element in the current window. A window is valid only if * all K elements are distinct (frequency map size equals K). * * @param k The size of the subarray. Must be non-negative. * @param nums The array from which subarrays will be considered. * @return The maximum sum of any distinct-element subarray of size K. * Returns 0 if no such subarray exists or if k is 0 or negative. * @throws IllegalArgumentException if k is negative */ public static long maximumSubarraySum(int k, int... nums) { if (k <= 0 || nums == null || nums.length < k) { return 0; } long maxSum = 0; long currentSum = 0; Map<Integer, Integer> frequencyMap = new HashMap<>(); // Initialize the first window of size k for (int i = 0; i < k; i++) { currentSum += nums[i]; frequencyMap.put(nums[i], frequencyMap.getOrDefault(nums[i], 0) + 1); } // Check if the first window has all distinct elements if (frequencyMap.size() == k) { maxSum = currentSum; } // Slide the window across the array for (int i = k; i < nums.length; i++) { // Remove the leftmost element from the window int leftElement = nums[i - k]; currentSum -= leftElement; int leftFrequency = frequencyMap.get(leftElement); if (leftFrequency == 1) { frequencyMap.remove(leftElement); } else { frequencyMap.put(leftElement, leftFrequency - 1); } // Add the new rightmost element to the window int rightElement = nums[i]; currentSum += rightElement; frequencyMap.put(rightElement, frequencyMap.getOrDefault(rightElement, 0) + 1); // If all elements in the window are distinct, update maxSum if needed if (frequencyMap.size() == k && currentSum > maxSum) { maxSum = currentSum; } } return maxSum; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/IterativeFloodFill.java
src/main/java/com/thealgorithms/others/IterativeFloodFill.java
package com.thealgorithms.others; import java.util.LinkedList; import java.util.Queue; /** * Implementation of the Flood Fill algorithm using an iterative BFS (Breadth-First Search) approach. * * <p>The Flood Fill algorithm is used to fill connected areas in an image with a new color, starting from a specified point. * This implementation uses an iterative BFS approach with a queue * instead of recursion to avoid stack overflow issues with large images.</p> * * <p><b>Implementation Features:</b></p> * <ul> * <li>Supports 8-connected filling (horizontal, vertical, and diagonal directions)</li> * <li>Uses BFS traversal through {@link java.util.Queue}</li> * <li>Includes nested {@code Point} class to represent pixel coordinates</li> * <li>Iterative approach avoids stack overflow for large images</li> * </ul> * * <p><b>Time Complexity:</b> O(M × N) where M and N are the dimensions of the image</p> * <p><b>Space Complexity:</b> O(M × N) in the worst case the queue stores every pixel</p> * * @see <a href="https://www.geeksforgeeks.org/dsa/flood-fill-algorithm">Flood Fill Algorithm - GeeksforGeeks</a> * @see <a href="https://en.wikipedia.org/wiki/Flood_fill">Flood Fill Algorithm - Wikipedia</a> */ public final class IterativeFloodFill { private IterativeFloodFill() { } /** * Iteratively fill the 2D image with new color * * @param image The image to be filled * @param x The x coordinate at which color is to be filled * @param y The y coordinate at which color is to be filled * @param newColor The new color which to be filled in the image * @param oldColor The old color which is to be replaced in the image * @see <a href=https://www.geeksforgeeks.org/dsa/flood-fill-algorithm>FloodFill BFS<a/> */ public static void floodFill(final int[][] image, final int x, final int y, final int newColor, final int oldColor) { if (image.length == 0 || image[0].length == 0 || newColor == oldColor || shouldSkipPixel(image, x, y, oldColor)) { return; } Queue<Point> queue = new LinkedList<>(); queue.add(new Point(x, y)); int[] dx = {0, 0, -1, 1, 1, -1, 1, -1}; int[] dy = {-1, 1, 0, 0, -1, 1, 1, -1}; while (!queue.isEmpty()) { Point currPoint = queue.poll(); if (shouldSkipPixel(image, currPoint.x, currPoint.y, oldColor)) { continue; } image[currPoint.x][currPoint.y] = newColor; for (int i = 0; i < 8; i++) { int curX = currPoint.x + dx[i]; int curY = currPoint.y + dy[i]; if (!shouldSkipPixel(image, curX, curY, oldColor)) { queue.add(new Point(curX, curY)); } } } } /** * Represents a point in 2D space with integer coordinates. */ private static class Point { final int x; final int y; Point(final int x, final int y) { this.x = x; this.y = y; } } /** * Checks if a pixel should be skipped during flood fill operation. * * @param image The image to get boundaries * @param x The x coordinate of pixel to check * @param y The y coordinate of pixel to check * @param oldColor The old color which is to be replaced in the image * @return {@code true} if pixel should be skipped, else {@code false} */ private static boolean shouldSkipPixel(final int[][] image, final int x, final int y, final int oldColor) { if (x < 0 || x >= image.length || y < 0 || y >= image[0].length || image[x][y] != oldColor) { return true; } return false; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/Mandelbrot.java
src/main/java/com/thealgorithms/others/Mandelbrot.java
package com.thealgorithms.others; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * The Mandelbrot set is the set of complex numbers "c" for which the series * "z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a * complex number "c" is a member of the Mandelbrot set if, when starting with * "z_0 = 0" and applying the iteration repeatedly, the absolute value of "z_n" * remains bounded for all "n > 0". Complex numbers can be written as "a + b*i": * "a" is the real component, usually drawn on the x-axis, and "b*i" is the * imaginary component, usually drawn on the y-axis. Most visualizations of the * Mandelbrot set use a color-coding to indicate after how many steps in the * series the numbers outside the set cross the divergence threshold. Images of * the Mandelbrot set exhibit an elaborate and infinitely complicated boundary * that reveals progressively ever-finer recursive detail at increasing * magnifications, making the boundary of the Mandelbrot set a fractal curve. * (description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set ) (see * also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set * ) */ public final class Mandelbrot { private Mandelbrot() { } public static void main(String[] args) { // Test black and white BufferedImage blackAndWhiteImage = getImage(800, 600, -0.6, 0, 3.2, 50, false); // Pixel outside the Mandelbrot set should be white. assert blackAndWhiteImage.getRGB(0, 0) == new Color(255, 255, 255).getRGB(); // Pixel inside the Mandelbrot set should be black. assert blackAndWhiteImage.getRGB(400, 300) == new Color(0, 0, 0).getRGB(); // Test color-coding BufferedImage coloredImage = getImage(800, 600, -0.6, 0, 3.2, 50, true); // Pixel distant to the Mandelbrot set should be red. assert coloredImage.getRGB(0, 0) == new Color(255, 0, 0).getRGB(); // Pixel inside the Mandelbrot set should be black. assert coloredImage.getRGB(400, 300) == new Color(0, 0, 0).getRGB(); // Save image try { ImageIO.write(coloredImage, "png", new File("Mandelbrot.png")); } catch (IOException e) { e.printStackTrace(); } } /** * Method to generate the image of the Mandelbrot set. Two types of * coordinates are used: image-coordinates that refer to the pixels and * figure-coordinates that refer to the complex numbers inside and outside * the Mandelbrot set. The figure-coordinates in the arguments of this * method determine which section of the Mandelbrot set is viewed. The main * area of the Mandelbrot set is roughly between "-1.5 < x < 0.5" and "-1 < * y < 1" in the figure-coordinates. * * @param imageWidth The width of the rendered image. * @param imageHeight The height of the rendered image. * @param figureCenterX The x-coordinate of the center of the figure. * @param figureCenterY The y-coordinate of the center of the figure. * @param figureWidth The width of the figure. * @param maxStep Maximum number of steps to check for divergent behavior. * @param useDistanceColorCoding Render in color or black and white. * @return The image of the rendered Mandelbrot set. */ public static BufferedImage getImage(int imageWidth, int imageHeight, double figureCenterX, double figureCenterY, double figureWidth, int maxStep, boolean useDistanceColorCoding) { if (imageWidth <= 0) { throw new IllegalArgumentException("imageWidth should be greater than zero"); } if (imageHeight <= 0) { throw new IllegalArgumentException("imageHeight should be greater than zero"); } if (maxStep <= 0) { throw new IllegalArgumentException("maxStep should be greater than zero"); } BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); double figureHeight = figureWidth / imageWidth * imageHeight; // loop through the image-coordinates for (int imageX = 0; imageX < imageWidth; imageX++) { for (int imageY = 0; imageY < imageHeight; imageY++) { // determine the figure-coordinates based on the image-coordinates double figureX = figureCenterX + ((double) imageX / imageWidth - 0.5) * figureWidth; double figureY = figureCenterY + ((double) imageY / imageHeight - 0.5) * figureHeight; double distance = getDistance(figureX, figureY, maxStep); // color the corresponding pixel based on the selected coloring-function image.setRGB(imageX, imageY, useDistanceColorCoding ? colorCodedColorMap(distance).getRGB() : blackAndWhiteColorMap(distance).getRGB()); } } return image; } /** * Black and white color-coding that ignores the relative distance. The * Mandelbrot set is black, everything else is white. * * @param distance Distance until divergence threshold * @return The color corresponding to the distance. */ private static Color blackAndWhiteColorMap(double distance) { return distance >= 1 ? new Color(0, 0, 0) : new Color(255, 255, 255); } /** * Color-coding taking the relative distance into account. The Mandelbrot * set is black. * * @param distance Distance until divergence threshold. * @return The color corresponding to the distance. */ private static Color colorCodedColorMap(double distance) { if (distance >= 1) { return new Color(0, 0, 0); } else { // simplified transformation of HSV to RGB // distance determines hue double hue = 360 * distance; double saturation = 1; double val = 255; int hi = (int) (Math.floor(hue / 60)) % 6; double f = hue / 60 - Math.floor(hue / 60); int v = (int) val; int p = 0; int q = (int) (val * (1 - f * saturation)); int t = (int) (val * (1 - (1 - f) * saturation)); switch (hi) { case 0: return new Color(v, t, p); case 1: return new Color(q, v, p); case 2: return new Color(p, v, t); case 3: return new Color(p, q, v); case 4: return new Color(t, p, v); default: return new Color(v, p, q); } } } /** * Return the relative distance (ratio of steps taken to maxStep) after * which the complex number constituted by this x-y-pair diverges. Members * of the Mandelbrot set do not diverge so their distance is 1. * * @param figureX The x-coordinate within the figure. * @param figureX The y-coordinate within the figure. * @param maxStep Maximum number of steps to check for divergent behavior. * @return The relative distance as the ratio of steps taken to maxStep. */ private static double getDistance(double figureX, double figureY, int maxStep) { double a = figureX; double b = figureY; int currentStep = 0; for (int step = 0; step < maxStep; step++) { currentStep = step; double aNew = a * a - b * b + figureX; b = 2 * a * b + figureY; a = aNew; // divergence happens for all complex number with an absolute value // greater than 4 (= divergence threshold) if (a * a + b * b > 4) { break; } } return (double) currentStep / (maxStep - 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/PageRank.java
src/main/java/com/thealgorithms/others/PageRank.java
package com.thealgorithms.others; import java.util.Scanner; /** * PageRank Algorithm Implementation * * <p> * The PageRank algorithm is used by Google Search to rank web pages in their * search engine * results. It was named after Larry Page, one of the founders of Google. * PageRank is a way of * measuring the importance of website pages. * * <p> * Algorithm: 1. Initialize PageRank values for all pages to 1/N (where N is the * total number * of pages) 2. For each iteration: - For each page, calculate the new PageRank * by summing the * contributions from all incoming links - Apply the damping factor: PR(page) = * (1-d) + d * * sum(PR(incoming_page) / outgoing_links(incoming_page)) 3. Repeat until * convergence * * @see <a href="https://en.wikipedia.org/wiki/PageRank">PageRank Algorithm</a> */ public final class PageRank { private static final int MAX_NODES = 10; private static final double DEFAULT_DAMPING_FACTOR = 0.85; private static final int DEFAULT_ITERATIONS = 2; private int[][] adjacencyMatrix; private double[] pageRankValues; private int nodeCount; /** * Constructor to initialize PageRank with specified number of nodes * * @param numberOfNodes the number of nodes/pages in the graph * @throws IllegalArgumentException if numberOfNodes is less than 1 or greater * than MAX_NODES */ public PageRank(int numberOfNodes) { if (numberOfNodes < 1 || numberOfNodes > MAX_NODES) { throw new IllegalArgumentException("Number of nodes must be between 1 and " + MAX_NODES); } this.nodeCount = numberOfNodes; this.adjacencyMatrix = new int[MAX_NODES][MAX_NODES]; this.pageRankValues = new double[MAX_NODES]; } /** * Default constructor for interactive mode */ public PageRank() { this.adjacencyMatrix = new int[MAX_NODES][MAX_NODES]; this.pageRankValues = new double[MAX_NODES]; } /** * Main method for interactive PageRank calculation * * @param args command line arguments (not used) */ public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter the Number of WebPages: "); int nodes = scanner.nextInt(); PageRank pageRank = new PageRank(nodes); System.out.println("Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: "); for (int i = 1; i <= nodes; i++) { for (int j = 1; j <= nodes; j++) { int value = scanner.nextInt(); pageRank.setEdge(i, j, value); } } pageRank.calculatePageRank(nodes, DEFAULT_DAMPING_FACTOR, DEFAULT_ITERATIONS, true); } } /** * Sets an edge in the adjacency matrix * * @param from source node (1-indexed) * @param to destination node (1-indexed) * @param value 1 if edge exists, 0 otherwise */ public void setEdge(int from, int to, int value) { if (from == to) { adjacencyMatrix[from][to] = 0; // No self-loops } else { adjacencyMatrix[from][to] = value; } } /** * Sets the adjacency matrix for the graph * * @param matrix the adjacency matrix (1-indexed) */ public void setAdjacencyMatrix(int[][] matrix) { for (int i = 1; i <= nodeCount; i++) { for (int j = 1; j <= nodeCount; j++) { setEdge(i, j, matrix[i][j]); } } } /** * Gets the PageRank value for a specific node * * @param node the node index (1-indexed) * @return the PageRank value */ public double getPageRank(int node) { if (node < 1 || node > nodeCount) { throw new IllegalArgumentException("Node index out of bounds"); } return pageRankValues[node]; } /** * Gets all PageRank values * * @return array of PageRank values (1-indexed) */ public double[] getAllPageRanks() { return pageRankValues.clone(); } /** * Calculates PageRank using the default damping factor and iterations * * @param totalNodes the total number of nodes * @return array of PageRank values */ public double[] calculatePageRank(int totalNodes) { return calculatePageRank(totalNodes, DEFAULT_DAMPING_FACTOR, DEFAULT_ITERATIONS, false); } /** * Calculates PageRank with custom parameters * * @param totalNodes the total number of nodes * @param dampingFactor the damping factor (typically 0.85) * @param iterations number of iterations to perform * @param verbose whether to print detailed output * @return array of PageRank values */ public double[] calculatePageRank(int totalNodes, double dampingFactor, int iterations, boolean verbose) { validateInputParameters(totalNodes, dampingFactor, iterations); this.nodeCount = totalNodes; double initialPageRank = 1.0 / totalNodes; if (verbose) { System.out.printf("Total Number of Nodes: %d\tInitial PageRank of All Nodes: %.6f%n", totalNodes, initialPageRank); } initializePageRanks(totalNodes, initialPageRank, verbose); performIterations(totalNodes, dampingFactor, iterations, verbose); if (verbose) { System.out.println("\nFinal PageRank:"); printPageRanks(totalNodes); } return pageRankValues.clone(); } /** * Validates input parameters for PageRank calculation * * @param totalNodes the total number of nodes * @param dampingFactor the damping factor * @param iterations number of iterations * @throws IllegalArgumentException if parameters are invalid */ private void validateInputParameters(int totalNodes, double dampingFactor, int iterations) { if (totalNodes < 1 || totalNodes > MAX_NODES) { throw new IllegalArgumentException("Total nodes must be between 1 and " + MAX_NODES); } if (dampingFactor < 0 || dampingFactor > 1) { throw new IllegalArgumentException("Damping factor must be between 0 and 1"); } if (iterations < 1) { throw new IllegalArgumentException("Iterations must be at least 1"); } } /** * Initializes PageRank values for all nodes * * @param totalNodes the total number of nodes * @param initialPageRank the initial PageRank value * @param verbose whether to print output */ private void initializePageRanks(int totalNodes, double initialPageRank, boolean verbose) { for (int i = 1; i <= totalNodes; i++) { pageRankValues[i] = initialPageRank; } if (verbose) { System.out.println("\nInitial PageRank Values, 0th Step"); printPageRanks(totalNodes); } } /** * Performs the iterative PageRank calculation * * @param totalNodes the total number of nodes * @param dampingFactor the damping factor * @param iterations number of iterations * @param verbose whether to print output */ private void performIterations(int totalNodes, double dampingFactor, int iterations, boolean verbose) { for (int iteration = 1; iteration <= iterations; iteration++) { double[] tempPageRank = storeCurrentPageRanks(totalNodes); calculateNewPageRanks(totalNodes, tempPageRank); applyDampingFactor(totalNodes, dampingFactor); if (verbose) { System.out.printf("%nAfter %d iteration(s)%n", iteration); printPageRanks(totalNodes); } } } /** * Stores current PageRank values in a temporary array * * @param totalNodes the total number of nodes * @return temporary array with current PageRank values */ private double[] storeCurrentPageRanks(int totalNodes) { double[] tempPageRank = new double[MAX_NODES]; for (int i = 1; i <= totalNodes; i++) { tempPageRank[i] = pageRankValues[i]; pageRankValues[i] = 0; } return tempPageRank; } /** * Calculates new PageRank values based on incoming links * * @param totalNodes the total number of nodes * @param tempPageRank temporary array with previous PageRank values */ private void calculateNewPageRanks(int totalNodes, double[] tempPageRank) { for (int targetNode = 1; targetNode <= totalNodes; targetNode++) { for (int sourceNode = 1; sourceNode <= totalNodes; sourceNode++) { if (adjacencyMatrix[sourceNode][targetNode] == 1) { int outgoingLinks = countOutgoingLinks(sourceNode, totalNodes); if (outgoingLinks > 0) { pageRankValues[targetNode] += tempPageRank[sourceNode] / outgoingLinks; } } } } } /** * Applies the damping factor to all PageRank values * * @param totalNodes the total number of nodes * @param dampingFactor the damping factor */ private void applyDampingFactor(int totalNodes, double dampingFactor) { for (int i = 1; i <= totalNodes; i++) { pageRankValues[i] = (1 - dampingFactor) + dampingFactor * pageRankValues[i]; } } /** * Counts the number of outgoing links from a node * * @param node the source node (1-indexed) * @param totalNodes total number of nodes * @return the count of outgoing links */ private int countOutgoingLinks(int node, int totalNodes) { int count = 0; for (int i = 1; i <= totalNodes; i++) { if (adjacencyMatrix[node][i] == 1) { count++; } } return count; } /** * Prints the PageRank values for all nodes * * @param totalNodes the total number of nodes */ private void printPageRanks(int totalNodes) { for (int i = 1; i <= totalNodes; i++) { System.out.printf("PageRank of %d: %.6f%n", i, pageRankValues[i]); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/PasswordGen.java
src/main/java/com/thealgorithms/others/PasswordGen.java
package com.thealgorithms.others; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Creates a random password from ASCII letters Given password length bounds * * @author AKS1996 * @date 2017.10.25 */ final class PasswordGen { private static final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"; private static final String DIGITS = "0123456789"; private static final String SPECIAL_CHARACTERS = "!@#$%^&*(){}?"; private static final String ALL_CHARACTERS = UPPERCASE_LETTERS + LOWERCASE_LETTERS + DIGITS + SPECIAL_CHARACTERS; private PasswordGen() { } /** * Generates a random password with a length between minLength and maxLength. * * @param minLength The minimum length of the password. * @param maxLength The maximum length of the password. * @return A randomly generated password. * @throws IllegalArgumentException if minLength is greater than maxLength or if either is non-positive. */ public static String generatePassword(int minLength, int maxLength) { if (minLength > maxLength || minLength <= 0 || maxLength <= 0) { throw new IllegalArgumentException("Incorrect length parameters: minLength must be <= maxLength and both must be > 0"); } Random random = new Random(); List<Character> letters = new ArrayList<>(); for (char c : ALL_CHARACTERS.toCharArray()) { letters.add(c); } // Inbuilt method to randomly shuffle a elements of a list Collections.shuffle(letters); StringBuilder password = new StringBuilder(); // Note that size of the password is also random for (int i = random.nextInt(maxLength - minLength) + minLength; i > 0; --i) { password.append(ALL_CHARACTERS.charAt(random.nextInt(ALL_CHARACTERS.length()))); } return password.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
package com.thealgorithms.others; import java.util.ArrayList; /** * @author Alexandros Lemonaris */ public abstract class MemoryManagementAlgorithms { /** * Method to allocate memory to blocks according to CPU algorithms. * Use of inheritance to avoid repeated code. * Abstract method since it is implemented different for each algorithm. * It should return an ArrayList of Integers, where the index is the process * ID (zero-indexed) and the value is the block number (also zero-indexed). * @param sizeOfBlocks an int array that contains the sizes of the memory * blocks available. * @param sizeOfProcesses: an int array that contains the sizes of the * processes we need memory blocks for. * @return the ArrayList filled with Integers representing the memory * allocation that took place. */ public abstract ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses); /** * A constant value used to indicate that an allocation has not been made. * This value is used as a sentinel value to represent that no allocation has been made * when allocating space in an array or other data structure. * The value is -255 and is marked as protected and final to ensure that it cannot be modified * from outside the class and that its value remains consistent throughout the program * execution. * * @author: Ishan Makadia (github.com/intrepid-ishan) * @version: April 06, 2023 */ protected static final int NO_ALLOCATION = -255; } /** * @author Dekas Dimitrios */ class BestFitCPU extends MemoryManagementAlgorithms { /** * Method to find the maximum valued element of an array filled with * positive integers. * * @param array: an array filled with positive integers. * @return the maximum valued element of the array. */ private static int findMaxElement(int[] array) { int max = -1; for (int value : array) { if (value > max) { max = value; } } return max; } /** * Method to find the index of the memory block that is going to fit the * given process based on the best fit algorithm. * * @param blocks: the array with the available memory blocks. * @param process: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. */ private static int findBestFit(int[] blockSizes, int processSize) { // Initialize minDiff with an unreachable value by a difference between a blockSize and the // processSize. int minDiff = findMaxElement(blockSizes); int index = NO_ALLOCATION; // If there is no block that can fit the process, return // NO_ALLOCATION as the // result. for (int i = 0; i < blockSizes.length; i++) { // Find the most fitting memory block for the given process. if (blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) { minDiff = blockSizes[i] - processSize; index = i; } } return index; } /** * Method to allocate memory to blocks according to the best fit algorithm. * It should return an ArrayList of Integers, where the index is the process * ID (zero-indexed) and the value is the block number (also zero-indexed). * * @param sizeOfBlocks: an int array that contains the sizes of the memory * blocks available. * @param sizeOfProcesses: an int array that contains the sizes of the * processes we need memory blocks for. * @return the ArrayList filled with Integers representing the memory * allocation that took place. */ public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { // The array list responsible for saving the memory allocations done by the best-fit // algorithm ArrayList<Integer> memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { int chosenBlockIdx = findBestFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size } } return memAlloc; } } /** * @author Dekas Dimitrios */ class WorstFitCPU extends MemoryManagementAlgorithms { /** * Method to find the index of the memory block that is going to fit the * given process based on the worst fit algorithm. * * @param blocks: the array with the available memory blocks. * @param process: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. */ private static int findWorstFit(int[] blockSizes, int processSize) { int max = -1; int index = -1; for (int i = 0; i < blockSizes.length; i++) { // Find the index of the biggest memory block available. if (blockSizes[i] > max) { max = blockSizes[i]; index = i; } } // If the biggest memory block cannot fit the process, return -255 as the result if (processSize > blockSizes[index]) { return NO_ALLOCATION; } return index; } /** * Method to allocate memory to blocks according to the worst fit algorithm. * It should return an ArrayList of Integers, where the index is the process * ID (zero-indexed) and the value is the block number (also zero-indexed). * * @param sizeOfBlocks: an int array that contains the sizes of the memory * blocks available. * @param sizeOfProcesses: an int array that contains the sizes of the * processes we need memory blocks for. * @return the ArrayList filled with Integers representing the memory * allocation that took place. */ public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { // The array list responsible for saving the memory allocations done by the worst-fit // algorithm ArrayList<Integer> memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { int chosenBlockIdx = findWorstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size } } return memAlloc; } } /** * @author Dekas Dimitrios */ class FirstFitCPU extends MemoryManagementAlgorithms { /** * Method to find the index of the memory block that is going to fit the * given process based on the first fit algorithm. * * @param blocks: the array with the available memory blocks. * @param process: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. */ private static int findFirstFit(int[] blockSizes, int processSize) { for (int i = 0; i < blockSizes.length; i++) { if (blockSizes[i] >= processSize) { return i; } } // If there is not a block that can fit the process, return -255 as the result return NO_ALLOCATION; } /** * Method to allocate memory to blocks according to the first fit algorithm. * It should return an ArrayList of Integers, where the index is the process * ID (zero-indexed) and the value is the block number (also zero-indexed). * * @param sizeOfBlocks: an int array that contains the sizes of the memory * blocks available. * @param sizeOfProcesses: an int array that contains the sizes of the * processes we need memory blocks for. * @return the ArrayList filled with Integers representing the memory * allocation that took place. */ public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { // The array list responsible for saving the memory allocations done by the first-fit // algorithm ArrayList<Integer> memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { int chosenBlockIdx = findFirstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size } } return memAlloc; } } /** * @author Alexandros Lemonaris */ class NextFit extends MemoryManagementAlgorithms { private int counter = 0; // variable that keeps the position of the last registration into the memory /** * Method to find the index of the memory block that is going to fit the * given process based on the next fit algorithm. In the case of next fit, * if the search is interrupted in between, the new search is carried out from the last * location. * * @param blocks: the array with the available memory blocks. * @param process: the size of the process. * @return the index of the block that fits, or -255 if no such block * exists. */ private int findNextFit(int[] blockSizes, int processSize) { for (int i = 0; i < blockSizes.length; i++) { if (counter + i >= blockSizes.length) { counter = -i; // starts from the start of the array } if (blockSizes[i + counter] >= processSize) { counter += i; return counter; } } // If there is not a block that can fit the process, return -255 as the result counter += blockSizes.length; // counter keeps its last value return NO_ALLOCATION; } /** * Method to allocate memory to blocks according to the first fit algorithm. * It should return an ArrayList of Integers, where the index is the process * ID (zero-indexed) and the value is the block number (also zero-indexed). * * @param sizeOfBlocks: an int array that contains the sizes of the memory * blocks available. * @param sizeOfProcesses: an int array that contains the sizes of the * processes we need memory blocks for. * @return the ArrayList filled with Integers representing the memory * allocation that took place. */ public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { // The array list responsible for saving the memory allocations done by the first-fit // algorithm ArrayList<Integer> memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { int chosenBlockIdx = findNextFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size } } return memAlloc; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/CRCAlgorithm.java
src/main/java/com/thealgorithms/others/CRCAlgorithm.java
package com.thealgorithms.others; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; /** * @author dimgrichr */ @SuppressWarnings("unchecked") public class CRCAlgorithm { private int correctMess; private int wrongMess; private int wrongMessCaught; private int wrongMessNotCaught; private int messSize; private double ber; private boolean messageChanged; private ArrayList<Integer> message; private ArrayList<Integer> p; private Random randomGenerator; /** * The algorithm's main constructor. The most significant variables, used in * the algorithm, are set in their initial values. * * @param str The binary number P, in a string form, which is used by the * CRC algorithm * @param size The size of every transmitted message * @param ber The Bit Error Rate */ public CRCAlgorithm(String str, int size, double ber) { messageChanged = false; message = new ArrayList<>(); messSize = size; p = new ArrayList<>(); for (int i = 0; i < str.length(); i++) { p.add(Character.getNumericValue(str.charAt(i))); } randomGenerator = new Random(); correctMess = 0; wrongMess = 0; wrongMessCaught = 0; wrongMessNotCaught = 0; this.ber = ber; } /** * Returns the counter wrongMess * * @return wrongMess, the number of Wrong Messages */ public int getWrongMess() { return wrongMess; } /** * Returns the counter wrongMessCaught * * @return wrongMessCaught, the number of wrong messages, which are caught * by the CRC algoriithm */ public int getWrongMessCaught() { return wrongMessCaught; } /** * Returns the counter wrongMessNotCaught * * @return wrongMessNotCaught, the number of wrong messages, which are not * caught by the CRC algorithm */ public int getWrongMessNotCaught() { return wrongMessNotCaught; } /** * Returns the counter correctMess * * @return correctMess, the number of the Correct Messages */ public int getCorrectMess() { return correctMess; } /** * Resets some of the object's values, used on the main function, so that it * can be reused, in order not to waste too much memory and time, by * creating new objects. */ public void refactor() { messageChanged = false; message = new ArrayList<>(); } /** * Random messages, consisted of 0's and 1's, are generated, so that they * can later be transmitted */ public void generateRandomMess() { for (int i = 0; i < messSize; i++) { int x = ThreadLocalRandom.current().nextInt(0, 2); message.add(x); } } /** * The most significant part of the CRC algorithm. The message is divided by * P, so the dividedMessage ArrayList<Integer> is created. If check == true, * the dividedMessaage is examined, in order to see if it contains any 1's. * If it does, the message is considered to be wrong by the receiver,so the * variable wrongMessCaught changes. If it does not, it is accepted, so one * of the variables correctMess, wrongMessNotCaught, changes. If check == * false, the diviided Message is added at the end of the ArrayList<integer> * message. * * @param check the variable used to determine, if the message is going to * be checked from the receiver if true, it is checked otherwise, it is not */ public void divideMessageWithP(boolean check) { ArrayList<Integer> x = new ArrayList<>(); ArrayList<Integer> k = (ArrayList<Integer>) message.clone(); if (!check) { for (int i = 0; i < p.size() - 1; i++) { k.add(0); } } while (!k.isEmpty()) { while (x.size() < p.size() && !k.isEmpty()) { x.add(k.get(0)); k.remove(0); } if (x.size() == p.size()) { for (int i = 0; i < p.size(); i++) { if (x.get(i) == p.get(i)) { x.set(i, 0); } else { x.set(i, 1); } } for (int i = 0; i < x.size() && x.get(i) != 1; i++) { x.remove(0); } } } ArrayList<Integer> dividedMessage = (ArrayList<Integer>) x.clone(); if (!check) { message.addAll(dividedMessage); } else { if (dividedMessage.contains(1) && messageChanged) { wrongMessCaught++; } else if (!dividedMessage.contains(1) && messageChanged) { wrongMessNotCaught++; } else if (!messageChanged) { correctMess++; } } } /** * Once the message is transmitted, some of it's elements, is possible to * change from 1 to 0, or from 0 to 1, because of the Bit Error Rate (ber). * For every element of the message, a random double number is created. If * that number is smaller than ber, then the specific element changes. On * the other hand, if it's bigger than ber, it does not. Based on these * changes. the boolean variable messageChanged, gets the value: true, or * false. */ public void changeMess() { for (int y : message) { double x = randomGenerator.nextDouble(); while (x < 0.0000 || x > 1.00000) { x = randomGenerator.nextDouble(); } if (x < ber) { messageChanged = true; if (y == 1) { message.set(message.indexOf(y), 0); } else { message.set(message.indexOf(y), 1); } } } if (messageChanged) { wrongMess++; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/Verhoeff.java
src/main/java/com/thealgorithms/others/Verhoeff.java
package com.thealgorithms.others; import java.util.Objects; /** * The Verhoeff algorithm is a checksum formula for error detection developed by * the Dutch mathematician Jacobus Verhoeff and was first published in 1969. It * was the first decimal check digit algorithm which detects all single-digit * errors, and all transposition errors involving two adjacent digits. * * <p> * The strengths of the algorithm are that it detects all transliteration and * transposition errors, and additionally most twin, twin jump, jump * transposition and phonetic errors. The main weakness of the Verhoeff * algorithm is its complexity. The calculations required cannot easily be * expressed as a formula. For easy calculation three tables are required:</p> * <ol> * <li>multiplication table</li> * <li>inverse table</li> * <li>permutation table</li> * </ol> * * @see <a href="https://en.wikipedia.org/wiki/Verhoeff_algorithm">Wiki. * Verhoeff algorithm</a> */ public final class Verhoeff { private Verhoeff() { } /** * Table {@code d}. Based on multiplication in the dihedral group D5 and is * simply the Cayley table of the group. Note that this group is not * commutative, that is, for some values of {@code j} and {@code k}, * {@code d(j,k) ≠ d(k, j)}. * * @see <a href="https://en.wikipedia.org/wiki/Dihedral_group">Wiki. * Dihedral group</a> */ private static final byte[][] MULTIPLICATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; /** * The inverse table {@code inv}. Represents the multiplicative inverse of a * digit, that is, the value that satisfies {@code d(j, inv(j)) = 0}. */ private static final byte[] MULTIPLICATIVE_INVERSE = { 0, 4, 3, 2, 1, 5, 6, 7, 8, 9, }; /** * The permutation table {@code p}. Applies a permutation to each digit * based on its position in the number. This is actually a single * permutation {@code (1 5 8 9 4 2 7 0)(3 6)} applied iteratively; i.e. * {@code p(i+j,n) = p(i, p(j,n))}. */ private static final byte[][] PERMUTATION_TABLE = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; /** * Check input digits by Verhoeff algorithm. * * @param digits input to check * @return true if check was successful, false otherwise * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static boolean verhoeffCheck(String digits) { checkInput(digits); int[] numbers = toIntArray(digits); // The Verhoeff algorithm int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } return checksum == 0; } /** * Calculate check digit for initial digits and add it tho the last * position. * * @param initialDigits initial value * @return digits with the checksum in the last position * @throws IllegalArgumentException if input parameter contains not only * digits * @throws NullPointerException if input is null */ public static String addVerhoeffChecksum(String initialDigits) { checkInput(initialDigits); // Add zero to end of input value var modifiedDigits = initialDigits + "0"; int[] numbers = toIntArray(modifiedDigits); int checksum = 0; for (int i = 0; i < numbers.length; i++) { int index = numbers.length - i - 1; byte b = PERMUTATION_TABLE[i % 8][numbers[index]]; checksum = MULTIPLICATION_TABLE[checksum][b]; } checksum = MULTIPLICATIVE_INVERSE[checksum]; return initialDigits + checksum; } public static void main(String[] args) { System.out.println("Verhoeff algorithm usage examples:"); var validInput = "2363"; var invalidInput = "2364"; checkAndPrint(validInput); checkAndPrint(invalidInput); System.out.println("\nCheck digit generation example:"); var input = "236"; generateAndPrint(input); } private static void checkAndPrint(String input) { String validationResult = Verhoeff.verhoeffCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addVerhoeffChecksum(input); System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } private static int[] toIntArray(String string) { return string.chars().map(i -> Character.digit(i, 10)).toArray(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java
src/main/java/com/thealgorithms/others/ArrayLeftRotation.java
package com.thealgorithms.others; /** * Provides a method to perform a left rotation on an array. * A left rotation operation shifts each element of the array * by a specified number of positions to the left. * * @author sangin-lee */ public final class ArrayLeftRotation { private ArrayLeftRotation() { } /** * Performs a left rotation on the given array by the specified number of positions. * * @param arr the array to be rotated * @param n the number of positions to rotate the array to the left * @return a new array containing the elements of the input array rotated to the left */ public static int[] rotateLeft(int[] arr, int n) { int size = arr.length; // Handle cases where array is empty or rotation count is zero if (size == 0 || n <= 0) { return arr.clone(); } // Normalize the number of rotations n = n % size; if (n == 0) { return arr.clone(); } int[] rotated = new int[size]; // Perform rotation for (int i = 0; i < size; i++) { rotated[i] = arr[(i + n) % size]; } return rotated; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/others/cn/HammingDistance.java
src/main/java/com/thealgorithms/others/cn/HammingDistance.java
package com.thealgorithms.others.cn; public final class HammingDistance { private HammingDistance() { } private static void checkChar(char inChar) { if (inChar != '0' && inChar != '1') { throw new IllegalArgumentException("Input must be a binary string."); } } public static int compute(char charA, char charB) { checkChar(charA); checkChar(charB); return charA == charB ? 0 : 1; } public static int compute(String bitsStrA, String bitsStrB) { if (bitsStrA.length() != bitsStrB.length()) { throw new IllegalArgumentException("Input strings must have the same length."); } int totalErrorBitCount = 0; for (int i = 0; i < bitsStrA.length(); i++) { totalErrorBitCount += compute(bitsStrA.charAt(i), bitsStrB.charAt(i)); } return totalErrorBitCount; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/slidingwindow/MaximumSlidingWindow.java
src/main/java/com/thealgorithms/slidingwindow/MaximumSlidingWindow.java
package com.thealgorithms.slidingwindow; import java.util.ArrayDeque; import java.util.Deque; /** * Maximum Sliding Window Algorithm * * This algorithm finds the maximum element in each sliding window of size k * in a given array of integers. It uses a deque (double-ended queue) to * efficiently keep track of potential maximum values in the current window. * * Time Complexity: O(n), where n is the number of elements in the input array * Space Complexity: O(k), where k is the size of the sliding window */ public class MaximumSlidingWindow { /** * Finds the maximum values in each sliding window of size k. * * @param nums The input array of integers * @param windowSize The size of the sliding window * @return An array of integers representing the maximums in each window */ public int[] maxSlidingWindow(int[] nums, int windowSize) { if (nums == null || nums.length == 0 || windowSize <= 0 || windowSize > nums.length) { return new int[0]; // Handle edge cases } int[] result = new int[nums.length - windowSize + 1]; Deque<Integer> deque = new ArrayDeque<>(); for (int currentIndex = 0; currentIndex < nums.length; currentIndex++) { // Remove the first element if it's outside the current window if (!deque.isEmpty() && deque.peekFirst() == currentIndex - windowSize) { deque.pollFirst(); } // Remove all elements smaller than the current element from the end while (!deque.isEmpty() && nums[deque.peekLast()] < nums[currentIndex]) { deque.pollLast(); } // Add the current element's index to the deque deque.offerLast(currentIndex); // If we have processed at least k elements, add to result if (currentIndex >= windowSize - 1) { result[currentIndex - windowSize + 1] = nums[deque.peekFirst()]; } } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/slidingwindow/ShortestCoprimeSegment.java
src/main/java/com/thealgorithms/slidingwindow/ShortestCoprimeSegment.java
package com.thealgorithms.slidingwindow; import java.util.Arrays; import java.util.LinkedList; /** * The Sliding Window technique together with 2-stack technique is used to find coprime segment of minimal size in an array. * Segment a[i],...,a[i+l] is coprime if gcd(a[i], a[i+1], ..., a[i+l]) = 1 * <p> * Run-time complexity: O(n log n) * What is special about this 2-stack technique is that it enables us to remove element a[i] and find gcd(a[i+1],...,a[i+l]) in amortized O(1) time. * For 'remove' worst-case would be O(n) operation, but this happens rarely. * Main observation is that each element gets processed a constant amount of times, hence complexity will be: * O(n log n), where log n comes from complexity of gcd. * <p> * More generally, the 2-stack technique enables us to 'remove' an element fast if it is known how to 'add' an element fast to the set. * In our case 'adding' is calculating d' = gcd(a[i],...,a[i+l+1]), when d = gcd(a[i],...a[i]) with d' = gcd(d, a[i+l+1]). * and removing is find gcd(a[i+1],...,a[i+l]). We don't calculate it explicitly, but it is pushed in the stack which we can pop in O(1). * <p> * One can change methods 'legalSegment' and function 'f' in DoubleStack to adapt this code to other sliding-window type problems. * I recommend this article for more explanations: "<a href="https://codeforces.com/edu/course/2/lesson/9/2">CF Article</a>">Article 1</a> or <a href="https://usaco.guide/gold/sliding-window?lang=cpp#method-2---two-stacks">USACO Article</a> * <p> * Another method to solve this problem is through segment trees. Then query operation would have O(log n), not O(1) time, but runtime complexity would still be O(n log n) * * @author DomTr (<a href="https://github.com/DomTr">Github</a>) */ public final class ShortestCoprimeSegment { // Prevent instantiation private ShortestCoprimeSegment() { } /** * @param arr is the input array * @return shortest segment in the array which has gcd equal to 1. If no such segment exists or array is empty, returns empty array */ public static long[] shortestCoprimeSegment(long[] arr) { if (arr == null || arr.length == 0) { return new long[] {}; } DoubleStack front = new DoubleStack(); DoubleStack back = new DoubleStack(); int n = arr.length; int l = 0; int shortestLength = n + 1; int beginsAt = -1; // beginning index of the shortest coprime segment for (int i = 0; i < n; i++) { back.push(arr[i]); while (legalSegment(front, back)) { remove(front, back); if (shortestLength > i - l + 1) { beginsAt = l; shortestLength = i - l + 1; } l++; } } if (shortestLength > n) { shortestLength = -1; } if (shortestLength == -1) { return new long[] {}; } return Arrays.copyOfRange(arr, beginsAt, beginsAt + shortestLength); } private static boolean legalSegment(DoubleStack front, DoubleStack back) { return gcd(front.top(), back.top()) == 1; } private static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } else if (b == 0) { return a; } else { return gcd(a % b, b); } } /** * This solves the problem of removing elements quickly. * Even though the worst case of 'remove' method is O(n), it is a very pessimistic view. * We will need to empty out 'back', only when 'from' is empty. * Consider element x when it is added to stack 'back'. * After some time 'front' becomes empty and x goes to 'front'. Notice that in the for-loop we proceed further and x will never come back to any stacks 'back' or 'front'. * In other words, every element gets processed by a constant number of operations. * So 'remove' amortized runtime is actually O(n). */ private static void remove(DoubleStack front, DoubleStack back) { if (front.isEmpty()) { while (!back.isEmpty()) { front.push(back.pop()); } } front.pop(); } /** * DoubleStack serves as a collection of two stacks. One is a normal stack called 'stack', the other 'values' stores gcd-s up until some index. */ private static class DoubleStack { LinkedList<Long> stack; LinkedList<Long> values; DoubleStack() { values = new LinkedList<>(); stack = new LinkedList<>(); values.add(0L); // Initialise with 0 which is neutral element in terms of gcd, i.e. gcd(a,0) = a } long f(long a, long b) { // Can be replaced with other function return gcd(a, b); } public void push(long x) { stack.addLast(x); values.addLast(f(values.getLast(), x)); } public long top() { return values.getLast(); } public long pop() { long res = stack.getLast(); stack.removeLast(); values.removeLast(); return res; } public boolean isEmpty() { return stack.isEmpty(); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarray.java
src/main/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarray.java
package com.thealgorithms.slidingwindow; /** * The Sliding Window algorithm is used to find the maximum sum of a subarray * of a fixed size k within a given array. * * <p> * Worst-case performance O(n) * Best-case performance O(n) * Average performance O(n) * Worst-case space complexity O(1) * * @author Your Name (https://github.com/Chiefpatwal) */ public final class MaxSumKSizeSubarray { // Prevent instantiation private MaxSumKSizeSubarray() { } /** * This method finds the maximum sum of a subarray of a given size k. * * @param arr is the input array where the maximum sum needs to be found * @param k is the size of the subarray * @return the maximum sum of the subarray of size k */ public static int maxSumKSizeSubarray(int[] arr, int k) { if (arr.length < k) { return -1; // Edge case: not enough elements } int maxSum; int windowSum = 0; // Calculate the sum of the first window for (int i = 0; i < k; i++) { windowSum += arr[i]; } maxSum = windowSum; // Slide the window across the array for (int i = k; i < arr.length; i++) { windowSum += arr[i] - arr[i - k]; maxSum = Math.max(maxSum, windowSum); } return maxSum; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java
src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java
package com.thealgorithms.slidingwindow; import java.util.HashSet; /** * The Longest Substring Without Repeating Characters algorithm finds the length of * the longest substring without repeating characters in a given string. * * <p> * Worst-case performance O(n) * Best-case performance O(n) * Average performance O(n) * Worst-case space complexity O(min(n, m)), where n is the length of the string * and m is the size of the character set. * * @author (https://github.com/Chiefpatwal) */ public final class LongestSubstringWithoutRepeatingCharacters { // Prevent instantiation private LongestSubstringWithoutRepeatingCharacters() { } /** * This method finds the length of the longest substring without repeating characters. * * @param s is the input string * @return the length of the longest substring without repeating characters */ public static int lengthOfLongestSubstring(String s) { int maxLength = 0; int left = 0; HashSet<Character> charSet = new HashSet<>(); for (int right = 0; right < s.length(); right++) { // If the character is already in the set, remove characters from the left while (charSet.contains(s.charAt(right))) { charSet.remove(s.charAt(left)); left++; } charSet.add(s.charAt(right)); maxLength = Math.max(maxLength, right - left + 1); } return maxLength; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/slidingwindow/MinimumWindowSubstring.java
src/main/java/com/thealgorithms/slidingwindow/MinimumWindowSubstring.java
package com.thealgorithms.slidingwindow; import java.util.HashMap; /** * Finds the minimum window substring in 's' that contains all characters of 't'. * * Worst-case performance O(n) * Best-case performance O(n) * Average performance O(n) * Worst-case space complexity O(1) * * @author https://github.com/Chiefpatwal */ public final class MinimumWindowSubstring { // Prevent instantiation private MinimumWindowSubstring() { } /** * Finds the minimum window substring of 's' containing all characters of 't'. * * @param s The input string to search within. * @param t The string with required characters. * @return The minimum window substring, or empty string if not found. */ public static String minWindow(String s, String t) { if (s.length() < t.length()) { return ""; } HashMap<Character, Integer> tFreq = new HashMap<>(); for (char c : t.toCharArray()) { tFreq.put(c, tFreq.getOrDefault(c, 0) + 1); } HashMap<Character, Integer> windowFreq = new HashMap<>(); int left = 0; int right = 0; int minLen = Integer.MAX_VALUE; int count = 0; String result = ""; while (right < s.length()) { char c = s.charAt(right); windowFreq.put(c, windowFreq.getOrDefault(c, 0) + 1); if (tFreq.containsKey(c) && windowFreq.get(c).intValue() <= tFreq.get(c).intValue()) { count++; } while (count == t.length()) { if (right - left + 1 < minLen) { minLen = right - left + 1; result = s.substring(left, right + 1); } char leftChar = s.charAt(left); windowFreq.put(leftChar, windowFreq.get(leftChar) - 1); if (tFreq.containsKey(leftChar) && windowFreq.get(leftChar) < tFreq.get(leftChar)) { count--; } left++; } right++; } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java
src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java
package com.thealgorithms.slidingwindow; /** * The Sliding Window algorithm is used to find the minimum sum of a subarray * of a fixed size k within a given array. * * <p> * Worst-case performance O(n) * Best-case performance O(n) * Average performance O(n) * Worst-case space complexity O(1) * * This class provides a static method to find the minimum sum of a subarray * with a specified length k. * * @author Rashi Dashore (https://github.com/rashi07dashore) */ public final class MinSumKSizeSubarray { // Prevent instantiation private MinSumKSizeSubarray() { } /** * This method finds the minimum sum of a subarray of a given size k. * * @param arr is the input array where the minimum sum needs to be found * @param k is the size of the subarray * @return the minimum sum of the subarray of size k */ public static int minSumKSizeSubarray(int[] arr, int k) { if (arr.length < k) { return -1; // Edge case: not enough elements } int minSum; int windowSum = 0; // Calculate the sum of the first window for (int i = 0; i < k; i++) { windowSum += arr[i]; } minSum = windowSum; // Slide the window across the array for (int i = k; i < arr.length; i++) { windowSum += arr[i] - arr[i - k]; minSum = Math.min(minSum, windowSum); } return minSum; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToK.java
src/main/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToK.java
package com.thealgorithms.slidingwindow; /** * The Longest Subarray with Sum Less Than or Equal to k algorithm finds the length * of the longest subarray whose sum is less than or equal to a given value k. * * <p> * Worst-case performance O(n) * Best-case performance O(n) * Average performance O(n) * Worst-case space complexity O(1) * * @author https://github.com/Chiefpatwal */ public final class LongestSubarrayWithSumLessOrEqualToK { // Prevent instantiation private LongestSubarrayWithSumLessOrEqualToK() { } /** * This method finds the length of the longest subarray with a sum less than or equal to k. * * @param arr is the input array * @param k is the maximum sum allowed * @return the length of the longest subarray with sum less than or equal to k */ public static int longestSubarrayWithSumLEK(int[] arr, int k) { int maxLength = 0; // To store the maximum length found int currentSum = 0; // To store the current sum of the window int left = 0; // Left index of the sliding window for (int right = 0; right < arr.length; right++) { currentSum += arr[right]; // Expand the window to the right // Shrink the window from the left if the current sum exceeds k while (currentSum > k && left <= right) { currentSum -= arr[left]; // Remove the leftmost element left++; // Move the left index to the right } // Update maxLength if the current window is valid maxLength = Math.max(maxLength, right - left + 1); } return maxLength; // Return the maximum length found } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/divideandconquer/TilingProblem.java
src/main/java/com/thealgorithms/divideandconquer/TilingProblem.java
package com.thealgorithms.divideandconquer; /** * This class provides a solution to the Tiling Problem using divide-and-conquer. * <p> * The Tiling Problem involves filling a 2^n x 2^n board with a single missing * square using L-shaped tiles (each tile covers exactly three squares). * The algorithm recursively divides the board into four quadrants, places an * L-shaped tile in the appropriate quadrant, and fills the remaining areas. * * <p>Applications: * - Used in graphics and image processing. * - Helpful in solving puzzles and tiling problems in competitive programming. * * @author Hardvan */ public final class TilingProblem { private TilingProblem() { } /** * A counter used to label the L-shaped tiles placed on the board. */ private static int tile = 1; /** * A 2D array representing the board to be tiled. */ private static int[][] board; /** * Solves the tiling problem for a 2^n x 2^n board with one missing square. * * @param size The size of the board (must be a power of 2). * @param missingRow The row index of the missing square. * @param missingCol The column index of the missing square. * @return A 2D array representing the tiled board with L-shaped tiles. */ public static int[][] solveTiling(int size, int missingRow, int missingCol) { board = new int[size][size]; fillBoard(size, 0, 0, missingRow, missingCol); return board; } /** * Recursively fills the board with L-shaped tiles. * * <p>The board is divided into four quadrants. Depending on the location of * the missing square, an L-shaped tile is placed at the center of the board * to cover three of the four quadrants. The process is then repeated for * each quadrant until the entire board is filled. * * @param size The current size of the sub-board. * @param row The starting row index of the current sub-board. * @param col The starting column index of the current sub-board. * @param missingRow The row index of the missing square within the board. * @param missingCol The column index of the missing square within the board. */ private static void fillBoard(int size, int row, int col, int missingRow, int missingCol) { if (size == 1) { return; } int half = size / 2; int t = tile++; // Top-left quadrant if (missingRow < row + half && missingCol < col + half) { fillBoard(half, row, col, missingRow, missingCol); } else { board[row + half - 1][col + half - 1] = t; fillBoard(half, row, col, row + half - 1, col + half - 1); } // Top-right quadrant if (missingRow < row + half && missingCol >= col + half) { fillBoard(half, row, col + half, missingRow, missingCol); } else { board[row + half - 1][col + half] = t; fillBoard(half, row, col + half, row + half - 1, col + half); } // Bottom-left quadrant if (missingRow >= row + half && missingCol < col + half) { fillBoard(half, row + half, col, missingRow, missingCol); } else { board[row + half][col + half - 1] = t; fillBoard(half, row + half, col, row + half, col + half - 1); } // Bottom-right quadrant if (missingRow >= row + half && missingCol >= col + half) { fillBoard(half, row + half, col + half, missingRow, missingCol); } else { board[row + half][col + half] = t; fillBoard(half, row + half, col + half, row + half, col + half); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java
src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java
package com.thealgorithms.divideandconquer; // Java Program to Implement Strassen Algorithm for Matrix Multiplication /* * Uses the divide and conquer approach to multiply two matrices. * Time Complexity: O(n^2.8074) better than the O(n^3) of the standard matrix multiplication * algorithm. Space Complexity: O(n^2) * * This Matrix multiplication can be performed only on square matrices * where n is a power of 2. Order of both of the matrices are n × n. * * Reference: * https://www.tutorialspoint.com/design_and_analysis_of_algorithms/design_and_analysis_of_algorithms_strassens_matrix_multiplication.htm#:~:text=Strassen's%20Matrix%20multiplication%20can%20be,matrices%20are%20n%20%C3%97%20n. * https://www.geeksforgeeks.org/strassens-matrix-multiplication/ */ public class StrassenMatrixMultiplication { // Function to multiply matrices public int[][] multiply(int[][] a, int[][] b) { int n = a.length; int[][] mat = new int[n][n]; if (n == 1) { mat[0][0] = a[0][0] * b[0][0]; } else { // Dividing Matrix into parts // by storing sub-parts to variables int[][] a11 = new int[n / 2][n / 2]; int[][] a12 = new int[n / 2][n / 2]; int[][] a21 = new int[n / 2][n / 2]; int[][] a22 = new int[n / 2][n / 2]; int[][] b11 = new int[n / 2][n / 2]; int[][] b12 = new int[n / 2][n / 2]; int[][] b21 = new int[n / 2][n / 2]; int[][] b22 = new int[n / 2][n / 2]; // Dividing matrix A into 4 parts split(a, a11, 0, 0); split(a, a12, 0, n / 2); split(a, a21, n / 2, 0); split(a, a22, n / 2, n / 2); // Dividing matrix B into 4 parts split(b, b11, 0, 0); split(b, b12, 0, n / 2); split(b, b21, n / 2, 0); split(b, b22, n / 2, n / 2); // Using Formulas as described in algorithm // m1:=(A1+A3)×(B1+B2) int[][] m1 = multiply(add(a11, a22), add(b11, b22)); // m2:=(A2+A4)×(B3+B4) int[][] m2 = multiply(add(a21, a22), b11); // m3:=(A1−A4)×(B1+A4) int[][] m3 = multiply(a11, sub(b12, b22)); // m4:=A1×(B2−B4) int[][] m4 = multiply(a22, sub(b21, b11)); // m5:=(A3+A4)×(B1) int[][] m5 = multiply(add(a11, a12), b22); // m6:=(A1+A2)×(B4) int[][] m6 = multiply(sub(a21, a11), add(b11, b12)); // m7:=A4×(B3−B1) int[][] m7 = multiply(sub(a12, a22), add(b21, b22)); // P:=m2+m3−m6−m7 int[][] c11 = add(sub(add(m1, m4), m5), m7); // Q:=m4+m6 int[][] c12 = add(m3, m5); // mat:=m5+m7 int[][] c21 = add(m2, m4); // S:=m1−m3−m4−m5 int[][] c22 = add(sub(add(m1, m3), m2), m6); join(c11, mat, 0, 0); join(c12, mat, 0, n / 2); join(c21, mat, n / 2, 0); join(c22, mat, n / 2, n / 2); } return mat; } // Function to subtract two matrices public int[][] sub(int[][] a, int[][] b) { int n = a.length; int[][] c = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { c[i][j] = a[i][j] - b[i][j]; } } return c; } // Function to add two matrices public int[][] add(int[][] a, int[][] b) { int n = a.length; int[][] c = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { c[i][j] = a[i][j] + b[i][j]; } } return c; } // Function to split parent matrix into child matrices public void split(int[][] p, int[][] c, int iB, int jB) { for (int i1 = 0, i2 = iB; i1 < c.length; i1++, i2++) { for (int j1 = 0, j2 = jB; j1 < c.length; j1++, j2++) { c[i1][j1] = p[i2][j2]; } } } // Function to join child matrices into (to) parent matrix public void join(int[][] c, int[][] p, int iB, int jB) { for (int i1 = 0, i2 = iB; i1 < c.length; i1++, i2++) { for (int j1 = 0, j2 = jB; j1 < c.length; j1++, j2++) { p[i2][j2] = c[i1][j1]; } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/divideandconquer/CountingInversions.java
src/main/java/com/thealgorithms/divideandconquer/CountingInversions.java
package com.thealgorithms.divideandconquer; /** * A utility class for counting the number of inversions in an array. * <p> * An inversion is a pair (i, j) such that i < j and arr[i] > arr[j]. * This class implements a divide-and-conquer approach, similar to merge sort, * to count the number of inversions efficiently. * <p> * Time Complexity: O(n log n) * Space Complexity: O(n) (due to temporary arrays during merge step) * * <p>Applications: * - Used in algorithms related to sorting and permutation analysis. * - Helps in determining how far an array is from being sorted. * - Applicable in bioinformatics and signal processing. * * <p>This class cannot be instantiated, as it is intended to provide * only static utility methods. * * @author Hardvan */ public final class CountingInversions { private CountingInversions() { } /** * Counts the number of inversions in the given array. * * @param arr The input array of integers. * @return The total number of inversions in the array. */ public static int countInversions(int[] arr) { return mergeSortAndCount(arr, 0, arr.length - 1); } /** * Recursively divides the array into two halves, sorts them, and counts * the number of inversions. Uses a modified merge sort approach. * * @param arr The input array. * @param left The starting index of the current segment. * @param right The ending index of the current segment. * @return The number of inversions within the segment [left, right]. */ private static int mergeSortAndCount(int[] arr, int left, int right) { if (left >= right) { return 0; } int mid = left + (right - left) / 2; int inversions = 0; inversions += mergeSortAndCount(arr, left, mid); inversions += mergeSortAndCount(arr, mid + 1, right); inversions += mergeAndCount(arr, left, mid, right); return inversions; } /** * Merges two sorted subarrays and counts the cross-inversions between them. * A cross-inversion occurs when an element from the right subarray is * smaller than an element from the left subarray. * * @param arr The input array. * @param left The starting index of the first subarray. * @param mid The ending index of the first subarray and midpoint of the segment. * @param right The ending index of the second subarray. * @return The number of cross-inversions between the two subarrays. */ private static int mergeAndCount(int[] arr, int left, int mid, int right) { int[] leftArr = new int[mid - left + 1]; int[] rightArr = new int[right - mid]; System.arraycopy(arr, left, leftArr, 0, mid - left + 1); System.arraycopy(arr, mid + 1, rightArr, 0, right - mid); int i = 0; int j = 0; int k = left; int inversions = 0; while (i < leftArr.length && j < rightArr.length) { if (leftArr[i] <= rightArr[j]) { arr[k++] = leftArr[i++]; } else { arr[k++] = rightArr[j++]; inversions += mid + 1 - left - i; } } while (i < leftArr.length) { arr[k++] = leftArr[i++]; } while (j < rightArr.length) { arr[k++] = rightArr[j++]; } return inversions; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/divideandconquer/MedianOfTwoSortedArrays.java
src/main/java/com/thealgorithms/divideandconquer/MedianOfTwoSortedArrays.java
package com.thealgorithms.divideandconquer; public final class MedianOfTwoSortedArrays { private MedianOfTwoSortedArrays() { } /** * Finds the median of two sorted arrays in logarithmic time. * * @param nums1 the first sorted array * @param nums2 the second sorted array * @return the median of the combined sorted array * @throws IllegalArgumentException if the input arrays are not sorted */ public static double findMedianSortedArrays(int[] nums1, int[] nums2) { if (nums1.length > nums2.length) { return findMedianSortedArrays(nums2, nums1); // Ensure nums1 is the smaller array } int m = nums1.length; int n = nums2.length; int low = 0; int high = m; while (low <= high) { int partition1 = (low + high) / 2; // Partition in the first array int partition2 = (m + n + 1) / 2 - partition1; // Partition in the second array int maxLeft1 = (partition1 == 0) ? Integer.MIN_VALUE : nums1[partition1 - 1]; int minRight1 = (partition1 == m) ? Integer.MAX_VALUE : nums1[partition1]; int maxLeft2 = (partition2 == 0) ? Integer.MIN_VALUE : nums2[partition2 - 1]; int minRight2 = (partition2 == n) ? Integer.MAX_VALUE : nums2[partition2]; // Check if partition is valid if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) { // If combined array length is odd if (((m + n) & 1) == 1) { return Math.max(maxLeft1, maxLeft2); } // If combined array length is even else { return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2.0; } } else if (maxLeft1 > minRight2) { high = partition1 - 1; } else { low = partition1 + 1; } } throw new IllegalArgumentException("Input arrays are not sorted"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java
src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java
package com.thealgorithms.divideandconquer; // Java Program to Implement Binary Exponentiation (power in log n) // Reference Link: https://en.wikipedia.org/wiki/Exponentiation_by_squaring /* * Binary Exponentiation is a method to calculate a to the power of b. * It is used to calculate a^n in O(log n) time. * * Reference: * https://iq.opengenus.org/binary-exponentiation/ */ public class BinaryExponentiation { // recursive function to calculate a to the power of b public static long calculatePower(long x, long y) { // Base Case if (y == 0) { return 1; } if (y % 2 == 1) { // odd power return x * calculatePower(x, y - 1); } return calculatePower(x * x, y / 2); // even power } // iterative function to calculate a to the power of b long power(long n, long m) { long power = n; long sum = 1; while (m > 0) { if ((m & 1) == 1) { sum *= power; } power = power * power; m = m >> 1; } return sum; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java
src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java
package com.thealgorithms.divideandconquer; import java.util.ArrayList; import java.util.Comparator; /** * @author dimgrichr * <p> * Space complexity: O(n) Time complexity: O(nlogn), because it is a divide and * conquer algorithm */ public class SkylineAlgorithm { private ArrayList<Point> points; /** * Main constructor of the application. ArrayList points gets created, which * represents the sum of all edges. */ public SkylineAlgorithm() { points = new ArrayList<>(); } /** * @return points, the ArrayList that includes all points. */ public ArrayList<Point> getPoints() { return points; } /** * The main divide and conquer, and also recursive algorithm. It gets an * ArrayList full of points as an argument. If the size of that ArrayList is * 1 or 2, the ArrayList is returned as it is, or with one less point (if * the initial size is 2 and one of it's points, is dominated by the other * one). On the other hand, if the ArrayList's size is bigger than 2, the * function is called again, twice, with arguments the corresponding half of * the initial ArrayList each time. Once the flashback has ended, the * function produceFinalSkyLine gets called, in order to produce the final * skyline, and return it. * * @param list, the initial list of points * @return leftSkyLine, the combination of first half's and second half's * skyline * @see Point */ public ArrayList<Point> produceSubSkyLines(ArrayList<Point> list) { // part where function exits flashback int size = list.size(); if (size == 1) { return list; } else if (size == 2) { if (list.get(0).dominates(list.get(1))) { list.remove(1); } else { if (list.get(1).dominates(list.get(0))) { list.remove(0); } } return list; } // recursive part of the function ArrayList<Point> leftHalf = new ArrayList<>(); ArrayList<Point> rightHalf = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { if (i < list.size() / 2) { leftHalf.add(list.get(i)); } else { rightHalf.add(list.get(i)); } } ArrayList<Point> leftSubSkyLine = produceSubSkyLines(leftHalf); ArrayList<Point> rightSubSkyLine = produceSubSkyLines(rightHalf); // skyline is produced return produceFinalSkyLine(leftSubSkyLine, rightSubSkyLine); } /** * The first half's skyline gets cleared from some points that are not part * of the final skyline (Points with same x-value and different y=values. * The point with the smallest y-value is kept). Then, the minimum y-value * of the points of first half's skyline is found. That helps us to clear * the second half's skyline, because, the points of second half's skyline * that have greater y-value of the minimum y-value that we found before, * are dominated, so they are not part of the final skyline. Finally, the * "cleaned" first half's and second half's skylines, are combined, * producing the final skyline, which is returned. * * @param left the skyline of the left part of points * @param right the skyline of the right part of points * @return left the final skyline */ public ArrayList<Point> produceFinalSkyLine(ArrayList<Point> left, ArrayList<Point> right) { // dominated points of ArrayList left are removed for (int i = 0; i < left.size() - 1; i++) { if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) { left.remove(i); i--; } } // minimum y-value is found int min = left.get(0).y; for (int i = 1; i < left.size(); i++) { if (min > left.get(i).y) { min = left.get(i).y; if (min == 1) { i = left.size(); } } } // dominated points of ArrayList right are removed for (int i = 0; i < right.size(); i++) { if (right.get(i).y >= min) { right.remove(i); i--; } } // final skyline found and returned left.addAll(right); return left; } public static class Point { private int x; private int y; /** * The main constructor of Point Class, used to represent the 2 * Dimension points. * * @param x the point's x-value. * @param y the point's y-value. */ public Point(int x, int y) { this.x = x; this.y = y; } /** * @return x, the x-value */ public int getX() { return x; } /** * @return y, the y-value */ public int getY() { return y; } /** * Based on the skyline theory, it checks if the point that calls the * function dominates the argument point. * * @param p1 the point that is compared * @return true if the point which calls the function dominates p1 false * otherwise. */ public boolean dominates(Point p1) { // checks if p1 is dominated return ((this.x < p1.x && this.y <= p1.y) || (this.x <= p1.x && this.y < p1.y)); } } /** * It is used to compare the 2 Dimension points, based on their x-values, in * order get sorted later. */ class XComparator implements Comparator<Point> { @Override public int compare(Point a, Point b) { return Integer.compare(a.x, b.x); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java
src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java
package com.thealgorithms.divideandconquer; /** * For a set of points in a coordinates system (10000 maximum), ClosestPair * class calculates the two closest points. */ public final class ClosestPair { /** * Number of points */ int numberPoints; /** * Input data, maximum 10000. */ Location[] array; /** * Minimum point coordinate. */ Location point1 = null; /** * Minimum point coordinate. */ Location point2 = null; /** * Minimum point length. */ private static double minNum = Double.MAX_VALUE; public static void setMinNum(double minNum) { ClosestPair.minNum = minNum; } public static void setSecondCount(int secondCount) { ClosestPair.secondCount = secondCount; } /** * secondCount */ private static int secondCount = 0; /** * Constructor. */ ClosestPair(int points) { numberPoints = points; array = new Location[numberPoints]; } /** * Location class is an auxiliary type to keep points coordinates. */ public static class Location { double x; double y; /** * @param xpar (IN Parameter) x coordinate <br> * @param ypar (IN Parameter) y coordinate <br> */ Location(final double xpar, final double ypar) { // Save x, y coordinates this.x = xpar; this.y = ypar; } } public Location[] createLocation(int numberValues) { return new Location[numberValues]; } public Location buildLocation(double x, double y) { return new Location(x, y); } /** * xPartition function: arrange x-axis. * * @param a (IN Parameter) array of points <br> * @param first (IN Parameter) first point <br> * @param last (IN Parameter) last point <br> * @return pivot index */ public int xPartition(final Location[] a, final int first, final int last) { Location pivot = a[last]; // pivot int i = first - 1; Location temp; // Temporarily store value for position transformation for (int j = first; j <= last - 1; j++) { if (a[j].x <= pivot.x) { // Less than or less than pivot i++; temp = a[i]; // array[i] <-> array[j] a[i] = a[j]; a[j] = temp; } } i++; temp = a[i]; // array[pivot] <-> array[i] a[i] = a[last]; a[last] = temp; return i; // pivot index } /** * yPartition function: arrange y-axis. * * @param a (IN Parameter) array of points <br> * @param first (IN Parameter) first point <br> * @param last (IN Parameter) last point <br> * @return pivot index */ public int yPartition(final Location[] a, final int first, final int last) { Location pivot = a[last]; // pivot int i = first - 1; Location temp; // Temporarily store value for position transformation for (int j = first; j <= last - 1; j++) { if (a[j].y <= pivot.y) { // Less than or less than pivot i++; temp = a[i]; // array[i] <-> array[j] a[i] = a[j]; a[j] = temp; } } i++; temp = a[i]; // array[pivot] <-> array[i] a[i] = a[last]; a[last] = temp; return i; // pivot index } /** * xQuickSort function: //x-axis Quick Sorting. * * @param a (IN Parameter) array of points <br> * @param first (IN Parameter) first point <br> * @param last (IN Parameter) last point <br> */ public void xQuickSort(final Location[] a, final int first, final int last) { if (first < last) { int q = xPartition(a, first, last); // pivot xQuickSort(a, first, q - 1); // Left xQuickSort(a, q + 1, last); // Right } } /** * yQuickSort function: //y-axis Quick Sorting. * * @param a (IN Parameter) array of points <br> * @param first (IN Parameter) first point <br> * @param last (IN Parameter) last point <br> */ public void yQuickSort(final Location[] a, final int first, final int last) { if (first < last) { int q = yPartition(a, first, last); // pivot yQuickSort(a, first, q - 1); // Left yQuickSort(a, q + 1, last); // Right } } /** * closestPair function: find closest pair. * * @param a (IN Parameter) array stored before divide <br> * @param indexNum (IN Parameter) number coordinates divideArray <br> * @return minimum distance <br> */ public double closestPair(final Location[] a, final int indexNum) { Location[] divideArray = new Location[indexNum]; System.arraycopy(a, 0, divideArray, 0, indexNum); // Copy previous array int divideX = indexNum / 2; // Intermediate value for divide Location[] leftArray = new Location[divideX]; // divide - left array // divide-right array Location[] rightArray = new Location[indexNum - divideX]; if (indexNum <= 3) { // If the number of coordinates is 3 or less return bruteForce(divideArray); } // divide-left array System.arraycopy(divideArray, 0, leftArray, 0, divideX); // divide-right array System.arraycopy(divideArray, divideX, rightArray, 0, indexNum - divideX); double minLeftArea; // Minimum length of left array double minRightArea; // Minimum length of right array double minValue; // Minimum length minLeftArea = closestPair(leftArray, divideX); // recursive closestPair minRightArea = closestPair(rightArray, indexNum - divideX); // window size (= minimum length) minValue = Math.min(minLeftArea, minRightArea); // Create window. Set the size for creating a window // and creating a new array for the coordinates in the window for (int i = 0; i < indexNum; i++) { double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); if (xGap < minValue) { ClosestPair.setSecondCount(secondCount + 1); // size of the array } else { if (divideArray[i].x > divideArray[divideX].x) { break; } } } // new array for coordinates in window Location[] firstWindow = new Location[secondCount]; int k = 0; for (int i = 0; i < indexNum; i++) { double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); if (xGap < minValue) { // if it's inside a window firstWindow[k] = divideArray[i]; // put in an array k++; } else { if (divideArray[i].x > divideArray[divideX].x) { break; } } } yQuickSort(firstWindow, 0, secondCount - 1); // Sort by y coordinates /* Coordinates in Window */ double length; // size comparison within window for (int i = 0; i < secondCount - 1; i++) { for (int j = (i + 1); j < secondCount; j++) { double xGap = Math.abs(firstWindow[i].x - firstWindow[j].x); double yGap = Math.abs(firstWindow[i].y - firstWindow[j].y); if (yGap < minValue) { length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); // If measured distance is less than current min distance if (length < minValue) { // Change minimum distance to current distance minValue = length; // Conditional for registering final coordinate if (length < minNum) { ClosestPair.setMinNum(length); point1 = firstWindow[i]; point2 = firstWindow[j]; } } } else { break; } } } ClosestPair.setSecondCount(0); return minValue; } /** * bruteForce function: When the number of coordinates is less than 3. * * @param arrayParam (IN Parameter) array stored before divide <br> * @return <br> */ public double bruteForce(final Location[] arrayParam) { double minValue = Double.MAX_VALUE; // minimum distance double length; double xGap; // Difference between x coordinates double yGap; // Difference between y coordinates double result = 0; if (arrayParam.length == 2) { // Difference between x coordinates xGap = (arrayParam[0].x - arrayParam[1].x); // Difference between y coordinates yGap = (arrayParam[0].y - arrayParam[1].y); // distance between coordinates length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); // Conditional statement for registering final coordinate if (length < minNum) { ClosestPair.setMinNum(length); } point1 = arrayParam[0]; point2 = arrayParam[1]; result = length; } if (arrayParam.length == 3) { for (int i = 0; i < arrayParam.length - 1; i++) { for (int j = (i + 1); j < arrayParam.length; j++) { // Difference between x coordinates xGap = (arrayParam[i].x - arrayParam[j].x); // Difference between y coordinates yGap = (arrayParam[i].y - arrayParam[j].y); // distance between coordinates length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); // If measured distance is less than current min distance if (length < minValue) { // Change minimum distance to current distance minValue = length; if (length < minNum) { // Registering final coordinate ClosestPair.setMinNum(length); point1 = arrayParam[i]; point2 = arrayParam[j]; } } } } result = minValue; } return result; // If only one point returns 0. } /** * main function: execute class. * * @param args (IN Parameter) <br> */ public static void main(final String[] args) { // Input data consists of one x-coordinate and one y-coordinate ClosestPair cp = new ClosestPair(12); cp.array[0] = cp.buildLocation(2, 3); cp.array[1] = cp.buildLocation(2, 16); cp.array[2] = cp.buildLocation(3, 9); cp.array[3] = cp.buildLocation(6, 3); cp.array[4] = cp.buildLocation(7, 7); cp.array[5] = cp.buildLocation(19, 4); cp.array[6] = cp.buildLocation(10, 11); cp.array[7] = cp.buildLocation(15, 2); cp.array[8] = cp.buildLocation(15, 19); cp.array[9] = cp.buildLocation(16, 11); cp.array[10] = cp.buildLocation(17, 13); cp.array[11] = cp.buildLocation(9, 12); System.out.println("Input data"); System.out.println("Number of points: " + cp.array.length); for (int i = 0; i < cp.array.length; i++) { System.out.println("x: " + cp.array[i].x + ", y: " + cp.array[i].y); } cp.xQuickSort(cp.array, 0, cp.array.length - 1); // Sorting by x value double result; // minimum distance result = cp.closestPair(cp.array, cp.array.length); // ClosestPair start // minimum distance coordinates and distance output System.out.println("Output Data"); System.out.println("(" + cp.point1.x + ", " + cp.point1.y + ")"); System.out.println("(" + cp.point2.x + ", " + cp.point2.y + ")"); System.out.println("Minimum Distance : " + result); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
kdn251/interviews
https://github.com/kdn251/interviews/blob/03fdcb2703ce72dc0606748733d0c13f09d41d21/cracking-the-coding-interview/chapter-four-trees-and-graphs/IsSubtree.java
cracking-the-coding-interview/chapter-four-trees-and-graphs/IsSubtree.java
/* you have two very large binary trees: T1, with millions of nodes, and T2, with hundreds * of nodes. Create an algorithm to decide if T2 is a subtree of T1. * A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n * is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical */ public class IsSubtree { boolean containsTree(TreeNode t1, TreeNode t2) { if(t2 == null) { //the empty tree is always a subtree return true; } return subTree(t1, t2); } boolean subTree(TreeNode r1, TreeNode r2) { if(r1 == null) { return false; //big tree empty & subtree still not found } if(r1.data == r2.data) { if(matchTree(r1, r2)) return true; } return (subTree(r1.left, r2) || subTree(r1.right, r2)); } boolean matchTree(TreeNode r1, TreeNode r2) { if(r2 == null && r1 == null) //if both are empty return true; //nothing left in the subtree //if one, but not both, are empty if(r1 == null || r2 == null) { return false; } if(r1.data != r2.data) return false; //data doesn't match return (matchTree(r1.left, r2.left) && matchTree(r1.right, r2.right)); } }
java
MIT
03fdcb2703ce72dc0606748733d0c13f09d41d21
2026-01-04T14:45:56.686758Z
false