linkedListValues = new Stack<>();
20 |
21 | for (final var x : linkedList) {
22 | linkedListValues.push(x);
23 | }
24 |
25 | for (final var x : linkedList) {
26 | if (x != linkedListValues.pop()) {
27 | return false;
28 | }
29 | }
30 |
31 | return true;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | /*
4 | * A left rotation operation on an array
5 | * shifts each of the array's elements
6 | * given integer n unit to the left.
7 | *
8 | * @author sangin-lee
9 | */
10 |
11 | public final class ArrayLeftRotation {
12 | private ArrayLeftRotation() {
13 | }
14 |
15 | /*
16 | * Returns the result of left rotation of given array arr and integer n
17 | *
18 | * @param arr : int[] given array
19 | *
20 | * @param n : int given integer
21 | *
22 | * @return : int[] result of left rotation
23 | */
24 | public static int[] rotateLeft(int[] arr, int n) {
25 | int size = arr.length;
26 | int[] dst = new int[size];
27 | n = n % size;
28 | for (int i = 0; i < size; i++) {
29 | dst[i] = arr[n];
30 | n = (n + 1) % size;
31 | }
32 | return dst;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/others/CRC16.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | /**
4 | * Generates a crc16 checksum for a given string
5 | */
6 | public final class CRC16 {
7 | private CRC16() {
8 | }
9 |
10 | public static void main(String[] args) {
11 | System.out.println(crc16("Hello World!"));
12 | }
13 |
14 | public static String crc16(String message) {
15 | int crc = 0xFFFF; // initial value
16 | int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
17 | byte[] bytes = message.getBytes();
18 |
19 | for (byte b : bytes) {
20 | for (int i = 0; i < 8; i++) {
21 | boolean bit = ((b >> (7 - i) & 1) == 1);
22 | boolean c15 = ((crc >> 15 & 1) == 1);
23 | crc <<= 1;
24 | if (c15 ^ bit) {
25 | crc ^= polynomial;
26 | }
27 | }
28 | }
29 | crc &= 0xffff;
30 | return Integer.toHexString(crc).toUpperCase();
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/others/CRC32.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.BitSet;
4 |
5 | /**
6 | * Generates a crc32 checksum for a given string or byte array
7 | */
8 | public final class CRC32 {
9 | private CRC32() {
10 | }
11 |
12 | public static void main(String[] args) {
13 | System.out.println(Integer.toHexString(crc32("Hello World")));
14 | }
15 |
16 | public static int crc32(String str) {
17 | return crc32(str.getBytes());
18 | }
19 |
20 | public static int crc32(byte[] data) {
21 | BitSet bitSet = BitSet.valueOf(data);
22 | int crc32 = 0xFFFFFFFF; // initial value
23 | for (int i = 0; i < data.length * 8; i++) {
24 | if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) {
25 | crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial
26 | } else {
27 | crc32 = (crc32 << 1);
28 | }
29 | }
30 | crc32 = Integer.reverse(crc32); // result reflect
31 | return crc32 ^ 0xFFFFFFFF; // final xor value
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/others/CountChar.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | public final class CountChar {
4 | private CountChar() {
5 | }
6 |
7 | /**
8 | * Count non space character in string
9 | *
10 | * @param str String to count the characters
11 | * @return number of character in the specified string
12 | */
13 |
14 | public static int countCharacters(String str) {
15 | return str.replaceAll("\\s", "").length();
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/others/FibbonaciSeries.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Fibonacci sequence, and characterized by the fact that every number after the
7 | * first two is the sum of the two preceding ones.
8 | *
9 | *
10 | * Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,...
11 | *
12 | *
13 | * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number
14 | *
15 | * Problem Statement: print all Fibonacci numbers that are smaller than your
16 | * given input N
17 | */
18 | public final class FibbonaciSeries {
19 | private FibbonaciSeries() {
20 | }
21 |
22 | public static void main(String[] args) {
23 | // Get input from the user
24 | Scanner scan = new Scanner(System.in);
25 | int n = scan.nextInt();
26 | int first = 0;
27 | int second = 1;
28 | scan.close();
29 | while (first <= n) {
30 | // print first fibo 0 then add second fibo into it while updating second as well
31 | System.out.println(first);
32 | int next = first + second;
33 | first = second;
34 | second = next;
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/others/FloydTriangle.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Scanner;
4 |
5 | final class FloydTriangle {
6 | private FloydTriangle() {
7 | }
8 |
9 | public static void main(String[] args) {
10 | Scanner sc = new Scanner(System.in);
11 | System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
12 | int r = sc.nextInt();
13 | int n = 0;
14 | sc.close();
15 | for (int i = 0; i < r; i++) {
16 | for (int j = 0; j <= i; j++) {
17 | System.out.print(++n + " ");
18 | }
19 | System.out.println();
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashSet;
5 | import java.util.Scanner;
6 | import java.util.Set;
7 |
8 | public final class HappyNumbersSeq {
9 | private HappyNumbersSeq() {
10 | }
11 |
12 | private static final Set CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145));
13 |
14 | public static void main(String[] args) {
15 | Scanner in = new Scanner(System.in);
16 | System.out.print("Enter number: ");
17 | int n = in.nextInt();
18 | while (n != 1 && !isSad(n)) {
19 | System.out.print(n + " ");
20 | n = sumSquares(n);
21 | }
22 | String res = n == 1 ? "1 Happy number" : "Sad number";
23 | System.out.println(res);
24 | in.close();
25 | }
26 |
27 | private static int sumSquares(int n) {
28 | int s = 0;
29 | for (; n > 0; n /= 10) {
30 | int r = n % 10;
31 | s += r * r;
32 | }
33 | return s;
34 | }
35 |
36 | private static boolean isSad(int n) {
37 | return CYCLE_NUMS.contains(n);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/others/Krishnamurthy.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Scanner;
4 |
5 | final class Krishnamurthy {
6 | private Krishnamurthy() {
7 | }
8 |
9 | static int fact(int n) {
10 | int i;
11 | int p = 1;
12 | for (i = n; i >= 1; i--) {
13 | p = p * i;
14 | }
15 | return p;
16 | }
17 |
18 | public static void main(String[] args) {
19 | Scanner sc = new Scanner(System.in);
20 | int a;
21 | int b;
22 | int s = 0;
23 | System.out.print("Enter the number : ");
24 | a = sc.nextInt();
25 | int n = a;
26 | while (a > 0) {
27 | b = a % 10;
28 | s = s + fact(b);
29 | a = a / 10;
30 | }
31 | if (s == n) {
32 | System.out.print(n + " is a krishnamurthy number");
33 | } else {
34 | System.out.print(n + " is not a krishnamurthy number");
35 | }
36 | sc.close();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/others/RootPrecision.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Scanner;
4 |
5 | public final class RootPrecision {
6 | private RootPrecision() {
7 | }
8 |
9 | public static void main(String[] args) {
10 | // take input
11 | Scanner scn = new Scanner(System.in);
12 |
13 | // n is the input number
14 | int n = scn.nextInt();
15 |
16 | // p is precision value for eg - p is 3 in 2.564 and 5 in 3.80870.
17 | int p = scn.nextInt();
18 | System.out.println(squareRoot(n, p));
19 |
20 | scn.close();
21 | }
22 |
23 | public static double squareRoot(int n, int p) {
24 | // rv means return value
25 | double rv;
26 |
27 | double root = Math.pow(n, 0.5);
28 |
29 | // calculate precision to power of 10 and then multiply it with root value.
30 | int precision = (int) Math.pow(10, p);
31 | root = root * precision;
32 | /*typecast it into integer then divide by precision and again typecast into double
33 | so as to have decimal points upto p precision */
34 |
35 | rv = (int) root;
36 | return rv / precision;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/others/cn/HammingDistance.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others.cn;
2 |
3 | public final class HammingDistance {
4 | private HammingDistance() {
5 | }
6 |
7 | private static void checkChar(char inChar) {
8 | if (inChar != '0' && inChar != '1') {
9 | throw new IllegalArgumentException("Input must be a binary string.");
10 | }
11 | }
12 |
13 | public static int compute(char charA, char charB) {
14 | checkChar(charA);
15 | checkChar(charB);
16 | return charA == charB ? 0 : 1;
17 | }
18 |
19 | public static int compute(String bitsStrA, String bitsStrB) {
20 | if (bitsStrA.length() != bitsStrB.length()) {
21 | throw new IllegalArgumentException("Input strings must have the same length.");
22 | }
23 |
24 | int totalErrorBitCount = 0;
25 |
26 | for (int i = 0; i < bitsStrA.length(); i++) {
27 | totalErrorBitCount += compute(bitsStrA.charAt(i), bitsStrB.charAt(i));
28 | }
29 |
30 | return totalErrorBitCount;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 |
3 | import com.thealgorithms.datastructures.Node;
4 | import java.util.ArrayList;
5 | import java.util.List;
6 | import java.util.Optional;
7 |
8 | /**
9 | * @author: caos321
10 | * @date: 31 October 2021 (Sunday)
11 | * @wiki: https://en.wikipedia.org/wiki/Depth-first_search
12 | */
13 | public class DepthFirstSearch {
14 |
15 | private final List visited = new ArrayList<>();
16 |
17 | public Optional> recursiveSearch(final Node node, final Integer value) {
18 | if (node == null) {
19 | return Optional.empty();
20 | }
21 | visited.add(node.getValue());
22 | if (node.getValue().equals(value)) {
23 | return Optional.of(node);
24 | }
25 |
26 | return node.getChildren().stream().map(v -> recursiveSearch(v, value)).flatMap(Optional::stream).findAny();
27 | }
28 |
29 | public List getVisited() {
30 | return visited;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 |
3 | public class SearchInARowAndColWiseSortedMatrix {
4 | /**
5 | * Search a key in row and column wise sorted matrix
6 | *
7 | * @param matrix matrix to be searched
8 | * @param value Key being searched for
9 | * @author Sadiul Hakim : https://github.com/sadiul-hakim
10 | */
11 |
12 | public int[] search(int[][] matrix, int value) {
13 | int n = matrix.length;
14 | // This variable iterates over rows
15 | int i = 0;
16 | // This variable iterates over columns
17 | int j = n - 1;
18 | int[] result = {-1, -1};
19 |
20 | while (i < n && j >= 0) {
21 | if (matrix[i][j] == value) {
22 | result[0] = i;
23 | result[1] = j;
24 | return result;
25 | }
26 | if (value > matrix[i][j]) {
27 | i++;
28 | } else {
29 | j--;
30 | }
31 | }
32 | return result;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 | public final class SortOrderAgnosticBinarySearch {
3 | private SortOrderAgnosticBinarySearch() {
4 | }
5 | public static int find(int[] arr, int key) {
6 | int start = 0;
7 | int end = arr.length - 1;
8 | boolean arrDescending = arr[start] > arr[end]; // checking for Array is in ascending order or descending order.
9 | while (start <= end) {
10 | int mid = end - start / 2;
11 | if (arr[mid] == key) {
12 | return mid;
13 | }
14 | if (arrDescending) { // boolean is true then our array is in descending order
15 | if (key < arr[mid]) {
16 | start = mid + 1;
17 | } else {
18 | end = mid - 1;
19 | }
20 | } else { // otherwise our array is in ascending order
21 | if (key > arr[mid]) {
22 | start = mid + 1;
23 | } else {
24 | end = mid - 1;
25 | }
26 | }
27 | }
28 | return -1;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/sorts/BubbleSort.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | /**
4 | * @author Varun Upadhyay (https://github.com/varunu28)
5 | * @author Podshivalov Nikita (https://github.com/nikitap492)
6 | * @see SortAlgorithm
7 | */
8 | class BubbleSort implements SortAlgorithm {
9 |
10 | /**
11 | * Implements generic bubble sort algorithm.
12 | *
13 | * @param array the array to be sorted.
14 | * @param the type of elements in the array.
15 | * @return the sorted array.
16 | */
17 | @Override
18 | public > T[] sort(T[] array) {
19 | for (int i = 1, size = array.length; i < size; ++i) {
20 | boolean swapped = false;
21 | for (int j = 0; j < size - i; ++j) {
22 | if (SortUtils.greater(array[j], array[j + 1])) {
23 | SortUtils.swap(array, j, j + 1);
24 | swapped = true;
25 | }
26 | }
27 | if (!swapped) {
28 | break;
29 | }
30 | }
31 | return array;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/sorts/BubbleSortRecursive.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | /**
4 | * BubbleSort algorithm implemented using recursion
5 | */
6 | public class BubbleSortRecursive implements SortAlgorithm {
7 | /**
8 | * @param array - an array should be sorted
9 | * @return sorted array
10 | */
11 | @Override
12 | public > T[] sort(T[] array) {
13 | bubbleSort(array, array.length);
14 | return array;
15 | }
16 |
17 | /**
18 | * BubbleSort algorithm implements using recursion
19 | *
20 | * @param array array contains elements
21 | * @param len length of given array
22 | */
23 | private static > void bubbleSort(T[] array, int len) {
24 | boolean swapped = false;
25 | for (int i = 0; i < len - 1; ++i) {
26 | if (SortUtils.greater(array[i], array[i + 1])) {
27 | SortUtils.swap(array, i, i + 1);
28 | swapped = true;
29 | }
30 | }
31 | if (swapped) {
32 | bubbleSort(array, len - 1);
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/sorts/SelectionSort.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | public class SelectionSort implements SortAlgorithm {
4 | /**
5 | * Sorts an array of comparable elements in increasing order using the selection sort algorithm.
6 | *
7 | * @param array the array to be sorted
8 | * @param the class of array elements
9 | * @return the sorted array
10 | */
11 | @Override
12 | public > T[] sort(T[] array) {
13 | // One by one move the boundary of the unsorted subarray
14 | for (int i = 0; i < array.length - 1; i++) {
15 |
16 | // Swap the remaining minimum element with the current element
17 | SortUtils.swap(array, i, findIndexOfMin(array, i));
18 | }
19 | return array;
20 | }
21 |
22 | private static > int findIndexOfMin(T[] array, final int start) {
23 | int minIndex = start;
24 | for (int i = start + 1; i < array.length; i++) {
25 | if (array[i].compareTo(array[minIndex]) < 0) {
26 | minIndex = i;
27 | }
28 | }
29 | return minIndex;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/sorts/SlowSort.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | /**
4 | * @author Amir Hassan (https://github.com/ahsNT)
5 | * @see SortAlgorithm
6 | */
7 | public class SlowSort implements SortAlgorithm {
8 |
9 | @Override
10 | public > T[] sort(T[] unsortedArray) {
11 | sort(unsortedArray, 0, unsortedArray.length - 1);
12 | return unsortedArray;
13 | }
14 |
15 | private > void sort(T[] array, int i, int j) {
16 | if (SortUtils.greaterOrEqual(i, j)) {
17 | return;
18 | }
19 | final int m = (i + j) >>> 1;
20 | sort(array, i, m);
21 | sort(array, m + 1, j);
22 | if (SortUtils.less(array[j], array[m])) {
23 | SortUtils.swap(array, j, m);
24 | }
25 | sort(array, i, j - 1);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | /**
7 | * The common interface of most sorting algorithms
8 | *
9 | * @author Podshivalov Nikita (https://github.com/nikitap492)
10 | */
11 | public interface SortAlgorithm {
12 | /**
13 | * Main method arrays sorting algorithms
14 | *
15 | * @param unsorted - an array should be sorted
16 | * @return a sorted array
17 | */
18 | > T[] sort(T[] unsorted);
19 |
20 | /**
21 | * Auxiliary method for algorithms what wanted to work with lists from JCF
22 | *
23 | * @param unsorted - a list should be sorted
24 | * @return a sorted list
25 | */
26 | @SuppressWarnings("unchecked")
27 | default> List sort(List unsorted) {
28 | return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()])));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/strings/CharactersSame.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | public final class CharactersSame {
4 | private CharactersSame() {
5 | }
6 |
7 | /**
8 | * Driver Code
9 | */
10 | public static void main(String[] args) {
11 | assert isAllCharactersSame("");
12 | assert !isAllCharactersSame("aab");
13 | assert isAllCharactersSame("aaa");
14 | assert isAllCharactersSame("11111");
15 | }
16 |
17 | /**
18 | * check if all the characters of a string are same
19 | *
20 | * @param s the string to check
21 | * @return {@code true} if all characters of a string are same, otherwise
22 | * {@code false}
23 | */
24 | public static boolean isAllCharactersSame(String s) {
25 | for (int i = 1, length = s.length(); i < length; ++i) {
26 | if (s.charAt(i) != s.charAt(0)) {
27 | return false;
28 | }
29 | }
30 | return true;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/strings/CheckVowels.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 |
7 | /**
8 | * Vowel Count is a system whereby character strings are placed in order based
9 | * on the position of the characters in the conventional ordering of an
10 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
11 | */
12 | public final class CheckVowels {
13 | private CheckVowels() {
14 | }
15 |
16 | private static final Set VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
17 |
18 | /**
19 | * Check if a string is has vowels or not
20 | *
21 | * @param input a string
22 | * @return {@code true} if given string has vowels, otherwise {@code false}
23 | */
24 | public static boolean hasVowels(String input) {
25 | if (input == null) {
26 | return false;
27 | }
28 | input = input.toLowerCase();
29 | for (int i = 0; i < input.length(); i++) {
30 | if (VOWELS.contains(input.charAt(i))) {
31 | return true;
32 | }
33 | }
34 | return false;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/strings/HammingDistance.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | /* In information theory, the Hamming distance between two strings of equal length
4 | is the number of positions at which the corresponding symbols are different.
5 | https://en.wikipedia.org/wiki/Hamming_distance
6 | */
7 | public final class HammingDistance {
8 | private HammingDistance() {
9 | }
10 |
11 | /**
12 | * calculate the hamming distance between two strings of equal length
13 | *
14 | * @param s1 the first string
15 | * @param s2 the second string
16 | * @return {@code int} hamming distance
17 | * @throws Exception
18 | */
19 | public static int calculateHammingDistance(String s1, String s2) throws Exception {
20 | if (s1.length() != s2.length()) {
21 | throw new Exception("String lengths must be equal");
22 | }
23 |
24 | int stringLength = s1.length();
25 | int counter = 0;
26 |
27 | for (int i = 0; i < stringLength; i++) {
28 | if (s1.charAt(i) != s2.charAt(i)) {
29 | counter++;
30 | }
31 | }
32 | return counter;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/strings/Lower.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | public final class Lower {
4 | private Lower() {
5 | }
6 |
7 | /**
8 | * Driver Code
9 | */
10 | public static void main(String[] args) {
11 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
12 | for (String s : strings) {
13 | assert toLowerCase(s).equals(s.toLowerCase());
14 | }
15 | }
16 |
17 | /**
18 | * Converts all of the characters in this {@code String} to lower case
19 | *
20 | * @param s the string to convert
21 | * @return the {@code String}, converted to lowercase.
22 | */
23 | public static String toLowerCase(String s) {
24 | char[] values = s.toCharArray();
25 | for (int i = 0; i < values.length; ++i) {
26 | if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) {
27 | values[i] = Character.toLowerCase(values[i]);
28 | }
29 | }
30 | return new String(values);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | /**
4 | * Reverse String using Recursion
5 | */
6 |
7 | public final class ReverseStringRecursive {
8 | private ReverseStringRecursive() {
9 | }
10 | /**
11 | * @param str string to be reversed
12 | * @return reversed string
13 | */
14 | public static String reverse(String str) {
15 | if (str.isEmpty()) {
16 | return str;
17 | } else {
18 | return reverse(str.substring(1)) + str.charAt(0);
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/strings/ReverseWordsInString.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import java.util.Arrays;
4 | import java.util.Collections;
5 |
6 | public final class ReverseWordsInString {
7 |
8 | private ReverseWordsInString() {
9 | }
10 |
11 | /**
12 | * @brief Reverses words in the input string
13 | * @param s the input string
14 | * @return A string created by reversing the order of the words in {@code s}
15 | */
16 |
17 | public static String reverseWordsInString(final String s) {
18 | var words = s.trim().split("\\s+");
19 | Collections.reverse(Arrays.asList(words));
20 | return String.join(" ", words);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/strings/Upper.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | public final class Upper {
4 | private Upper() {
5 | }
6 |
7 | /**
8 | * Driver Code
9 | */
10 | public static void main(String[] args) {
11 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"};
12 | for (String s : strings) {
13 | assert toUpperCase(s).equals(s.toUpperCase());
14 | }
15 | }
16 |
17 | /**
18 | * Converts all of the characters in this {@code String} to upper case
19 | *
20 | * @param s the string to convert
21 | * @return the {@code String}, converted to uppercase.
22 | */
23 | public static String toUpperCase(String s) {
24 | if (s == null || "".equals(s)) {
25 | return s;
26 | }
27 | char[] values = s.toCharArray();
28 | for (int i = 0; i < values.length; ++i) {
29 | if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) {
30 | values[i] = Character.toUpperCase(values[i]);
31 | }
32 | }
33 | return new String(values);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/backtracking/CombinationTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.backtracking;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertTrue;
4 |
5 | import java.util.List;
6 | import java.util.TreeSet;
7 | import org.junit.jupiter.api.Test;
8 |
9 | public class CombinationTest {
10 |
11 | @Test
12 | void testNoElement() {
13 | List> result = Combination.combination(new Integer[] {1, 2}, 0);
14 | assertTrue(result == null);
15 | }
16 |
17 | @Test
18 | void testLengthOne() {
19 | List> result = Combination.combination(new Integer[] {1, 2}, 1);
20 | assertTrue(result.get(0).iterator().next() == 1);
21 | assertTrue(result.get(1).iterator().next() == 2);
22 | }
23 |
24 | @Test
25 | void testLengthTwo() {
26 | List> result = Combination.combination(new Integer[] {1, 2}, 2);
27 | Integer[] arr = result.get(0).toArray(new Integer[2]);
28 | assertTrue(arr[0] == 1);
29 | assertTrue(arr[1] == 2);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/backtracking/PermutationTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.backtracking;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import java.util.Arrays;
7 | import java.util.List;
8 | import org.junit.jupiter.api.Test;
9 |
10 | public class PermutationTest {
11 |
12 | @Test
13 | void testNoElement() {
14 | List result = Permutation.permutation(new Integer[] {});
15 | assertEquals(result.get(0).length, 0);
16 | }
17 |
18 | @Test
19 | void testSingleElement() {
20 | List result = Permutation.permutation(new Integer[] {1});
21 | assertEquals(result.get(0)[0], 1);
22 | }
23 |
24 | @Test
25 | void testMultipleElements() {
26 | List result = Permutation.permutation(new Integer[] {1, 2});
27 | assertTrue(Arrays.equals(result.get(0), new Integer[] {1, 2}));
28 | assertTrue(Arrays.equals(result.get(1), new Integer[] {2, 1}));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.backtracking;
2 | import static org.junit.jupiter.api.Assertions.assertEquals;
3 |
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class PowerSumTest {
7 |
8 | @Test
9 | void testNumberZeroAndPowerZero() {
10 | PowerSum powerSum = new PowerSum();
11 | int result = powerSum.powSum(0, 0);
12 | assertEquals(1, result);
13 | }
14 |
15 | @Test
16 | void testNumberHundredAndPowerTwo() {
17 | PowerSum powerSum = new PowerSum();
18 | int result = powerSum.powSum(100, 2);
19 | assertEquals(3, result);
20 | }
21 |
22 | @Test
23 | void testNumberHundredAndPowerThree() {
24 | PowerSum powerSum = new PowerSum();
25 | int result = powerSum.powSum(100, 3);
26 | assertEquals(1, result);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.backtracking;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertTrue;
4 |
5 | import org.junit.jupiter.api.Assertions;
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class WordSearchTest {
9 | @Test
10 | void test1() {
11 | WordSearch ws = new WordSearch();
12 | char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};
13 | String word = "ABCCED";
14 | assertTrue(ws.exist(board, word));
15 | }
16 |
17 | @Test
18 | void test2() {
19 | WordSearch ws = new WordSearch();
20 | char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};
21 | String word = "SEE";
22 | assertTrue(ws.exist(board, word));
23 | }
24 |
25 | @Test
26 | void test3() {
27 | WordSearch ws = new WordSearch();
28 | char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};
29 | String word = "ABCB";
30 | Assertions.assertFalse(ws.exist(board, word));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.bitmanipulation;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 | public class BitSwapTest {
7 | @Test
8 | void testHighestSetBit() {
9 | assertEquals(3, BitSwap.bitSwap(3, 0, 1));
10 | assertEquals(5, BitSwap.bitSwap(6, 0, 1));
11 | assertEquals(7, BitSwap.bitSwap(7, 1, 1));
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.bitmanipulation;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | /**
8 | * Test case for Index Of Right Most SetBit
9 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
10 | */
11 |
12 | class IndexOfRightMostSetBitTest {
13 |
14 | @Test
15 | void testIndexOfRightMostSetBit() {
16 | assertEquals(3, IndexOfRightMostSetBit.indexOfRightMostSetBit(40));
17 | assertEquals(-1, IndexOfRightMostSetBit.indexOfRightMostSetBit(0));
18 | assertEquals(3, IndexOfRightMostSetBit.indexOfRightMostSetBit(-40));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/bitmanipulation/IsEvenTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.bitmanipulation;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | class IsEvenTest {
9 | @Test
10 | void testIsEven() {
11 | assertTrue(IsEven.isEven(0));
12 | assertTrue(IsEven.isEven(2));
13 | assertTrue(IsEven.isEven(-12));
14 | assertFalse(IsEven.isEven(21));
15 | assertFalse(IsEven.isEven(-1));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.bitmanipulation;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | /**
8 | * Test case for Non Repeating Number Finder
9 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
10 | */
11 |
12 | class NonRepeatingNumberFinderTest {
13 |
14 | @Test
15 | void testNonRepeatingNumberFinder() {
16 | int[] arr = {1, 2, 1, 2, 6};
17 | assertEquals(6, NonRepeatingNumberFinder.findNonRepeatingNumber(arr));
18 | int[] arr1 = {1, 2, 1, 2};
19 | assertEquals(0, NonRepeatingNumberFinder.findNonRepeatingNumber(arr1));
20 | int[] arr2 = {12};
21 | assertEquals(12, NonRepeatingNumberFinder.findNonRepeatingNumber(arr2));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.bitmanipulation;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 | /**
8 | * test Cases of Numbers Different Signs
9 | * @author Bama Charan Chhandogi
10 | */
11 | class NumbersDifferentSignsTest {
12 |
13 | @Test
14 | void testDifferentSignsPositiveNegative() {
15 | assertTrue(NumbersDifferentSigns.differentSigns(2, -1));
16 | }
17 |
18 | @Test
19 | void testDifferentSignsNegativePositive() {
20 | assertTrue(NumbersDifferentSigns.differentSigns(-3, 7));
21 | }
22 |
23 | @Test
24 | void testSameSignsPositive() {
25 | assertFalse(NumbersDifferentSigns.differentSigns(10, 20));
26 | }
27 |
28 | @Test
29 | void testSameSignsNegative() {
30 | assertFalse(NumbersDifferentSigns.differentSigns(-5, -8));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/bitmanipulation/ReverseBitsTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.bitmanipulation;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class ReverseBitsTest {
8 |
9 | @Test
10 | void testReverseBits() {
11 | assertEquals(0, ReverseBits.reverseBits(0));
12 | assertEquals(-1, ReverseBits.reverseBits(-1));
13 | assertEquals(964176192, ReverseBits.reverseBits(43261596));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.ciphers;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class BlowfishTest {
8 |
9 | Blowfish blowfish = new Blowfish();
10 |
11 | @Test
12 | void testEncrypt() {
13 | // given
14 | String plainText = "123456abcd132536";
15 | String key = "aabb09182736ccdd";
16 | String expectedOutput = "d748ec383d3405f7";
17 |
18 | // when
19 | String cipherText = blowfish.encrypt(plainText, key);
20 |
21 | // then
22 | assertEquals(expectedOutput, cipherText);
23 | }
24 |
25 | @Test
26 | void testDecrypt() {
27 | // given
28 | String cipherText = "d748ec383d3405f7";
29 | String key = "aabb09182736ccdd";
30 | String expectedOutput = "123456abcd132536";
31 |
32 | // when
33 | String plainText = blowfish.decrypt(cipherText, key);
34 |
35 | // then
36 | assertEquals(expectedOutput, plainText);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/ciphers/PolybiusTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.ciphers;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class PolybiusTest {
8 |
9 | @Test
10 | void testEncrypt() {
11 | // Given
12 | String plaintext = "HELLOWORLD";
13 |
14 | // When
15 | String actual = Polybius.encrypt(plaintext);
16 |
17 | // Then
18 | assertEquals("12042121244124322103", actual);
19 | }
20 |
21 | @Test
22 | void testDecrypt() {
23 | // Given
24 | String ciphertext = "12042121244124322103";
25 |
26 | // When
27 | String actual = Polybius.decrypt(ciphertext);
28 |
29 | // Then
30 | assertEquals("HELLOWORLD", actual);
31 | }
32 |
33 | @Test
34 | void testIsTextTheSameAfterEncryptionAndDecryption() {
35 | // Given
36 | String plaintext = "HELLOWORLD";
37 |
38 | // When
39 | String encryptedText = Polybius.encrypt(plaintext);
40 | String actual = Polybius.decrypt(encryptedText);
41 |
42 | // Then
43 | assertEquals(plaintext, actual);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/ciphers/RSATest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.ciphers;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class RSATest {
8 |
9 | RSA rsa = new RSA(1024);
10 |
11 | @Test
12 | void testRSA() {
13 | // given
14 | String textToEncrypt = "Such secure";
15 |
16 | // when
17 | String cipherText = rsa.encrypt(textToEncrypt);
18 | String decryptedText = rsa.decrypt(cipherText);
19 |
20 | // then
21 | assertEquals("Such secure", decryptedText);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.ciphers;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class SimpleSubCipherTest {
8 |
9 | SimpleSubCipher simpleSubCipher = new SimpleSubCipher();
10 |
11 | @Test
12 | void simpleSubCipherEncryptTest() {
13 | // given
14 | String text = "defend the east wall of the castle";
15 | String cipherSmall = "phqgiumeaylnofdxjkrcvstzwb";
16 |
17 | // when
18 | String cipherText = simpleSubCipher.encode(text, cipherSmall);
19 |
20 | // then
21 | assertEquals("giuifg cei iprc tpnn du cei qprcni", cipherText);
22 | }
23 |
24 | @Test
25 | void simpleSubCipherDecryptTest() {
26 | // given
27 | String encryptedText = "giuifg cei iprc tpnn du cei qprcni";
28 | String cipherSmall = "phqgiumeaylnofdxjkrcvstzwb";
29 |
30 | // when
31 | String decryptedText = simpleSubCipher.decode(encryptedText, cipherSmall);
32 |
33 | // then
34 | assertEquals("defend the east wall of the castle", decryptedText);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/ciphers/VigenereTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.ciphers;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class VigenereTest {
8 |
9 | Vigenere vigenere = new Vigenere();
10 |
11 | @Test
12 | void vigenereEncryptTest() {
13 | // given
14 | String text = "Hello World!";
15 | String key = "suchsecret";
16 |
17 | // when
18 | String cipherText = vigenere.encrypt(text, key);
19 |
20 | // then
21 | assertEquals("Zynsg Yfvev!", cipherText);
22 | }
23 |
24 | @Test
25 | void vigenereDecryptTest() {
26 | // given
27 | String encryptedText = "Zynsg Yfvev!";
28 | String key = "suchsecret";
29 |
30 | // when
31 | String decryptedText = vigenere.decrypt(encryptedText, key);
32 |
33 | // then
34 | assertEquals("Hello World!", decryptedText);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/BinaryToHexadecimalTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class BinaryToHexadecimalTest {
8 |
9 | @Test
10 | public void testBinaryToHexadecimal() {
11 | assertEquals("6A", BinaryToHexadecimal.binToHex(1101010));
12 | assertEquals("C", BinaryToHexadecimal.binToHex(1100));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/BinaryToOctalTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class BinaryToOctalTest {
8 |
9 | @Test
10 | public void testBinaryToOctal() {
11 | assertEquals("226", BinaryToOctal.convertBinaryToOctal(10010110));
12 | assertEquals("135", BinaryToOctal.convertBinaryToOctal(1011101));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/DecimalToHexaDecimalTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class DecimalToHexaDecimalTest {
8 |
9 | @Test
10 | public void testDecimalToHexaDecimal() {
11 | assertEquals("000000be", DecimalToHexaDecimal.decToHex(190));
12 | assertEquals("00000708", DecimalToHexaDecimal.decToHex(1800));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/HexToOctTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class HexToOctTest {
8 |
9 | @Test
10 | public void testHexToOct() {
11 | assertEquals(110, HexToOct.decimal2octal(HexToOct.hex2decimal("48")));
12 | assertEquals(255, HexToOct.decimal2octal(HexToOct.hex2decimal("AD")));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class HexaDecimalToBinaryTest {
8 |
9 | @Test
10 | public void testHexaDecimalToBinary() {
11 | HexaDecimalToBinary hexaDecimalToBinary = new HexaDecimalToBinary();
12 | assertEquals("1111111111111111111111111111111", hexaDecimalToBinary.convert("7fffffff"));
13 | assertEquals("101010111100110111101111", hexaDecimalToBinary.convert("abcdef"));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class HexaDecimalToDecimalTest {
8 |
9 | @Test
10 | public void testhexaDecimalToDecimal() {
11 | assertEquals(161, HexaDecimalToDecimal.getHexaToDec("A1"));
12 | assertEquals(428, HexaDecimalToDecimal.getHexaToDec("1ac"));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/IntegerToRomanTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class IntegerToRomanTest {
8 |
9 | @Test
10 | public void testIntegerToRoman() {
11 | assertEquals("MCMXCIV", IntegerToRoman.integerToRoman(1994));
12 | assertEquals("LVIII", IntegerToRoman.integerToRoman(58));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class OctalToBinaryTest {
8 | @Test
9 | public void testConvertOctalToBinary() {
10 | assertEquals(101, OctalToBinary.convertOctalToBinary(5));
11 | assertEquals(1001, OctalToBinary.convertOctalToBinary(11));
12 | assertEquals(101010, OctalToBinary.convertOctalToBinary(52));
13 | assertEquals(110, OctalToBinary.convertOctalToBinary(6));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/OctalToDecimalTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class OctalToDecimalTest {
8 |
9 | @Test
10 | public void testOctalToDecimal() {
11 | assertEquals(1465, OctalToDecimal.convertOctalToDecimal("2671"));
12 | assertEquals(189, OctalToDecimal.convertOctalToDecimal("275"));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class OctalToHexadecimalTest {
8 |
9 | @Test
10 | public void testOctalToHexadecimal() {
11 | assertEquals("1EA", OctalToHexadecimal.decimalToHex(OctalToHexadecimal.octToDec("752")));
12 | assertEquals("15E", OctalToHexadecimal.decimalToHex(OctalToHexadecimal.octToDec("536")));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.conversions;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class RomanToIntegerTest {
8 |
9 | @Test
10 | public void testRomanToInteger() {
11 | assertEquals(1994, RomanToInteger.romanToInt("MCMXCIV"));
12 | assertEquals(58, RomanToInteger.romanToInt("LVIII"));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.datastructures.bloomfilter;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class BloomFilterTest {
7 |
8 | @Test
9 | public void test1() {
10 | BloomFilter bloomFilter = new BloomFilter<>(3, 10);
11 | bloomFilter.insert(3);
12 | bloomFilter.insert(17);
13 |
14 | Assertions.assertTrue(bloomFilter.contains(3));
15 | Assertions.assertTrue(bloomFilter.contains(17));
16 | }
17 |
18 | @Test
19 | public void test2() {
20 | BloomFilter bloomFilter = new BloomFilter<>(4, 20);
21 | bloomFilter.insert("omar");
22 | bloomFilter.insert("mahamid");
23 |
24 | Assertions.assertTrue(bloomFilter.contains("omar"));
25 | Assertions.assertTrue(bloomFilter.contains("mahamid"));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMapTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.datastructures.hashmap.hashing;
2 |
3 | class LinearProbingHashMapTest extends MapTest {
4 | @Override
5 | , Value> Map getMap() {
6 | return new LinearProbingHashMap<>();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.datastructures.heaps;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class FibonacciHeapTest {
7 |
8 | @Test
9 | void testHeap() {
10 | FibonacciHeap fibonacciHeap = new FibonacciHeap();
11 | fibonacciHeap.insert(5);
12 | fibonacciHeap.insert(3);
13 | fibonacciHeap.insert(1);
14 | fibonacciHeap.insert(18);
15 | fibonacciHeap.insert(33);
16 |
17 | Assertions.assertEquals(fibonacciHeap.findMin().getKey(), 1);
18 | fibonacciHeap.deleteMin();
19 | Assertions.assertEquals(fibonacciHeap.findMin().getKey(), 3);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.datastructures.heaps;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class LeftistHeapTest {
7 |
8 | @Test
9 | void testLeftistHeap() {
10 | LeftistHeap heap = new LeftistHeap();
11 | Assertions.assertTrue(heap.isEmpty());
12 | heap.insert(6);
13 | Assertions.assertTrue(!heap.isEmpty());
14 | heap.insert(2);
15 | heap.insert(3);
16 | heap.insert(1);
17 | heap.inOrder();
18 | Assertions.assertTrue(heap.inOrder().toString().equals("[6, 2, 3, 1]"));
19 | Assertions.assertTrue(heap.extractMin() == 1);
20 | Assertions.assertTrue(heap.inOrder().toString().equals("[6, 2, 3]"));
21 | heap.insert(8);
22 | heap.insert(12);
23 | heap.insert(4);
24 | Assertions.assertTrue(heap.inOrder().toString().equals("[8, 3, 12, 2, 6, 4]"));
25 | heap.clear();
26 | Assertions.assertTrue(heap.isEmpty());
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.datastructures.queues;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class LinkedQueueTest {
8 | @Test
9 | public void testQue() {
10 | LinkedQueue queue = new LinkedQueue<>();
11 | for (int i = 1; i < 5; i++) {
12 | queue.enqueue(i);
13 | }
14 |
15 | assertEquals(queue.peekRear(), 4);
16 | assertEquals(queue.peek(2), 2);
17 |
18 | assertEquals(queue.peek(4), 4);
19 |
20 | final int[] element = {1};
21 |
22 | // iterates over all the elements present
23 | // as in the form of nodes
24 | queue.forEach(integer -> {
25 | if (element[0]++ != integer) {
26 | throw new AssertionError();
27 | }
28 | });
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/dynamicprogramming/CatalanNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.dynamicprogramming;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class CatalanNumberTest {
8 |
9 | @Test
10 | public void testCatalanNumber() {
11 | assertEquals(42, CatalanNumber.findNthCatalan(5));
12 | assertEquals(16796, CatalanNumber.findNthCatalan(10));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/dynamicprogramming/ClimbStairsTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.dynamicprogramming;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class ClimbStairsTest {
8 |
9 | @Test
10 | void climbStairsTestForTwo() {
11 | assertEquals(2, ClimbingStairs.numberOfWays(2));
12 | }
13 |
14 | @Test
15 | void climbStairsTestForZero() {
16 | assertEquals(0, ClimbingStairs.numberOfWays(0));
17 | }
18 |
19 | @Test
20 | void climbStairsTestForOne() {
21 | assertEquals(1, ClimbingStairs.numberOfWays(1));
22 | }
23 |
24 | @Test
25 | void climbStairsTestForFive() {
26 | assertEquals(8, ClimbingStairs.numberOfWays(5));
27 | }
28 |
29 | @Test
30 | void climbStairsTestForThree() {
31 | assertEquals(3, ClimbingStairs.numberOfWays(3));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.dynamicprogramming;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class EggDroppingTest {
8 |
9 | @Test
10 | void hasMultipleEggSingleFloor() {
11 | assertEquals(1, EggDropping.minTrials(3, 1));
12 | }
13 |
14 | @Test
15 | void hasSingleEggSingleFloor() {
16 | assertEquals(1, EggDropping.minTrials(1, 1));
17 | }
18 |
19 | @Test
20 | void hasSingleEggMultipleFloor() {
21 | assertEquals(3, EggDropping.minTrials(1, 3));
22 | }
23 |
24 | @Test
25 | void hasMultipleEggMultipleFloor() {
26 | assertEquals(7, EggDropping.minTrials(100, 101));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.dynamicprogramming;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class KnapsackMemoizationTest {
8 |
9 | KnapsackMemoization knapsackMemoization = new KnapsackMemoization();
10 |
11 | @Test
12 | void test1() {
13 | int[] weight = {1, 3, 4, 5};
14 | int[] value = {1, 4, 5, 7};
15 | int capacity = 10;
16 | assertEquals(13, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
17 | }
18 |
19 | @Test
20 | void test2() {
21 | int[] weight = {95, 4, 60, 32, 23, 72, 80, 62, 65, 46};
22 | int[] value = {55, 10, 47, 5, 4, 50, 8, 61, 85, 87};
23 | int capacity = 269;
24 | assertEquals(295, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
25 | }
26 |
27 | @Test
28 | void test3() {
29 | int[] weight = {10, 20, 30};
30 | int[] value = {60, 100, 120};
31 | int capacity = 50;
32 | assertEquals(220, knapsackMemoization.knapSack(capacity, weight, value, weight.length));
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.dynamicprogramming;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | class PartitionProblemTest {
9 | @Test
10 | public void testIfSumOfTheArrayIsOdd() {
11 | assertFalse(PartitionProblem.partition(new int[] {1, 2, 2}));
12 | }
13 | @Test
14 | public void testIfSizeOfTheArrayIsOne() {
15 | assertFalse(PartitionProblem.partition(new int[] {2}));
16 | }
17 | @Test
18 | public void testIfSumOfTheArrayIsEven1() {
19 | assertTrue(PartitionProblem.partition(new int[] {1, 2, 3, 6}));
20 | }
21 | @Test
22 | public void testIfSumOfTheArrayIsEven2() {
23 | assertFalse(PartitionProblem.partition(new int[] {1, 2, 3, 8}));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.dynamicprogramming;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class SubsetCountTest {
8 | @Test
9 | void hasMultipleSubset() {
10 | int[] arr = new int[] {1, 2, 3, 3};
11 | assertEquals(3, SubsetCount.getCount(arr, 6));
12 | }
13 | @Test
14 | void singleElementSubset() {
15 | int[] arr = new int[] {1, 1, 1, 1};
16 | assertEquals(4, SubsetCount.getCount(arr, 1));
17 | }
18 |
19 | @Test
20 | void hasMultipleSubsetSO() {
21 | int[] arr = new int[] {1, 2, 3, 3};
22 | assertEquals(3, SubsetCount.getCountSO(arr, 6));
23 | }
24 | @Test
25 | void singleSubsetSO() {
26 | int[] arr = new int[] {1, 1, 1, 1};
27 | assertEquals(1, SubsetCount.getCountSO(arr, 4));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/dynamicprogramming/SumOfSubsetTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.dynamicprogramming;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | class SumOfSubsetTest {
9 |
10 | @Test
11 | void basicCheck() {
12 | assertFalse(SumOfSubset.subsetSum(new int[] {1, 2, 7, 10, 9}, 4, 14));
13 | assertFalse(SumOfSubset.subsetSum(new int[] {2, 15, 1, 6, 7}, 4, 4));
14 | assertTrue(SumOfSubset.subsetSum(new int[] {7, 3, 2, 5, 8}, 4, 14));
15 | assertTrue(SumOfSubset.subsetSum(new int[] {4, 3, 2, 1}, 3, 5));
16 | assertTrue(SumOfSubset.subsetSum(new int[] {1, 7, 2, 9, 10}, 4, 13));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/dynamicprogramming/TribonacciTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.dynamicprogramming;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | /**
8 | * Test class for {@code Tribonacci}.
9 | */
10 | public class TribonacciTest {
11 |
12 | /**
13 | * Tests the Tribonacci computation for a set of known values.
14 | */
15 | @Test
16 | public void testKnownValues() {
17 | assertEquals(0, Tribonacci.compute(0), "The 0th Tribonacci should be 0.");
18 | assertEquals(1, Tribonacci.compute(1), "The 1st Tribonacci should be 1.");
19 | assertEquals(1, Tribonacci.compute(2), "The 2nd Tribonacci should be 1.");
20 | assertEquals(2, Tribonacci.compute(3), "The 3rd Tribonacci should be 2.");
21 | assertEquals(4, Tribonacci.compute(4), "The 4th Tribonacci should be 4.");
22 | assertEquals(7, Tribonacci.compute(5), "The 5th Tribonacci should be 7.");
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/dynamicprogramming/WildcardMatchingTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.dynamicprogramming;
2 | import static org.junit.jupiter.api.Assertions.assertFalse;
3 | import static org.junit.jupiter.api.Assertions.assertTrue;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class WildcardMatchingTest {
8 |
9 | @Test
10 | public void testMatchingPattern() {
11 | assertTrue(WildcardMatching.isMatch("aa", "a*"));
12 | assertTrue(WildcardMatching.isMatch("adceb", "*a*b"));
13 | }
14 |
15 | @Test
16 | public void testNonMatchingPattern() {
17 | assertFalse(WildcardMatching.isMatch("cb", "?a"));
18 | assertFalse(WildcardMatching.isMatch("acdcb", "a*c?b"));
19 | assertFalse(WildcardMatching.isMatch("mississippi", "m*issi*iss?*i"));
20 | }
21 |
22 | @Test
23 | public void testEmptyPattern() {
24 | assertTrue(WildcardMatching.isMatch("", ""));
25 | assertFalse(WildcardMatching.isMatch("abc", ""));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.geometry;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class GrahamScanTest {
8 | @Test
9 | void testGrahamScan() {
10 | GrahamScan.Point[] points = {new GrahamScan.Point(0, 3), new GrahamScan.Point(1, 1), new GrahamScan.Point(2, 2), new GrahamScan.Point(4, 4), new GrahamScan.Point(0, 0), new GrahamScan.Point(1, 2), new GrahamScan.Point(3, 1), new GrahamScan.Point(3, 3)};
11 | String expectedResult = "[(0, 0), (3, 1), (4, 4), (0, 3)]";
12 |
13 | GrahamScan graham = new GrahamScan(points);
14 | assertEquals(expectedResult, graham.hull().toString());
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.greedyalgorithms;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class FractionalKnapsackTest {
8 |
9 | @Test
10 | public void testFractionalKnapsackWithExampleCase() {
11 | int[] weight = {10, 20, 30};
12 | int[] value = {60, 100, 120};
13 | int capacity = 50;
14 | assertEquals(240, FractionalKnapsack.fractionalKnapsack(weight, value, capacity));
15 | }
16 |
17 | @Test
18 | public void testFractionalKnapsackWithZeroCapacity() {
19 | int[] weight = {10, 20, 30};
20 | int[] value = {60, 100, 120};
21 | int capacity = 0;
22 | assertEquals(0, FractionalKnapsack.fractionalKnapsack(weight, value, capacity));
23 | }
24 |
25 | @Test
26 | public void testFractionalKnapsackWithEmptyItems() {
27 | int[] weight = {};
28 | int[] value = {};
29 | int capacity = 50;
30 | assertEquals(0, FractionalKnapsack.fractionalKnapsack(weight, value, capacity));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.greedyalgorithms;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import java.util.ArrayList;
6 | import java.util.Collections;
7 | import org.junit.jupiter.api.Test;
8 |
9 | public class JobSequencingTest {
10 | @Test
11 | public void testJobSequencingWithExampleCase() {
12 | ArrayList jobs = new ArrayList<>();
13 | jobs.add(new JobSequencing.Job('a', 2, 100));
14 | jobs.add(new JobSequencing.Job('b', 1, 19));
15 | jobs.add(new JobSequencing.Job('c', 2, 27));
16 | jobs.add(new JobSequencing.Job('d', 1, 25));
17 | jobs.add(new JobSequencing.Job('e', 3, 15));
18 | Collections.sort(jobs);
19 | String jobSequence = JobSequencing.findJobSequence(jobs, jobs.size());
20 |
21 | assertEquals("Job Sequence: c -> a -> e", jobSequence);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class AbsoluteMaxTest {
9 |
10 | @Test
11 | void testGetMaxValue() {
12 | assertEquals(16, AbsoluteMax.getMaxValue(-2, 0, 16));
13 | assertEquals(-22, AbsoluteMax.getMaxValue(-3, -10, -22));
14 | assertEquals(-888, AbsoluteMax.getMaxValue(-888));
15 | }
16 |
17 | @Test
18 | void testGetMaxValueWithNoArguments() {
19 | assertThrows(IllegalArgumentException.class, AbsoluteMax::getMaxValue);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class AbsoluteMinTest {
9 |
10 | @Test
11 | void testGetMinValue() {
12 | assertEquals(0, AbsoluteMin.getMinValue(4, 0, 16));
13 | assertEquals(-2, AbsoluteMin.getMinValue(3, -10, -2));
14 | }
15 |
16 | @Test
17 | void testGetMinValueWithNoArguments() {
18 | Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMin.getMinValue());
19 | assertEquals("Numbers array cannot be empty", exception.getMessage());
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import java.util.concurrent.ThreadLocalRandom;
6 | import java.util.stream.Stream;
7 | import org.junit.jupiter.api.Test;
8 |
9 | public class AbsoluteValueTest {
10 |
11 | @Test
12 | void testGetAbsValue() {
13 | Stream.generate(() -> ThreadLocalRandom.current().nextInt()).limit(1000).forEach(number -> assertEquals(Math.abs(number), AbsoluteValue.getAbsValue(number)));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/AliquotSumTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class AliquotSumTest {
8 |
9 | @Test
10 | void testGetMaxValue() {
11 | assertEquals(0, AliquotSum.getAliquotValue(1));
12 | assertEquals(6, AliquotSum.getAliquotValue(6));
13 | assertEquals(9, AliquotSum.getAliquotValue(15));
14 | assertEquals(1, AliquotSum.getAliquotValue(19));
15 | assertEquals(0, AliquotSum.getAliquotSum(1));
16 | assertEquals(6, AliquotSum.getAliquotSum(6));
17 | assertEquals(9, AliquotSum.getAliquotSum(15));
18 | assertEquals(1, AliquotSum.getAliquotSum(19));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/ArmstrongTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | /**
8 | * @author satyabarghav
9 | * @since 4/10/2023
10 | */
11 | class ArmstrongTest {
12 |
13 | @Test
14 | void testIsArmstrong() {
15 | Armstrong armstrong = new Armstrong();
16 | assertThat(armstrong.isArmstrong(0)).isTrue();
17 | assertThat(armstrong.isArmstrong(1)).isTrue();
18 | assertThat(armstrong.isArmstrong(153)).isTrue();
19 | assertThat(armstrong.isArmstrong(371)).isTrue();
20 | assertThat(armstrong.isArmstrong(1634)).isTrue();
21 | assertThat(armstrong.isArmstrong(200)).isFalse();
22 | assertThat(armstrong.isArmstrong(548834)).isTrue();
23 | assertThat(armstrong.isArmstrong(9474)).isTrue();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/AverageTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class AverageTest {
7 |
8 | private static final double SMALL_VALUE = 0.00001d;
9 |
10 | @Test
11 | public void testAverageDouble12() {
12 | double[] numbers = {3d, 6d, 9d, 12d, 15d, 18d, 21d};
13 | Assertions.assertEquals(12d, Average.average(numbers), SMALL_VALUE);
14 | }
15 |
16 | @Test
17 | public void testAverageDouble20() {
18 | double[] numbers = {5d, 10d, 15d, 20d, 25d, 30d, 35d};
19 | Assertions.assertEquals(20d, Average.average(numbers), SMALL_VALUE);
20 | }
21 |
22 | @Test
23 | public void testAverageDouble() {
24 | double[] numbers = {1d, 2d, 3d, 4d, 5d, 6d, 7d, 8d};
25 | Assertions.assertEquals(4.5d, Average.average(numbers), SMALL_VALUE);
26 | }
27 |
28 | @Test
29 | public void testAverageInt() {
30 | int[] numbers = {2, 4, 10};
31 | Assertions.assertEquals(5, Average.average(numbers));
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/BinaryPowTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class BinaryPowTest {
8 |
9 | @Test
10 | void testBinPow() {
11 | assertEquals(4, BinaryPow.binPow(2, 2));
12 | assertEquals(256, BinaryPow.binPow(4, 4));
13 | assertEquals(729, BinaryPow.binPow(9, 3));
14 | assertEquals(262144, BinaryPow.binPow(8, 6));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/BinomialCoefficientTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class BinomialCoefficientTest {
8 |
9 | @Test
10 | void testBinomialCoefficient() {
11 | assertEquals(190, BinomialCoefficient.binomialCoefficient(20, 2));
12 | assertEquals(792, BinomialCoefficient.binomialCoefficient(12, 5));
13 | assertEquals(84, BinomialCoefficient.binomialCoefficient(9, 3));
14 | assertEquals(1, BinomialCoefficient.binomialCoefficient(17, 17));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/CeilTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class CeilTest {
8 |
9 | @Test
10 | void testCeil() {
11 | assertEquals(8, Ceil.ceil(7.057));
12 | assertEquals(8, Ceil.ceil(7.004));
13 | assertEquals(-13, Ceil.ceil(-13.004));
14 | assertEquals(1, Ceil.ceil(.98));
15 | assertEquals(-11, Ceil.ceil(-11.357));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/CombinationsTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class CombinationsTest {
8 |
9 | @Test
10 | void testCombination() {
11 | assertEquals(1, Combinations.combinations(1, 1));
12 | assertEquals(252, Combinations.combinations(10, 5));
13 | assertEquals(20, Combinations.combinations(6, 3));
14 | assertEquals(15504, Combinations.combinations(20, 5));
15 | }
16 |
17 | @Test
18 | void testCombinationOptimised() {
19 | assertEquals(100, Combinations.combinationsOptimized(100, 1));
20 | assertEquals(1, Combinations.combinationsOptimized(1, 1));
21 | assertEquals(252, Combinations.combinationsOptimized(10, 5));
22 | assertEquals(20, Combinations.combinationsOptimized(6, 3));
23 | assertEquals(15504, Combinations.combinationsOptimized(20, 5));
24 | assertEquals(2535650040L, Combinations.combinationsOptimized(200, 5));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/DigitalRootTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class DigitalRootTest {
8 |
9 | @Test
10 | void testDigitalroot() {
11 | assertEquals(4, DigitalRoot.digitalRoot(4));
12 | assertEquals(9, DigitalRoot.digitalRoot(9));
13 | assertEquals(4, DigitalRoot.digitalRoot(49));
14 | assertEquals(6, DigitalRoot.digitalRoot(78));
15 | assertEquals(4, DigitalRoot.digitalRoot(1228));
16 | assertEquals(5, DigitalRoot.digitalRoot(71348));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 | import static org.junit.jupiter.api.Assertions.assertTrue;
6 |
7 | import org.junit.jupiter.params.ParameterizedTest;
8 | import org.junit.jupiter.params.provider.CsvSource;
9 |
10 | class DudeneyNumberTest {
11 | @ParameterizedTest
12 | @CsvSource({"1", "512", "4913", "5832", "17576", "19683"})
13 | void positiveDudeneyBase10Power3(final int n) {
14 | assertTrue(DudeneyNumber.isDudeney(n));
15 | }
16 |
17 | @ParameterizedTest
18 | @CsvSource({"2", "19", "21", "125", "27", "343", "729", "19682", "19684"})
19 | void negativeDudeneyBase10Power3(final int n) {
20 | assertFalse(DudeneyNumber.isDudeney(n));
21 | }
22 |
23 | @ParameterizedTest
24 | @CsvSource({"0", "-1"})
25 | void throwsInputLessThanOne(final int n) {
26 | assertThrows(IllegalArgumentException.class, () -> DudeneyNumber.isDudeney(n));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/FactorialRecursionTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 |
6 | import java.util.stream.Stream;
7 | import org.junit.jupiter.api.Test;
8 | import org.junit.jupiter.params.ParameterizedTest;
9 | import org.junit.jupiter.params.provider.Arguments;
10 | import org.junit.jupiter.params.provider.MethodSource;
11 |
12 | public class FactorialRecursionTest {
13 | @ParameterizedTest
14 | @MethodSource("inputStream")
15 | void testFactorialRecursion(long expected, int number) {
16 | assertEquals(expected, FactorialRecursion.factorial(number));
17 | }
18 |
19 | private static Stream inputStream() {
20 | return Stream.of(Arguments.of(1, 0), Arguments.of(1, 1), Arguments.of(2, 2), Arguments.of(6, 3), Arguments.of(120, 5));
21 | }
22 |
23 | @Test
24 | void testThrowsForNegativeInput() {
25 | assertThrows(IllegalArgumentException.class, () -> FactorialRecursion.factorial(-1));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/FactorialTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class FactorialTest {
9 | private static final String EXCEPTION_MESSAGE = "Input number cannot be negative";
10 |
11 | @Test
12 | public void testWhenInvalidInoutProvidedShouldThrowException() {
13 | IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> Factorial.factorial(-1));
14 | assertEquals(exception.getMessage(), EXCEPTION_MESSAGE);
15 | }
16 |
17 | @Test
18 | public void testCorrectFactorialCalculation() {
19 | assertEquals(1, Factorial.factorial(0));
20 | assertEquals(1, Factorial.factorial(1));
21 | assertEquals(120, Factorial.factorial(5));
22 | assertEquals(3628800, Factorial.factorial(10));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/FibonacciLoopTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 |
6 | import java.math.BigInteger;
7 | import org.junit.jupiter.api.Test;
8 |
9 | public class FibonacciLoopTest {
10 | @Test
11 | public void checkValueAtZero() {
12 | assertEquals(BigInteger.ZERO, FibonacciLoop.compute(0));
13 | }
14 |
15 | @Test
16 | public void checkValueAtOne() {
17 | assertEquals(BigInteger.ONE, FibonacciLoop.compute(1));
18 | }
19 |
20 | @Test
21 | public void checkValueAtTwo() {
22 | assertEquals(BigInteger.ONE, FibonacciLoop.compute(2));
23 | }
24 |
25 | @Test
26 | public void checkRecurrenceRelation() {
27 | for (int i = 0; i < 100; ++i) {
28 | assertEquals(FibonacciLoop.compute(i + 2), FibonacciLoop.compute(i + 1).add(FibonacciLoop.compute(i)));
29 | }
30 | }
31 |
32 | @Test
33 | public void checkNegativeInput() {
34 | assertThrows(IllegalArgumentException.class, () -> { FibonacciLoop.compute(-1); });
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/FibonacciNumberGoldenRationTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 |
6 | import java.math.BigInteger;
7 | import org.junit.jupiter.api.Test;
8 |
9 | public class FibonacciNumberGoldenRationTest {
10 |
11 | @Test
12 | public void returnsCorrectValues() {
13 | for (int n = 0; n <= FibonacciNumberGoldenRation.MAX_ARG; ++n) {
14 | final var actual = FibonacciNumberGoldenRation.compute(n);
15 | final var expected = FibonacciLoop.compute(n);
16 | assertEquals(expected, BigInteger.valueOf(actual));
17 | }
18 | }
19 |
20 | @Test
21 | public void throwsIllegalArgumentExceptionForNegativeInput() {
22 | assertThrows(IllegalArgumentException.class, () -> { FibonacciNumberGoldenRation.compute(-1); });
23 | }
24 |
25 | @Test
26 | public void throwsIllegalArgumentExceptionForLargeInput() {
27 | assertThrows(IllegalArgumentException.class, () -> { FibonacciNumberGoldenRation.compute(FibonacciNumberGoldenRation.MAX_ARG + 1); });
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/FindMaxRecursionTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertThrows;
4 |
5 | import java.util.stream.Stream;
6 | import org.junit.jupiter.api.Assertions;
7 | import org.junit.jupiter.api.Test;
8 | import org.junit.jupiter.params.ParameterizedTest;
9 | import org.junit.jupiter.params.provider.Arguments;
10 | import org.junit.jupiter.params.provider.MethodSource;
11 |
12 | public class FindMaxRecursionTest {
13 |
14 | @ParameterizedTest
15 | @MethodSource("inputStream")
16 | void numberTests(int expected, int[] input) {
17 | Assertions.assertEquals(expected, FindMaxRecursion.max(input));
18 | }
19 |
20 | private static Stream inputStream() {
21 | return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(0, new int[] {-1, 0}), Arguments.of(-1, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(9, new int[] {3, -2, 3, 9, -4, -4, 8}), Arguments.of(3, new int[] {3}));
22 | }
23 |
24 | @Test
25 | public void testFindMaxThrowsExceptionForEmptyInput() {
26 | assertThrows(IllegalArgumentException.class, () -> FindMaxRecursion.max(new int[] {}));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/FindMaxTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertThrows;
4 |
5 | import java.util.stream.Stream;
6 | import org.junit.jupiter.api.Assertions;
7 | import org.junit.jupiter.api.Test;
8 | import org.junit.jupiter.params.ParameterizedTest;
9 | import org.junit.jupiter.params.provider.Arguments;
10 | import org.junit.jupiter.params.provider.MethodSource;
11 |
12 | public class FindMaxTest {
13 |
14 | @ParameterizedTest
15 | @MethodSource("inputStream")
16 | void numberTests(int expected, int[] input) {
17 | Assertions.assertEquals(expected, FindMax.findMax(input));
18 | }
19 |
20 | private static Stream inputStream() {
21 | return Stream.of(Arguments.of(10, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(0, new int[] {-1, 0}), Arguments.of(-1, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(9, new int[] {3, -2, 3, 9, -4, -4, 8}));
22 | }
23 |
24 | @Test
25 | public void testFindMaxThrowsExceptionForEmptyInput() {
26 | assertThrows(IllegalArgumentException.class, () -> FindMax.findMax(new int[] {}));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/FindMinRecursionTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertThrows;
4 |
5 | import java.util.stream.Stream;
6 | import org.junit.jupiter.api.Assertions;
7 | import org.junit.jupiter.api.Test;
8 | import org.junit.jupiter.params.ParameterizedTest;
9 | import org.junit.jupiter.params.provider.Arguments;
10 | import org.junit.jupiter.params.provider.MethodSource;
11 |
12 | public class FindMinRecursionTest {
13 |
14 | @ParameterizedTest
15 | @MethodSource("inputStream")
16 | void numberTests(int expected, int[] input) {
17 | Assertions.assertEquals(expected, FindMinRecursion.min(input));
18 | }
19 |
20 | private static Stream inputStream() {
21 | return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(-1, new int[] {-1, 0}), Arguments.of(-10, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(-4, new int[] {3, -2, 3, 9, -4, -4, 8}), Arguments.of(3, new int[] {3}));
22 | }
23 |
24 | @Test
25 | public void testFindMaxThrowsExceptionForEmptyInput() {
26 | assertThrows(IllegalArgumentException.class, () -> FindMinRecursion.min(new int[] {}));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/FloorTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 | public class FloorTest {
7 | @Test
8 | public void testFloorWholeNumber() {
9 | assertEquals(0, Floor.floor(0));
10 | assertEquals(1, Floor.floor(1));
11 | assertEquals(-1, Floor.floor(-1));
12 | assertEquals(42, Floor.floor(42));
13 | assertEquals(-42, Floor.floor(-42));
14 | }
15 |
16 | @Test
17 | public void testFloorDoubleNumber() {
18 | assertEquals(0, Floor.floor(0.1));
19 | assertEquals(1, Floor.floor(1.9));
20 | assertEquals(-2, Floor.floor(-1.1));
21 | assertEquals(-43, Floor.floor(-42.7));
22 | }
23 |
24 | @Test
25 | public void testFloorNegativeZero() {
26 | assertEquals(-0.0, Floor.floor(-0.0));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 | public class FrizzyNumberTest {
7 | @Test
8 | public void testFrizziesForBase2() {
9 | assertEquals(1, FrizzyNumber.getNthFrizzy(2, 1));
10 | assertEquals(3, FrizzyNumber.getNthFrizzy(2, 3));
11 | assertEquals(1000, FrizzyNumber.getNthFrizzy(2, 1000));
12 | }
13 |
14 | @Test
15 | public void testFrizziesForBase3() {
16 | assertEquals(1, FrizzyNumber.getNthFrizzy(3, 1));
17 | assertEquals(3, FrizzyNumber.getNthFrizzy(3, 2));
18 | assertEquals(29430, FrizzyNumber.getNthFrizzy(3, 1000));
19 | }
20 |
21 | @Test
22 | public void testFrizziesForBase69() {
23 | assertEquals(1, FrizzyNumber.getNthFrizzy(69, 1));
24 | assertEquals(69, FrizzyNumber.getNthFrizzy(69, 2));
25 | assertEquals(328510, FrizzyNumber.getNthFrizzy(69, 9));
26 | assertEquals(333340, FrizzyNumber.getNthFrizzy(69, 15));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/GaussianTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static com.thealgorithms.maths.Gaussian.gaussian;
4 | import static org.junit.jupiter.api.Assertions.assertEquals;
5 |
6 | import java.util.ArrayList;
7 | import org.junit.jupiter.api.Test;
8 |
9 | public class GaussianTest {
10 |
11 | // easy pass test for the whole class. Matrix of 2*3.
12 | @Test
13 | void passTest1() {
14 | ArrayList list = new ArrayList();
15 | ArrayList gaussian = new ArrayList();
16 | ArrayList answer = new ArrayList();
17 | answer.add(0.0);
18 | answer.add(1.0);
19 |
20 | int matrixSize = 2;
21 | list.add(1.0);
22 | list.add(1.0);
23 | list.add(1.0);
24 | list.add(2.0);
25 | list.add(1.0);
26 | list.add(1.0);
27 | gaussian = gaussian(matrixSize, list);
28 |
29 | assertEquals(answer, gaussian);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/GenericRootTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import java.util.stream.Stream;
6 | import org.junit.jupiter.params.ParameterizedTest;
7 | import org.junit.jupiter.params.provider.Arguments;
8 | import org.junit.jupiter.params.provider.MethodSource;
9 |
10 | public class GenericRootTest {
11 | @ParameterizedTest
12 | @MethodSource("tcStream")
13 | public void testGenericRoot(final int input, final int expected) {
14 | assertEquals(expected, GenericRoot.genericRoot(input));
15 | }
16 |
17 | @ParameterizedTest
18 | @MethodSource("tcStream")
19 | public void testGenericRootWithNegativeInputs(final int input, final int expected) {
20 | assertEquals(expected, GenericRoot.genericRoot(-input));
21 | }
22 |
23 | private static Stream tcStream() {
24 | return Stream.of(Arguments.of(0, 0), Arguments.of(1, 1), Arguments.of(12345, 6), Arguments.of(123, 6), Arguments.of(15937, 7), Arguments.of(222222, 3), Arguments.of(99999, 9));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class HarshadNumberTest {
9 |
10 | @Test
11 | public void harshadNumber() {
12 |
13 | assertTrue(HarshadNumber.isHarshad(18));
14 | assertFalse(HarshadNumber.isHarshad(-18));
15 | assertFalse(HarshadNumber.isHarshad(19));
16 | assertTrue(HarshadNumber.isHarshad(999999999));
17 | assertFalse(HarshadNumber.isHarshad(0));
18 |
19 | assertTrue(HarshadNumber.isHarshad("18"));
20 | assertFalse(HarshadNumber.isHarshad("-18"));
21 | assertFalse(HarshadNumber.isHarshad("19"));
22 | assertTrue(HarshadNumber.isHarshad("999999999"));
23 | assertTrue(HarshadNumber.isHarshad("99999999999100"));
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/JosephusProblemTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class JosephusProblemTest {
8 |
9 | @Test
10 | void testJosephusProblem() {
11 | assertEquals(3, JosephusProblem.findTheWinner(5, 2));
12 | assertEquals(5, JosephusProblem.findTheWinner(6, 4));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class LeastCommonMultipleTest {
7 |
8 | /*
9 | * Test for first number greater than second number
10 | */
11 | @Test
12 | public void testForFirst() {
13 | int result = LeastCommonMultiple.lcm(6, 8);
14 | int expected = 24;
15 | Assertions.assertEquals(result, expected);
16 | }
17 |
18 | /*
19 | * Test for second number greater than first number
20 | */
21 | @Test
22 | public void testForSecond() {
23 | int result = LeastCommonMultiple.lcm(8, 6);
24 | int expected = 24;
25 | Assertions.assertEquals(result, expected);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class LeonardoNumberTest {
9 | @Test
10 | void leonardoNumberNegative() {
11 | assertThrows(ArithmeticException.class, () -> LeonardoNumber.leonardoNumber(-1));
12 | }
13 | @Test
14 | void leonardoNumberZero() {
15 | assertEquals(1, LeonardoNumber.leonardoNumber(0));
16 | }
17 | @Test
18 | void leonardoNumberOne() {
19 | assertEquals(1, LeonardoNumber.leonardoNumber(1));
20 | }
21 | @Test
22 | void leonardoNumberFive() {
23 | assertEquals(15, LeonardoNumber.leonardoNumber(5));
24 | }
25 | @Test
26 | void leonardoNumberTwenty() {
27 | assertEquals(21891, LeonardoNumber.leonardoNumber(20));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class LucasSeriesTest {
8 | @Test
9 | void lucasSeriesTwo() {
10 | assertEquals(2, LucasSeries.lucasSeries(1));
11 | assertEquals(2, LucasSeries.lucasSeriesIteration(1));
12 | }
13 | @Test
14 | void lucasSeriesOne() {
15 | assertEquals(1, LucasSeries.lucasSeries(2));
16 | assertEquals(1, LucasSeries.lucasSeriesIteration(2));
17 | }
18 | @Test
19 | void lucasSeriesSeven() {
20 | assertEquals(7, LucasSeries.lucasSeries(5));
21 | assertEquals(7, LucasSeries.lucasSeriesIteration(5));
22 | }
23 | @Test
24 | void lucasSeriesEleven() {
25 | assertEquals(123, LucasSeries.lucasSeries(11));
26 | assertEquals(123, LucasSeries.lucasSeriesIteration(11));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/MaxValueTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class MaxValueTest {
8 | @Test
9 | public void maxTest() {
10 | assertEquals(-1, MaxValue.max(-1, -3));
11 | assertEquals(3, MaxValue.max(3, 2));
12 | assertEquals(5, MaxValue.max(5, 5));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/MedianTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class MedianTest {
8 | @Test
9 | void medianSingleValue() {
10 | int[] arr = {0};
11 | assertEquals(0, Median.median(arr));
12 | }
13 |
14 | @Test
15 | void medianTwoValues() {
16 | int[] arr = {1, 2};
17 | assertEquals(1.5, Median.median(arr));
18 | }
19 |
20 | @Test
21 | void medianThreeValues() {
22 | int[] arr = {1, 2, 3};
23 | assertEquals(2, Median.median(arr));
24 | }
25 |
26 | @Test
27 | void medianDecimalValueReturn() {
28 | int[] arr = {1, 2, 3, 4, 5, 6, 8, 9};
29 | assertEquals(4.5, Median.median(arr));
30 | }
31 |
32 | @Test
33 | void medianNegativeValues() {
34 | int[] arr = {-27, -16, -7, -4, -2, -1};
35 | assertEquals(-5.5, Median.median(arr));
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/MinValueTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class MinValueTest {
8 | @Test
9 | public void minTest() {
10 | assertEquals(-1, MinValue.min(-1, 3));
11 | assertEquals(2, MinValue.min(3, 2));
12 | assertEquals(5, MinValue.min(5, 5));
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/ModeTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4 |
5 | import java.util.stream.Stream;
6 | import org.junit.jupiter.params.ParameterizedTest;
7 | import org.junit.jupiter.params.provider.Arguments;
8 | import org.junit.jupiter.params.provider.MethodSource;
9 |
10 | public class ModeTest {
11 | @ParameterizedTest
12 | @MethodSource("tcStream")
13 | void basicTest(final int[] expected, final int[] numbers) {
14 | assertArrayEquals(expected, Mode.mode(numbers));
15 | }
16 |
17 | private static Stream tcStream() {
18 | return Stream.of(Arguments.of(null, new int[] {}), Arguments.of(new int[] {5}, new int[] {5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {5, 4, 3, 2, 1}),
19 | Arguments.of(new int[] {7}, new int[] {7, 9, 9, 4, 5, 6, 7, 7, 8}), Arguments.of(new int[] {7, 9}, new int[] {7, 9, 9, 4, 5, 6, 7, 7, 9}));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | class PerfectNumberTest {
9 |
10 | @Test
11 | public void perfectNumber() {
12 | int[] trueTestCases = {6, 28, 496, 8128, 33550336};
13 | int[] falseTestCases = {-6, 0, 1, 9, 123};
14 | for (Integer n : trueTestCases) {
15 | assertTrue(PerfectNumber.isPerfectNumber(n));
16 | assertTrue(PerfectNumber.isPerfectNumber2(n));
17 | }
18 | for (Integer n : falseTestCases) {
19 | assertFalse(PerfectNumber.isPerfectNumber(n));
20 | assertFalse(PerfectNumber.isPerfectNumber2(n));
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.params.ParameterizedTest;
5 | import org.junit.jupiter.params.provider.ValueSource;
6 |
7 | public class PerfectSquareTest {
8 | @ParameterizedTest
9 | @ValueSource(ints = {0, 1, 2 * 2, 3 * 3, 4 * 4, 5 * 5, 6 * 6, 7 * 7, 8 * 8, 9 * 9, 10 * 10, 11 * 11, 123 * 123})
10 | void positiveTest(final int number) {
11 | Assertions.assertTrue(PerfectSquare.isPerfectSquare(number));
12 | }
13 |
14 | @ParameterizedTest
15 | @ValueSource(ints = {-1, -2, -3, -4, -5, -100, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 17, 99, 101, 257, 999, 1001})
16 | void negativeTest(final int number) {
17 | Assertions.assertFalse(PerfectSquare.isPerfectSquare(number));
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/PowerOfTwoOrNotTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class PowerOfTwoOrNotTest {
9 | @Test
10 | public void testPowerOfTwoOrNotForPowersOfTwo() {
11 | final var powersOfTwo = new int[] {1, 2, 4, 8, 16, 32, 64};
12 | for (final var n : powersOfTwo) {
13 | assertTrue(PowerOfTwoOrNot.checkIfPowerOfTwoOrNot(n));
14 | }
15 | }
16 |
17 | @Test
18 | public void testPowerOfTwoOrNotForNotPowersOfTwo() {
19 | final var notPowersOfTwo = new int[] {-16, -8, -6, -5, -4, -3, -2, -1, 0, 3, 5, 6, 7, 9, 10, 11, 33, 63, 65, 1000, 9999};
20 | for (final var n : notPowersOfTwo) {
21 | assertFalse(PowerOfTwoOrNot.checkIfPowerOfTwoOrNot(n));
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | /**
8 | * Test case for Power using Recursion
9 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
10 | */
11 |
12 | class PowerUsingRecursionTest {
13 |
14 | @Test
15 | void testPowerUsingRecursion() {
16 | assertEquals(32.0, PowerUsingRecursion.power(2.0, 5));
17 | assertEquals(97.65625, PowerUsingRecursion.power(2.5, 5));
18 | assertEquals(81, PowerUsingRecursion.power(3, 4));
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/PrimeCheckTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class PrimeCheckTest {
7 |
8 | @Test
9 | void test1() {
10 | Assertions.assertTrue(PrimeCheck.isPrime(2));
11 | }
12 |
13 | @Test
14 | void test2() {
15 | Assertions.assertFalse(PrimeCheck.isPrime(-1));
16 | }
17 |
18 | @Test
19 | void test3() {
20 | Assertions.assertFalse(PrimeCheck.isPrime(4));
21 | }
22 |
23 | @Test
24 | void test4() {
25 | Assertions.assertTrue(PrimeCheck.isPrime(5));
26 | }
27 |
28 | @Test
29 | void test5() {
30 | Assertions.assertFalse(PrimeCheck.isPrime(15));
31 | }
32 |
33 | @Test
34 | void test6() {
35 | Assertions.assertTrue(PrimeCheck.isPrime(11));
36 | }
37 |
38 | @Test
39 | void test7() {
40 | Assertions.assertFalse(PrimeCheck.isPrime(49));
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import java.util.List;
7 | import org.junit.jupiter.api.Test;
8 |
9 | class PrimeFactorizationTest {
10 |
11 | @Test
12 | void testpFactorsMustReturnEmptyList() {
13 | // given
14 | int n = 0;
15 |
16 | // then
17 | assertTrue(PrimeFactorization.pfactors(n).isEmpty());
18 | }
19 |
20 | @Test
21 | void testpFactorsMustReturnNonEmptyList() {
22 | // given
23 | int n = 198;
24 | int expectedListSize = 4;
25 |
26 | // when
27 | List actualResultList = PrimeFactorization.pfactors(n);
28 |
29 | // then
30 | assertEquals(expectedListSize, actualResultList.size());
31 | assertEquals(2, actualResultList.get(0));
32 | assertEquals(3, actualResultList.get(1));
33 | assertEquals(3, actualResultList.get(2));
34 | assertEquals(11, actualResultList.get(3));
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/PronicNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class PronicNumberTest {
9 |
10 | @Test
11 | void testForPronicNumber() {
12 | // given
13 | int number = 30;
14 |
15 | // when
16 | boolean result = PronicNumber.isPronic(number);
17 |
18 | // then
19 | assertTrue(result);
20 | }
21 |
22 | @Test
23 | void testForNonPronicNumber() {
24 | // given
25 | int number = 21;
26 |
27 | // when
28 | boolean result = PronicNumber.isPronic(number);
29 |
30 | // then
31 | assertFalse(result);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class PythagoreanTripleTest {
9 |
10 | @Test
11 | public void testPythagoreanTriple() {
12 | assertTrue(PythagoreanTriple.isPythagTriple(3, 4, 5));
13 | assertTrue(PythagoreanTriple.isPythagTriple(6, 8, 10));
14 | assertTrue(PythagoreanTriple.isPythagTriple(9, 12, 15));
15 | assertTrue(PythagoreanTriple.isPythagTriple(12, 16, 20));
16 | assertTrue(PythagoreanTriple.isPythagTriple(15, 20, 25));
17 | assertTrue(PythagoreanTriple.isPythagTriple(18, 24, 30));
18 | assertFalse(PythagoreanTriple.isPythagTriple(5, 20, 30));
19 | assertFalse(PythagoreanTriple.isPythagTriple(6, 8, 100));
20 | assertFalse(PythagoreanTriple.isPythagTriple(-2, -2, 2));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 |
6 | import java.util.HashMap;
7 | import org.junit.jupiter.api.Test;
8 |
9 | public class ReverseNumberTest {
10 |
11 | @Test
12 | public void testReverseNumber() {
13 | HashMap testCases = new HashMap<>();
14 | testCases.put(0, 0);
15 | testCases.put(1, 1);
16 | testCases.put(10, 1);
17 | testCases.put(123, 321);
18 | testCases.put(7890, 987);
19 |
20 | for (final var tc : testCases.entrySet()) {
21 | assertEquals(ReverseNumber.reverseNumber(tc.getKey()), tc.getValue());
22 | }
23 | }
24 |
25 | @Test
26 | public void testReverseNumberThrowsExceptionForNegativeInput() {
27 | assertThrows(IllegalArgumentException.class, () -> ReverseNumber.reverseNumber(-1));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class SquareRootWithNewtonRaphsonTestMethod {
7 |
8 | @Test
9 | void testfor1() {
10 | Assertions.assertEquals(1, SquareRootWithNewtonRaphsonMethod.squareRoot(1));
11 | }
12 |
13 | @Test
14 | void testfor2() {
15 | Assertions.assertEquals(1.414213562373095, SquareRootWithNewtonRaphsonMethod.squareRoot(2));
16 | }
17 |
18 | @Test
19 | void testfor625() {
20 | Assertions.assertEquals(25.0, SquareRootWithNewtonRaphsonMethod.squareRoot(625));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class SquareRootwithBabylonianMethodTest {
7 |
8 | @Test
9 | void testfor4() {
10 | Assertions.assertEquals(2, SquareRootWithBabylonianMethod.squareRoot(4));
11 | }
12 |
13 | @Test
14 | void testfor1() {
15 | Assertions.assertEquals(1, SquareRootWithBabylonianMethod.squareRoot(1));
16 | }
17 |
18 | @Test
19 | void testfor2() {
20 | Assertions.assertEquals(1.4142135381698608, SquareRootWithBabylonianMethod.squareRoot(2));
21 | }
22 |
23 | @Test
24 | void testfor625() {
25 | Assertions.assertEquals(25, SquareRootWithBabylonianMethod.squareRoot(625));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class StandardDeviationTest {
7 |
8 | @Test
9 | void test1() {
10 | double[] t1 = new double[] {1, 1, 1, 1, 1};
11 | Assertions.assertEquals(StandardDeviation.stdDev(t1), 0.0);
12 | }
13 |
14 | @Test
15 | void test2() {
16 | double[] t2 = new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
17 | Assertions.assertEquals(StandardDeviation.stdDev(t2), 2.8722813232690143);
18 | }
19 |
20 | @Test
21 | void test3() {
22 | double[] t3 = new double[] {1.1, 8.5, 20.3, 2.4, 6.2};
23 | Assertions.assertEquals(StandardDeviation.stdDev(t3), 6.8308125431752265);
24 | }
25 |
26 | @Test
27 | void test4() {
28 | double[] t4 = new double[] {
29 | 3.14,
30 | 2.22222,
31 | 9.89898989,
32 | 100.00045,
33 | 56.7,
34 | };
35 | Assertions.assertEquals(StandardDeviation.stdDev(t4), 38.506117353865775);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/StandardScoreTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class StandardScoreTest {
7 |
8 | @Test
9 | void test1() {
10 | Assertions.assertEquals(StandardScore.zScore(2, 0, 5), 0.4);
11 | }
12 |
13 | @Test
14 | void test2() {
15 | Assertions.assertEquals(StandardScore.zScore(1, 1, 1), 0.0);
16 | }
17 |
18 | @Test
19 | void test3() {
20 | Assertions.assertEquals(StandardScore.zScore(2.5, 1.8, 0.7), 1.0);
21 | }
22 |
23 | @Test
24 | void test4() {
25 | Assertions.assertEquals(StandardScore.zScore(8.9, 3, 4.2), 1.4047619047619049);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/StrobogrammaticNumberTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class StrobogrammaticNumberTest {
8 |
9 | @Test
10 | void testIsStrobogrammatic() {
11 | StrobogrammaticNumber strobogrammaticNumber = new StrobogrammaticNumber();
12 | assertThat(strobogrammaticNumber.isStrobogrammatic("69")).isTrue();
13 | assertThat(strobogrammaticNumber.isStrobogrammatic("88")).isTrue();
14 | assertThat(strobogrammaticNumber.isStrobogrammatic("818")).isTrue();
15 | assertThat(strobogrammaticNumber.isStrobogrammatic("101")).isTrue();
16 | assertThat(strobogrammaticNumber.isStrobogrammatic("609")).isTrue();
17 | assertThat(strobogrammaticNumber.isStrobogrammatic("120")).isFalse();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class SumWithoutArithmeticOperatorsTest {
8 | SumWithoutArithmeticOperators obj = new SumWithoutArithmeticOperators();
9 |
10 | @Test
11 | void addZerotoZero() {
12 | assertEquals(0, obj.getSum(0, 0));
13 | }
14 |
15 | @Test
16 | void addZerotoNumber() {
17 | assertEquals(5, obj.getSum(0, 5));
18 | assertEquals(28, obj.getSum(28, 0));
19 | }
20 |
21 | @Test
22 | void addOddtoEven() {
23 | assertEquals(13, obj.getSum(3, 10));
24 | assertEquals(55, obj.getSum(49, 6));
25 | }
26 |
27 | @Test
28 | void addEventoOdd() {
29 | assertEquals(13, obj.getSum(10, 3));
30 | assertEquals(41, obj.getSum(40, 1));
31 | }
32 |
33 | @Test
34 | void addRandoms() {
35 | assertEquals(88, obj.getSum(44, 44));
36 | assertEquals(370, obj.getSum(100, 270));
37 | assertEquals(3, obj.getSum(1, 2));
38 | assertEquals(5, obj.getSum(2, 3));
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/TestArmstrong.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class TestArmstrong {
8 |
9 | @Test
10 | public void testArmstrong() {
11 | Armstrong armstrong = new Armstrong();
12 | assertThat(armstrong.isArmstrong(371)).isTrue();
13 | assertThat(armstrong.isArmstrong(200)).isFalse();
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/maths/VolumeTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertTrue;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class VolumeTest {
8 |
9 | @Test
10 | public void volume() {
11 |
12 | /* test cube */
13 | assertTrue(Volume.volumeCube(7) == 343.0);
14 |
15 | /* test cuboid */
16 | assertTrue(Volume.volumeCuboid(2, 5, 7) == 70.0);
17 |
18 | /* test sphere */
19 | assertTrue(Volume.volumeSphere(7) == 1436.7550402417319);
20 |
21 | /* test cylinder */
22 | assertTrue(Volume.volumeCylinder(3, 7) == 197.92033717615698);
23 |
24 | /* test hemisphere */
25 | assertTrue(Volume.volumeHemisphere(7) == 718.3775201208659);
26 |
27 | /* test cone */
28 | assertTrue(Volume.volumeCone(3, 7) == 65.97344572538566);
29 |
30 | /* test prism */
31 | assertTrue(Volume.volumePrism(10, 2) == 20.0);
32 |
33 | /* test pyramid */
34 | assertTrue(Volume.volumePyramid(10, 3) == 10.0);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/misc/MapReduceTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.misc;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class MapReduceTest {
8 | @Test
9 | public void testMapReduceWithSingleWordSentence() {
10 | String oneWordSentence = "Hactober";
11 | String result = MapReduce.mapreduce(oneWordSentence);
12 |
13 | assertEquals("Hactober: 1", result);
14 | }
15 |
16 | @Test
17 | public void testMapReduceWithMultipleWordSentence() {
18 | String multipleWordSentence = "I Love Love HactoberFest";
19 | String result = MapReduce.mapreduce(multipleWordSentence);
20 |
21 | assertEquals("I: 1,Love: 2,HactoberFest: 1", result);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/misc/MedianOfMatrixtest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.misc;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import java.util.ArrayList;
6 | import java.util.Arrays;
7 | import java.util.List;
8 | import org.junit.jupiter.api.Test;
9 |
10 | public class MedianOfMatrixtest {
11 |
12 | @Test
13 | public void testMedianWithOddNumberOfElements() {
14 | List> matrix = new ArrayList<>();
15 | matrix.add(Arrays.asList(1, 3, 5));
16 | matrix.add(Arrays.asList(2, 4, 6));
17 | matrix.add(Arrays.asList(7, 8, 9));
18 |
19 | int result = MedianOfMatrix.median(matrix);
20 |
21 | assertEquals(5, result);
22 | }
23 |
24 | @Test
25 | public void testMedianWithEvenNumberOfElements() {
26 | List> matrix = new ArrayList<>();
27 | matrix.add(Arrays.asList(2, 4));
28 | matrix.add(Arrays.asList(1, 3));
29 |
30 | int result = MedianOfMatrix.median(matrix);
31 |
32 | assertEquals(2, result);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/others/ArrayRightRotation.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | public final class ArrayRightRotation {
4 | private ArrayRightRotation() {
5 | }
6 | public static int[] rotateRight(int[] arr, int k) {
7 | if (arr == null || arr.length == 0 || k < 0) {
8 | throw new IllegalArgumentException("Invalid input");
9 | }
10 |
11 | int n = arr.length;
12 | k = k % n; // Handle cases where k is larger than the array length
13 |
14 | reverseArray(arr, 0, n - 1);
15 | reverseArray(arr, 0, k - 1);
16 | reverseArray(arr, k, n - 1);
17 |
18 | return arr;
19 | }
20 |
21 | private static void reverseArray(int[] arr, int start, int end) {
22 | while (start < end) {
23 | int temp = arr[start];
24 | arr[start] = arr[end];
25 | arr[end] = temp;
26 | start++;
27 | end--;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/others/CRC16Test.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class CRC16Test {
8 | @Test
9 | void testCRC16() {
10 | // given
11 | String textToCRC16 = "hacktoberfest!";
12 |
13 | // when
14 | String resultCRC16 = CRC16.crc16(textToCRC16); // Algorithm CRC16-CCITT-FALSE
15 |
16 | // then
17 | assertEquals("10FC", resultCRC16);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java:
--------------------------------------------------------------------------------
1 |
2 | package com.thealgorithms.others;
3 |
4 | import static org.junit.jupiter.api.Assertions.assertEquals;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class CRCAlgorithmTest {
9 |
10 | @Test
11 | void test1() {
12 | CRCAlgorithm c = new CRCAlgorithm("10010101010100101010010000001010010101010", 10, 0.0);
13 |
14 | // A bit-error rate of 0.0 should not provide any wrong messages
15 | c.changeMess();
16 | c.divideMessageWithP(false);
17 | assertEquals(c.getWrongMess(), 0);
18 | }
19 |
20 | @Test
21 | void test2() {
22 | CRCAlgorithm c = new CRCAlgorithm("10010101010100101010010000001010010101010", 10, 1.0);
23 |
24 | // A bit error rate of 1.0 should not provide any correct messages
25 | c.changeMess();
26 | c.divideMessageWithP(false);
27 | assertEquals(c.getCorrectMess(), 0);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/others/CountCharTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | class CountCharTest {
8 |
9 | @Test
10 | void testCountCharacters() {
11 | String input = "12345";
12 | int expectedValue = 5;
13 |
14 | assertEquals(expectedValue, CountChar.countCharacters(input));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/others/CountSetBitsTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class CountSetBitsTest {
8 |
9 | @Test
10 | void testSetBits() {
11 | CountSetBits csb = new CountSetBits();
12 | assertEquals(1L, csb.countSetBits(16));
13 | assertEquals(4, csb.countSetBits(15));
14 | assertEquals(5, csb.countSetBits(10000));
15 | assertEquals(5, csb.countSetBits(31));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/others/LineSweepTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 | import static org.junit.jupiter.api.Assertions.assertEquals;
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 | public class LineSweepTest {
8 |
9 | @Test
10 | void testForOverlap() {
11 | int[][] arr = {{0, 10}, {7, 20}, {15, 24}};
12 | assertTrue(LineSweep.isOverlap(arr));
13 | }
14 |
15 | @Test
16 | void testForNoOverlap() {
17 | int[][] arr = {{0, 10}, {11, 20}, {21, 24}};
18 | assertFalse(LineSweep.isOverlap(arr));
19 | }
20 | @Test
21 | void testForOverlapWhenEndAEqualsStartBAndViceVersa() {
22 | int[][] arr = {{0, 10}, {10, 20}, {21, 24}};
23 | assertTrue(LineSweep.isOverlap(arr));
24 | }
25 | @Test
26 | void testForMaximumEndPoint() {
27 | int[][] arr = {{10, 20}, {1, 100}, {14, 16}, {1, 8}};
28 | assertEquals(100, LineSweep.findMaximumEndPoint(arr));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class MaximumSumOfDistinctSubarraysWithLengthKTest {
8 | @Test
9 | public void sampleTestCase1() {
10 | assertEquals(15, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(3, 1, 5, 4, 2, 9, 9, 9));
11 | }
12 |
13 | @Test
14 | public void sampleTestCase2() {
15 | assertEquals(0, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(3, 4, 4, 4));
16 | }
17 |
18 | @Test
19 | public void sampleTestCase3() {
20 | assertEquals(12, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(3, 9, 9, 9, 1, 2, 3));
21 | }
22 |
23 | @Test
24 | public void edgeCase1() {
25 | assertEquals(0, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(0, 9, 9, 9));
26 | }
27 |
28 | @Test
29 | public void edgeCase2() {
30 | assertEquals(0, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(5, 9, 9, 9));
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/others/PasswordGenTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertThrows;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class PasswordGenTest {
9 |
10 | @Test
11 | public void failGenerationWithSameMinMaxLengthTest() {
12 | int length = 10;
13 | assertThrows(IllegalArgumentException.class, () -> { PasswordGen.generatePassword(length, length); });
14 | }
15 |
16 | @Test
17 | public void generateOneCharacterPassword() {
18 | String tempPassword = PasswordGen.generatePassword(1, 2);
19 | assertTrue(tempPassword.length() == 1);
20 | }
21 |
22 | @Test
23 | public void failGenerationWithMinLengthSmallerThanMaxLengthTest() {
24 | int minLength = 10;
25 | int maxLength = 5;
26 | assertThrows(IllegalArgumentException.class, () -> { PasswordGen.generatePassword(minLength, maxLength); });
27 | }
28 |
29 | @Test
30 | public void generatePasswordNonEmptyTest() {
31 | String tempPassword = PasswordGen.generatePassword(8, 16);
32 | assertTrue(tempPassword.length() != 0);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertIterableEquals;
4 |
5 | import java.util.List;
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class TestPrintMatrixInSpiralOrder {
9 | @Test
10 | public void testOne() {
11 | int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}};
12 | var printClass = new PrintAMatrixInSpiralOrder();
13 | List res = printClass.print(matrix, matrix.length, matrix[0].length);
14 | List list = List.of(3, 4, 5, 6, 7, 12, 18, 27, 34, 33, 32, 31, 30, 23, 14, 8, 9, 10, 11, 17, 26, 25, 24, 15, 16);
15 | assertIterableEquals(res, list);
16 | }
17 |
18 | @Test
19 | public void testTwo() {
20 | int[][] matrix = {{2, 2}};
21 | var printClass = new PrintAMatrixInSpiralOrder();
22 | List res = printClass.print(matrix, matrix.length, matrix[0].length);
23 | List list = List.of(2, 2);
24 | assertIterableEquals(res, list);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class HowManyTimesRotatedTest {
8 |
9 | @Test
10 | public void testHowManyTimesRotated() {
11 | int[] arr1 = {5, 1, 2, 3, 4};
12 | assertEquals(1, HowManyTimesRotated.rotated(arr1));
13 | int[] arr2 = {15, 17, 2, 3, 5};
14 | assertEquals(2, HowManyTimesRotated.rotated(arr2));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.params.ParameterizedTest;
6 | import org.junit.jupiter.params.provider.CsvSource;
7 |
8 | class RabinKarpAlgorithmTest {
9 |
10 | @ParameterizedTest
11 | @CsvSource({"This is an example for rabin karp algorithmn, algorithmn, 101", "AAABBDDG, AAA, 137", "AAABBCCBB, BBCC, 101", "AAABBCCBB, BBCC, 131", "AAAABBBBCCC, CCC, 41", "ABCBCBCAAB, AADB, 293", "Algorithm The Algorithm, Algorithm, 101"})
12 | void rabinKarpAlgorithmTestExample(String txt, String pat, int q) {
13 | int indexFromOurAlgorithm = RabinKarpAlgorithm.search(pat, txt, q);
14 | int indexFromLinearSearch = txt.indexOf(pat);
15 | assertEquals(indexFromOurAlgorithm, indexFromLinearSearch);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearchTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class SortOrderAgnosticBinarySearchTest {
8 |
9 | @Test
10 | public void testAscending() {
11 | int[] arr = {1, 2, 3, 4, 5}; // for ascending order.
12 | int target = 2;
13 | int ans = SortOrderAgnosticBinarySearch.find(arr, target);
14 | int excepted = 1;
15 | assertEquals(excepted, ans);
16 | }
17 |
18 | @Test
19 | public void testDescending() {
20 | int[] arr = {5, 4, 3, 2, 1}; // for descending order.
21 | int target = 2;
22 | int ans = SortOrderAgnosticBinarySearch.find(arr, target);
23 | int excepted = 3;
24 | assertEquals(excepted, ans);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.searches;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class TestSearchInARowAndColWiseSortedMatrix {
8 | @Test
9 | public void searchItem() {
10 | int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}};
11 |
12 | var test = new SearchInARowAndColWiseSortedMatrix();
13 | int[] res = test.search(matrix, 16);
14 | int[] expectedResult = {2, 2};
15 | assertArrayEquals(expectedResult, res);
16 | }
17 |
18 | @Test
19 | public void notFound() {
20 | int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}};
21 |
22 | var test = new SearchInARowAndColWiseSortedMatrix();
23 | int[] res = test.search(matrix, 96);
24 | int[] expectedResult = {-1, -1};
25 | assertArrayEquals(expectedResult, res);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | class BinaryInsertionSortTest extends SortingAlgorithmTest {
4 | private final BinaryInsertionSort binaryInsertionSort = new BinaryInsertionSort();
5 |
6 | @Override
7 | SortAlgorithm getSortAlgorithm() {
8 | return binaryInsertionSort;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/BitonicSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | public class BitonicSortTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new BitonicSort();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/BubbleSortRecursiveTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | public class BubbleSortRecursiveTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new BubbleSortRecursive();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/CircleSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | class CircleSortTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new CircleSort();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/ExchangeSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | public class ExchangeSortTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new ExchangeSort();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/HeapSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | public class HeapSortTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new HeapSort();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import java.util.Arrays;
6 | import java.util.List;
7 | import org.junit.jupiter.api.Test;
8 |
9 | public class MergeSortRecursiveTest {
10 |
11 | // private MergeSortRecursive mergeSortRecursive = new MergeSortRecursive();
12 |
13 | @Test
14 | void testMergeSortRecursiveCase1() {
15 | MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(5, 12, 9, 3, 15, 88));
16 |
17 | List expected = Arrays.asList(3, 5, 9, 12, 15, 88);
18 | List sorted = mergeSortRecursive.mergeSort();
19 |
20 | assertEquals(expected, sorted);
21 | }
22 |
23 | @Test
24 | void testMergeSortRecursiveCase2() {
25 | MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(-3, 5, 3, 4, 3, 7, 40, -20, 30, 0));
26 |
27 | List expected = Arrays.asList(-20, -3, 0, 3, 3, 4, 5, 7, 30, 40);
28 | List sorted = mergeSortRecursive.mergeSort();
29 |
30 | assertEquals(expected, sorted);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/MergeSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | public class MergeSortTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new MergeSort();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | /**
4 | * @author Tabbygray (https://github.com/Tabbygray)
5 | * @see OddEvenSort
6 | */
7 |
8 | public class OddEvenSortTest extends SortingAlgorithmTest {
9 | private final OddEvenSort oddEvenSort = new OddEvenSort();
10 |
11 | @Override
12 | SortAlgorithm getSortAlgorithm() {
13 | return oddEvenSort;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/QuickSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | /**
4 | * @author Akshay Dubey (https://github.com/itsAkshayDubey)
5 | * @see QuickSort
6 | */
7 | class QuickSortTest extends SortingAlgorithmTest {
8 | @Override
9 | SortAlgorithm getSortAlgorithm() {
10 | return new QuickSort();
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/SelectionSortRecursiveTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | public class SelectionSortRecursiveTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new SelectionSortRecursive();
7 | }
8 |
9 | protected int getGeneratedArraySize() {
10 | return 5000;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | class SelectionSortTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new SelectionSort();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | import static org.assertj.core.api.Assertions.assertThat;
4 |
5 | import org.junit.jupiter.api.RepeatedTest;
6 | import org.junit.jupiter.api.Test;
7 |
8 | class SortUtilsRandomGeneratorTest {
9 |
10 | @RepeatedTest(1000)
11 | void generateArray() {
12 | int size = 1_000;
13 | Double[] doubles = SortUtilsRandomGenerator.generateArray(size);
14 | assertThat(doubles).hasSize(size);
15 | assertThat(doubles).doesNotContainNull();
16 | }
17 |
18 | @Test
19 | void generateArrayEmpty() {
20 | int size = 0;
21 | Double[] doubles = SortUtilsRandomGenerator.generateArray(size);
22 | assertThat(doubles).hasSize(size);
23 | }
24 |
25 | @RepeatedTest(1000)
26 | void generateDouble() {
27 | Double randomDouble = SortUtilsRandomGenerator.generateDouble();
28 | assertThat(randomDouble).isBetween(0.0, 1.0);
29 | assertThat(randomDouble).isNotEqualTo(1.0);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/StrandSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | class StrandSortTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new StrandSort();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/SwapSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | public class SwapSortTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new SwapSort();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/sorts/TimSortTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.sorts;
2 |
3 | class TimSortTest extends SortingAlgorithmTest {
4 | @Override
5 | SortAlgorithm getSortAlgorithm() {
6 | return new TimSort();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/AlphabeticalTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class AlphabeticalTest {
9 |
10 | @Test
11 | public void isAlphabetical() {
12 | // expected to be true
13 | String input1 = "abcdefghijklmno";
14 | String input2 = "abcdxxxyzzzz";
15 | String input3 = "fpw";
16 |
17 | // expected to be false
18 | String input4 = "123a";
19 | String input5 = "abcABC";
20 | String input6 = "abcdefghikjlmno";
21 |
22 | assertTrue(Alphabetical.isAlphabetical(input1));
23 | assertTrue(Alphabetical.isAlphabetical(input2));
24 | assertTrue(Alphabetical.isAlphabetical(input3));
25 |
26 | assertFalse(Alphabetical.isAlphabetical(input4));
27 | assertFalse(Alphabetical.isAlphabetical(input5));
28 | assertFalse(Alphabetical.isAlphabetical(input6));
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/AnagramsTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertTrue;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class AnagramsTest {
8 |
9 | @Test
10 | public void isAlphabetical() {
11 | String input1 = "late";
12 | Anagrams anagrams = new Anagrams();
13 | assertTrue(anagrams.approach1(input1, "tale"));
14 | assertTrue(anagrams.approach1(input1, "teal"));
15 | assertTrue(anagrams.approach2(input1, "tale"));
16 | assertTrue(anagrams.approach2(input1, "teal"));
17 | assertTrue(anagrams.approach3(input1, "tale"));
18 | assertTrue(anagrams.approach3(input1, "teal"));
19 | assertTrue(anagrams.approach4(input1, "tale"));
20 | assertTrue(anagrams.approach4(input1, "teal"));
21 | assertTrue(anagrams.approach5(input1, "teal"));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/CharacterSameTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class CharacterSameTest {
9 |
10 | @Test
11 | public void isAllCharactersSame() {
12 | String input1 = "aaa";
13 | String input2 = "abc";
14 | String input3 = "1 1 1 1";
15 | String input4 = "111";
16 | String input5 = "";
17 | String input6 = " ";
18 | String input7 = ". ";
19 |
20 | assertTrue(CharactersSame.isAllCharactersSame(input1));
21 | assertFalse(CharactersSame.isAllCharactersSame(input2));
22 | assertFalse(CharactersSame.isAllCharactersSame(input3));
23 | assertTrue(CharactersSame.isAllCharactersSame(input4));
24 | assertTrue(CharactersSame.isAllCharactersSame(input5));
25 | assertTrue(CharactersSame.isAllCharactersSame(input6));
26 | assertFalse(CharactersSame.isAllCharactersSame(input7));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/CheckVowelsTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class CheckVowelsTest {
9 |
10 | @Test
11 | public void isVowel() {
12 | assertTrue(CheckVowels.hasVowels("foo"));
13 | assertTrue(CheckVowels.hasVowels("bar"));
14 | assertFalse(CheckVowels.hasVowels("why"));
15 | assertFalse(CheckVowels.hasVowels("myths"));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 | import static org.junit.jupiter.api.Assertions.assertThrows;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class HammingDistanceTest {
9 |
10 | @Test
11 | void testHammingDistance() throws Exception {
12 | assertEquals(HammingDistance.calculateHammingDistance("", ""), 0);
13 | assertEquals(HammingDistance.calculateHammingDistance("java", "java"), 0);
14 | assertEquals(HammingDistance.calculateHammingDistance("karolin", "kathrin"), 3);
15 | assertEquals(HammingDistance.calculateHammingDistance("kathrin", "kerstin"), 4);
16 | assertEquals(HammingDistance.calculateHammingDistance("00000", "11111"), 5);
17 | }
18 |
19 | @Test
20 | void testNotEqualStringLengths() {
21 | Exception exception = assertThrows(Exception.class, () -> HammingDistance.calculateHammingDistance("ab", "abc"));
22 | assertEquals("String lengths must be equal", exception.getMessage());
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/IsomorphicTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public final class IsomorphicTest {
9 | private IsomorphicTest() {
10 | }
11 |
12 | @Test
13 | public static void main(String[] args) {
14 | String str1 = "abbbbaac";
15 | String str2 = "kffffkkd";
16 |
17 | String str3 = "xyxyxy";
18 | String str4 = "bnbnbn";
19 |
20 | String str5 = "ghjknnmm";
21 | String str6 = "wertpopo";
22 |
23 | String str7 = "aaammmnnn";
24 | String str8 = "ggghhhbbj";
25 |
26 | assertTrue(Isomorphic.checkStrings(str1, str2));
27 | assertTrue(Isomorphic.checkStrings(str3, str4));
28 | assertFalse(Isomorphic.checkStrings(str5, str6));
29 | assertFalse(Isomorphic.checkStrings(str7, str8));
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/LongestNonRepeativeSubstringTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class LongestNonRepeativeSubstringTest {
7 |
8 | @Test
9 | public void palindrome() {
10 | String input1 = "HelloWorld";
11 | String input2 = "javaIsAProgrammingLanguage";
12 | Assertions.assertEquals(LongestNonRepeativeSubstring.lengthOfLongestSubstring(input1), 5);
13 | Assertions.assertEquals(LongestNonRepeativeSubstring.lengthOfLongestSubstring(input2), 9);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/LowerTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class LowerTest {
8 | @Test
9 | public void toLowerCase() {
10 | String input1 = "hello world";
11 | String input2 = "HelLO WoRld";
12 | String input3 = "HELLO WORLD";
13 |
14 | assertEquals("hello world", Lower.toLowerCase(input1));
15 | assertEquals("hello world", Lower.toLowerCase(input2));
16 | assertEquals("hello world", Lower.toLowerCase(input3));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/MyAtoiTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class MyAtoiTest {
8 |
9 | @Test
10 | void testOne() {
11 | assertEquals(42, MyAtoi.myAtoi("42"));
12 | }
13 |
14 | @Test
15 | void testTwo() {
16 | assertEquals(-42, MyAtoi.myAtoi(" -42"));
17 | }
18 |
19 | @Test
20 | void testThree() {
21 | assertEquals(4193, MyAtoi.myAtoi("4193 with words"));
22 | }
23 |
24 | @Test
25 | void testFour() {
26 | assertEquals(0, MyAtoi.myAtoi("0"));
27 | }
28 |
29 | @Test
30 | void testFive() {
31 | assertEquals(5678, MyAtoi.myAtoi("5678"));
32 | }
33 |
34 | @Test
35 | void testSix() {
36 | assertEquals(42, MyAtoi.myAtoi("+42"));
37 | }
38 |
39 | @Test
40 | void testSeven() {
41 | assertEquals(0, MyAtoi.myAtoi(" +0 "));
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/PalindromeTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class PalindromeTest {
7 |
8 | @Test
9 | public void palindrome() {
10 |
11 | String[] palindromes = {null, "", "aba", "123321", "kayak"};
12 | for (String s : palindromes) {
13 | Assertions.assertTrue(Palindrome.isPalindrome(s) && Palindrome.isPalindromeRecursion(s) && Palindrome.isPalindromeTwoPointer(s));
14 | }
15 |
16 | String[] notPalindromes = {"abb", "abc", "abc123", "kayaks"};
17 | for (String s : notPalindromes) {
18 | Assertions.assertFalse(Palindrome.isPalindrome(s) || Palindrome.isPalindromeRecursion(s) || Palindrome.isPalindromeTwoPointer(s));
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class ReverseStringRecursiveTest {
8 | @Test
9 | void shouldAcceptWhenEmptyStringIsPassed() {
10 | String expected = "";
11 | String reversed = ReverseStringRecursive.reverse("");
12 |
13 | assertEquals(expected, reversed);
14 | }
15 |
16 | @Test
17 | void shouldAcceptNotWhenWhenSingleCharacterIsPassed() {
18 | String expected = "a";
19 | String reversed = ReverseStringRecursive.reverse("a");
20 |
21 | assertEquals(expected, reversed);
22 | }
23 |
24 | @Test
25 | void shouldAcceptWhenStringIsPassed() {
26 | String expected = "dlroWolleH";
27 | String reversed = ReverseStringRecursive.reverse("HelloWorld");
28 |
29 | assertEquals(expected, reversed);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/ReverseWordsInStringTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import java.util.stream.Stream;
4 | import org.junit.jupiter.api.Assertions;
5 | import org.junit.jupiter.params.ParameterizedTest;
6 | import org.junit.jupiter.params.provider.Arguments;
7 | import org.junit.jupiter.params.provider.MethodSource;
8 |
9 | public class ReverseWordsInStringTest {
10 | @ParameterizedTest
11 | @MethodSource("inputStream")
12 | void numberTests(String expected, String input) {
13 | Assertions.assertEquals(expected, ReverseWordsInString.reverseWordsInString(input));
14 | }
15 |
16 | private static Stream inputStream() {
17 | return Stream.of(Arguments.of("blue is Sky", "Sky is blue"), Arguments.of("blue is Sky", "Sky \n is \t \n blue "), Arguments.of("", ""), Arguments.of("", " "), Arguments.of("", "\t"));
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/RotationTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class RotationTest {
8 |
9 | @Test
10 | public void testRotation() {
11 | assertEquals("eksge", Rotation.rotation("geeks", 2));
12 | assertEquals("anasban", Rotation.rotation("bananas", 3));
13 | assertEquals("abracadabra", Rotation.rotation("abracadabra", 0));
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/StringCompressionTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 | import static org.junit.jupiter.api.Assertions.assertEquals;
3 |
4 | import org.junit.jupiter.params.ParameterizedTest;
5 | import org.junit.jupiter.params.provider.CsvSource;
6 |
7 | public class StringCompressionTest {
8 | @ParameterizedTest
9 | @CsvSource({"a,a", "aabbb,a2b3", "abbbc,ab3c", "aabccd,a2bc2d"})
10 | void stringCompressionTest(String input, String expectedOutput) {
11 | String output = StringCompression.compress(input);
12 | assertEquals(expectedOutput, output);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/UpperTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertEquals;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | public class UpperTest {
8 |
9 | @Test
10 | public void toUpperCase() {
11 | String input1 = "hello world";
12 | String input2 = "hElLo WoRlD";
13 | String input3 = "HELLO WORLD";
14 | assertEquals("HELLO WORLD", Upper.toUpperCase(input1));
15 | assertEquals("HELLO WORLD", Upper.toUpperCase(input2));
16 | assertEquals("HELLO WORLD", Upper.toUpperCase(input3));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings;
2 |
3 | import static org.junit.jupiter.api.Assertions.assertFalse;
4 | import static org.junit.jupiter.api.Assertions.assertTrue;
5 |
6 | import org.junit.jupiter.api.Test;
7 |
8 | public class ValidParenthesesTest {
9 |
10 | @Test
11 | void testOne() {
12 | assertTrue(ValidParentheses.isValid("()"));
13 | }
14 |
15 | @Test
16 | void testTwo() {
17 | assertTrue(ValidParentheses.isValid("()[]{}"));
18 | }
19 |
20 | @Test
21 | void testThree() {
22 | assertFalse(ValidParentheses.isValid("(]"));
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.strings.zigZagPattern;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 |
6 | public class ZigZagPatternTest {
7 |
8 | @Test
9 | public void palindrome() {
10 | String input1 = "HelloWorldFromJava";
11 | String input2 = "javaIsAProgrammingLanguage";
12 | Assertions.assertEquals(ZigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda");
13 | Assertions.assertEquals(ZigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig");
14 | }
15 | }
16 |
--------------------------------------------------------------------------------