> void doSort(
}
/**
- * Ramdomize the array to avoid the basically ordered sequences
+ * Randomize the array to avoid the basically ordered sequences
*
* @param array The array to be sorted
* @param left The first index of an array
From e14b30b88c0de95186fe1937f795b7d8fd3fa8aa Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Sat, 27 May 2023 16:58:56 +0200
Subject: [PATCH 0003/1237] Fix empty input handling in GCD (#4199)
---
src/main/java/com/thealgorithms/maths/GCD.java | 14 +++++++-------
.../java/com/thealgorithms/maths/GCDTest.java | 15 +++++++++++++++
2 files changed, 22 insertions(+), 7 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/GCD.java b/src/main/java/com/thealgorithms/maths/GCD.java
index c05f96332e55..96a2b47dc99d 100644
--- a/src/main/java/com/thealgorithms/maths/GCD.java
+++ b/src/main/java/com/thealgorithms/maths/GCD.java
@@ -33,15 +33,15 @@ public static int gcd(int num1, int num2) {
}
/**
- * get greatest common divisor in array
+ * @brief computes gcd of an array of numbers
*
- * @param number contains number
- * @return gcd
+ * @param numbers the input array
+ * @return gcd of all of the numbers in the input array
*/
- public static int gcd(int[] number) {
- int result = number[0];
- for (int i = 1; i < number.length; i++) { // call gcd function (input two value)
- result = gcd(result, number[i]);
+ public static int gcd(int[] numbers) {
+ int result = 0;
+ for (final var number : numbers) {
+ result = gcd(result, number);
}
return result;
diff --git a/src/test/java/com/thealgorithms/maths/GCDTest.java b/src/test/java/com/thealgorithms/maths/GCDTest.java
index e18d3ea82951..bbf10cad0bdb 100644
--- a/src/test/java/com/thealgorithms/maths/GCDTest.java
+++ b/src/test/java/com/thealgorithms/maths/GCDTest.java
@@ -48,4 +48,19 @@ void test6() {
void test7() {
Assertions.assertEquals(GCD.gcd(9, 6), 3);
}
+
+ @Test
+ void testArrayGcd1() {
+ Assertions.assertEquals(GCD.gcd(new int[]{9, 6}), 3);
+ }
+
+ @Test
+ void testArrayGcd2() {
+ Assertions.assertEquals(GCD.gcd(new int[]{2*3*5*7, 2*5*5*5, 2*5*11, 5*5*5*13}), 5);
+ }
+
+ @Test
+ void testArrayGcdForEmptyInput() {
+ Assertions.assertEquals(GCD.gcd(new int[]{}), 0);
+ }
}
From 4f1514980495c4daaae2eb060228a87e14cbae11 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Sun, 28 May 2023 13:08:44 +0200
Subject: [PATCH 0004/1237] style: handle empty input array in
`FindMin.findMin` (#4205)
* tests: add test case with mininum not being at the beginning
* style: throw IllegalArgumentException when input is empty
* style: use enhanced for loop
* docs: update doc-str
---
.../java/com/thealgorithms/maths/FindMin.java | 18 +++++++++++-------
.../com/thealgorithms/maths/FindMinTest.java | 14 ++++++++++++++
2 files changed, 25 insertions(+), 7 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/FindMin.java b/src/main/java/com/thealgorithms/maths/FindMin.java
index e3be09e34644..7764c1c049b4 100644
--- a/src/main/java/com/thealgorithms/maths/FindMin.java
+++ b/src/main/java/com/thealgorithms/maths/FindMin.java
@@ -24,16 +24,20 @@ public static void main(String[] args) {
}
/**
- * Find the minimum number of an array of numbers.
+ * @brief finds the minimum value stored in the input array
*
- * @param array the array contains element
- * @return min value
+ * @param array the input array
+ * @exception IllegalArgumentException input array is empty
+ * @return the mimum value stored in the input array
*/
public static int findMin(int[] array) {
- int min = array[0];
- for (int i = 1; i < array.length; ++i) {
- if (array[i] < min) {
- min = array[i];
+ if (array.length == 0) {
+ throw new IllegalArgumentException("array must be non-empty.");
+ }
+ int min = Integer.MAX_VALUE;
+ for (final var value : array) {
+ if (value < min) {
+ min = value;
}
}
return min;
diff --git a/src/test/java/com/thealgorithms/maths/FindMinTest.java b/src/test/java/com/thealgorithms/maths/FindMinTest.java
index 48fcb277d96f..dc9835475a08 100644
--- a/src/test/java/com/thealgorithms/maths/FindMinTest.java
+++ b/src/test/java/com/thealgorithms/maths/FindMinTest.java
@@ -1,6 +1,7 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
@@ -23,4 +24,17 @@ public void test1() {
public void test2() {
assertEquals(0, FindMin.findMin(new int[] { 0, 192, 384, 576 }));
}
+
+ @Test
+ public void test3() {
+ assertEquals(0, FindMin.findMin(new int[] { 10, 10, 0, 10 }));
+ }
+
+ @Test
+ public void testFindMinThrowsExceptionForEmptyInput() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> FindMin.findMin(new int[]{})
+ );
+ }
}
From 96c1a96647c947f8f0c531ade3bc18967359e0ea Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Sun, 28 May 2023 22:45:13 +0200
Subject: [PATCH 0005/1237] Fix empty input handling in FindMax (#4206)
---
.../java/com/thealgorithms/maths/FindMax.java | 18 ++++++++-----
.../com/thealgorithms/maths/FindMaxTest.java | 27 ++++++++++++++++++-
2 files changed, 37 insertions(+), 8 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/FindMax.java b/src/main/java/com/thealgorithms/maths/FindMax.java
index a7be8690952b..559424fe15df 100644
--- a/src/main/java/com/thealgorithms/maths/FindMax.java
+++ b/src/main/java/com/thealgorithms/maths/FindMax.java
@@ -24,16 +24,20 @@ public static void main(String[] args) {
}
/**
- * find max of array
+ * @brief finds the maximum value stored in the input array
*
- * @param array the array contains element
- * @return max value of given array
+ * @param array the input array
+ * @exception IllegalArgumentException input array is empty
+ * @return the maximum value stored in the input array
*/
public static int findMax(int[] array) {
- int max = array[0];
- for (int i = 1; i < array.length; ++i) {
- if (array[i] > max) {
- max = array[i];
+ if (array.length == 0) {
+ throw new IllegalArgumentException("array must be non-empty.");
+ }
+ int max = Integer.MIN_VALUE;
+ for (final var value : array) {
+ if (value > max) {
+ max = value;
}
}
return max;
diff --git a/src/test/java/com/thealgorithms/maths/FindMaxTest.java b/src/test/java/com/thealgorithms/maths/FindMaxTest.java
index 43daaeac0f49..a7a18fe198f1 100644
--- a/src/test/java/com/thealgorithms/maths/FindMaxTest.java
+++ b/src/test/java/com/thealgorithms/maths/FindMaxTest.java
@@ -1,16 +1,41 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class FindMaxTest {
@Test
- public void testFindMaxValue() {
+ public void testFindMax0() {
assertEquals(
10,
FindMax.findMax(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })
);
}
+
+ @Test
+ public void testFindMax1() {
+ assertEquals(
+ 7,
+ FindMax.findMax(new int[] { 6, 3, 5, 1, 7, 4, 1 })
+ );
+ }
+
+ @Test
+ public void testFindMax2() {
+ assertEquals(
+ 10,
+ FindMax.findMax(new int[] { 10, 0 })
+ );
+ }
+
+ @Test
+ public void testFindMaxThrowsExceptionForEmptyInput() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> FindMax.findMax(new int[]{})
+ );
+ }
}
From 5d7a59654fc4394162b69ee220c6c079c71a039b Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Mon, 29 May 2023 22:05:23 +0200
Subject: [PATCH 0006/1237] Refactor LowestBasePalindrome (#4207)
---
.../others/LowestBasePalindrome.java | 200 ++++++------------
.../others/LowestBasePalindromeTest.java | 87 ++++++++
2 files changed, 157 insertions(+), 130 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java
diff --git a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
index 3d50b4840f17..addf82554470 100644
--- a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
+++ b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
@@ -1,153 +1,93 @@
package com.thealgorithms.others;
-import java.util.InputMismatchException;
-import java.util.Scanner;
+import java.util.ArrayList;
/**
- * Class for finding the lowest base in which a given integer is a palindrome.
- * Includes auxiliary methods for converting between bases and reversing
- * strings.
- *
- *
- * NOTE: There is potential for error, see note at line 63.
- *
- * @author RollandMichael
- * @version 2017.09.28
+ * @brief Class for finding the lowest base in which a given integer is a palindrome.
+ cf. https://oeis.org/A016026
*/
-public class LowestBasePalindrome {
+final public class LowestBasePalindrome {
+ private LowestBasePalindrome() {
+ }
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = 0;
- while (true) {
- try {
- System.out.print("Enter number: ");
- n = in.nextInt();
- break;
- } catch (InputMismatchException e) {
- System.out.println("Invalid input!");
- in.next();
- }
+ private static void checkBase(int base) {
+ if (base <= 1) {
+ throw new IllegalArgumentException("base must be greater than 1.");
+ }
+ }
+
+ private static void checkNumber(int number) {
+ if (number < 0) {
+ throw new IllegalArgumentException("number must be nonnegative.");
}
- System.out.println(
- n + " is a palindrome in base " + lowestBasePalindrome(n)
- );
- System.out.println(
- base2base(Integer.toString(n), 10, lowestBasePalindrome(n))
- );
- in.close();
}
/**
- * Given a number in base 10, returns the lowest base in which the number is
- * represented by a palindrome (read the same left-to-right and
- * right-to-left).
- *
- * @param num A number in base 10.
- * @return The lowest base in which num is a palindrome.
+ * @brief computes the representation of the input number in given base
+ * @param number the input number
+ * @param base the given base
+ * @exception IllegalArgumentException number is negative or base is less than 2
+ * @return the list containing the digits of the input number in the given base, the most significant digit is at the end of the array
*/
- public static int lowestBasePalindrome(int num) {
- int base, num2 = num;
- int digit;
- char digitC;
- boolean foundBase = false;
- String newNum = "";
- String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
- while (!foundBase) {
- // Try from bases 2 to num-1
- for (base = 2; base < num2; base++) {
- newNum = "";
- while (num > 0) {
- // Obtain the first digit of n in the current base,
- // which is equivalent to the integer remainder of (n/base).
- // The next digit is obtained by dividing n by the base and
- // continuing the process of getting the remainder. This is done
- // until n is <=0 and the number in the new base is obtained.
- digit = (num % base);
- num /= base;
- // If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character
- // form is just its value in ASCII.
+ public static ArrayList computeDigitsInBase(int number, int base) {
+ checkNumber(number);
+ checkBase(base);
+ var result = new ArrayList();
+ while (number > 0) {
+ result.add(number % base);
+ number /= base;
+ }
+ return result;
+ }
- // NOTE: This may cause problems, as the capital letters are ASCII values
- // 65-90. It may cause false positives when one digit is, for instance 10 and assigned
- // 'A' from the character array and the other is 65 and also assigned 'A'.
- // Regardless, the character is added to the representation of n
- // in the current base.
- if (digit >= digits.length()) {
- digitC = (char) (digit);
- newNum += digitC;
- continue;
- }
- newNum += digits.charAt(digit);
- }
- // Num is assigned back its original value for the next iteration.
- num = num2;
- // Auxiliary method reverses the number.
- String reverse = reverse(newNum);
- // If the number is read the same as its reverse, then it is a palindrome.
- // The current base is returned.
- if (reverse.equals(newNum)) {
- foundBase = true;
- return base;
- }
+ /**
+ * @brief checks if the input array is a palindrome
+ * @brief list the input array
+ * @return true, if the input array is a palindrome, false otherwise
+ */
+ public static boolean isPalindromic(ArrayList list) {
+ for (int pos = 0; pos < list.size()/2; ++pos) {
+ if(list.get(pos) != list.get(list.size()-1-pos)) {
+ return false;
}
}
- // If all else fails, n is always a palindrome in base n-1. ("11")
- return num - 1;
+ return true;
}
- private static String reverse(String str) {
- String reverse = "";
- for (int i = str.length() - 1; i >= 0; i--) {
- reverse += str.charAt(i);
+ /**
+ * @brief checks if representation of the input number in given base is a palindrome
+ * @param number the input number
+ * @param base the given base
+ * @exception IllegalArgumentException number is negative or base is less than 2
+ * @return true, if the input number represented in the given base is a palindrome, false otherwise
+ */
+ public static boolean isPalindromicInBase(int number, int base) {
+ checkNumber(number);
+ checkBase(base);
+
+ if (number <= 1) {
+ return true;
}
- return reverse;
- }
- private static String base2base(String n, int b1, int b2) {
- // Declare variables: decimal value of n,
- // character of base b1, character of base b2,
- // and the string that will be returned.
- int decimalValue = 0, charB2;
- char charB1;
- String output = "";
- // Go through every character of n
- for (int i = 0; i < n.length(); i++) {
- // store the character in charB1
- charB1 = n.charAt(i);
- // if it is a non-number, convert it to a decimal value >9 and store it in charB2
- if (charB1 >= 'A' && charB1 <= 'Z') {
- charB2 = 10 + (charB1 - 'A');
- } // Else, store the integer value in charB2
- else {
- charB2 = charB1 - '0';
- }
- // Convert the digit to decimal and add it to the
- // decimalValue of n
- decimalValue = decimalValue * b1 + charB2;
+ if (number % base == 0) {
+ // the last digit of number written in base is 0
+ return false;
}
- // Converting the decimal value to base b2:
- // A number is converted from decimal to another base
- // by continuously dividing by the base and recording
- // the remainder until the quotient is zero. The number in the
- // new base is the remainders, with the last remainder
- // being the left-most digit.
- // While the quotient is NOT zero:
- while (decimalValue != 0) {
- // If the remainder is a digit < 10, simply add it to
- // the left side of the new number.
- if (decimalValue % b2 < 10) {
- output = decimalValue % b2 + output;
- } // If the remainder is >= 10, add a character with the
- // corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
- else {
- output = (char) ((decimalValue % b2) + 55) + output;
- }
- // Divide by the new base again
- decimalValue /= b2;
+ return isPalindromic(computeDigitsInBase(number, base));
+ }
+
+ /**
+ * @brief finds the smallest base for which the representation of the input number is a palindrome
+ * @param number the input number
+ * @exception IllegalArgumentException number is negative
+ * @return the smallest base for which the representation of the input number is a palindrome
+ */
+ public static int lowestBasePalindrome(int number) {
+ int base = 2;
+ while(!isPalindromicInBase(number, base)) {
+ ++base;
}
- return output;
+ return base;
}
}
diff --git a/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java
new file mode 100644
index 000000000000..3124d7b0224f
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java
@@ -0,0 +1,87 @@
+package com.thealgorithms.others;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import org.junit.jupiter.api.Test;
+
+public class LowestBasePalindromeTest {
+ @Test
+ public void testIsPalindromicPositive() {
+ assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList()));
+ assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1))));
+ assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 1))));
+ assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1))));
+ assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 2, 1))));
+ }
+
+ @Test
+ public void testIsPalindromicNegative() {
+ assertFalse(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2))));
+ assertFalse(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1, 1))));
+ }
+
+ @Test
+ public void testIsPalindromicInBasePositive() {
+ assertTrue(LowestBasePalindrome.isPalindromicInBase(101, 10));
+ assertTrue(LowestBasePalindrome.isPalindromicInBase(1, 190));
+ assertTrue(LowestBasePalindrome.isPalindromicInBase(0, 11));
+ assertTrue(LowestBasePalindrome.isPalindromicInBase(10101, 10));
+ assertTrue(LowestBasePalindrome.isPalindromicInBase(23, 22));
+ }
+
+ @Test
+ public void testIsPalindromicInBaseNegative() {
+ assertFalse(LowestBasePalindrome.isPalindromicInBase(1010, 10));
+ assertFalse(LowestBasePalindrome.isPalindromicInBase(123, 10));
+ }
+
+ @Test
+ public void testIsPalindromicInBaseThrowsExceptionForNegativeNumbers() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> LowestBasePalindrome.isPalindromicInBase(-1, 5)
+ );
+ }
+
+ @Test
+ public void testIsPalindromicInBaseThrowsExceptionForWrongBases() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> LowestBasePalindrome.isPalindromicInBase(10, 1)
+ );
+ }
+
+ @Test
+ public void testLowestBasePalindrome() {
+ HashMap testCases = new HashMap<>();
+ testCases.put(0, 2);
+ testCases.put(1, 2);
+ testCases.put(2, 3);
+ testCases.put(3, 2);
+ testCases.put(10, 3);
+ testCases.put(11, 10);
+ testCases.put(15, 2);
+ testCases.put(39, 12);
+ testCases.put(44, 10);
+ testCases.put(58, 28);
+ testCases.put(69, 22);
+ testCases.put(79, 78);
+ testCases.put(87, 28);
+ testCases.put(90, 14);
+ testCases.put(5591, 37);
+ testCases.put(5895, 130);
+ testCases.put(9950, 198);
+ testCases.put(9974, 4986);
+
+ for (final var tc : testCases.entrySet()) {
+ assertEquals(LowestBasePalindrome.lowestBasePalindrome(tc.getKey()), tc.getValue());
+ }
+ }
+}
From b6e78a45ac007570df4da7574b111a05000204d3 Mon Sep 17 00:00:00 2001
From: Bama Charan Chhandogi
Date: Tue, 30 May 2023 13:07:50 +0530
Subject: [PATCH 0007/1237] Add Octal To Binary Converter (#4202)
---
.../conversions/OctalToBinary.java | 42 +++++++++++++++++++
.../conversions/OctalToBinaryTest.java | 15 +++++++
2 files changed, 57 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/conversions/OctalToBinary.java
create mode 100644 src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java
diff --git a/src/main/java/com/thealgorithms/conversions/OctalToBinary.java b/src/main/java/com/thealgorithms/conversions/OctalToBinary.java
new file mode 100644
index 000000000000..711381d82a8e
--- /dev/null
+++ b/src/main/java/com/thealgorithms/conversions/OctalToBinary.java
@@ -0,0 +1,42 @@
+package com.thealgorithms.conversions;
+import java.util.Scanner;
+
+/**
+ * Converts any Octal Number to a Binary Number
+ *
+ * @author Bama Charan Chhandogi
+ */
+
+public class OctalToBinary {
+ public static long convertOctalToBinary(int octalNumber) {
+ long binaryNumber = 0;
+ int digitPosition = 1;
+
+ while (octalNumber != 0) {
+ int octalDigit = octalNumber % 10;
+ long binaryDigit = convertOctalDigitToBinary(octalDigit);
+
+ binaryNumber += binaryDigit * digitPosition;
+
+ octalNumber /= 10;
+ digitPosition *= 1000; // Move to the next group of 3 binary digits
+ }
+
+ return binaryNumber;
+ }
+
+ public static long convertOctalDigitToBinary(int octalDigit) {
+ long binaryDigit = 0;
+ int binaryMultiplier = 1;
+
+ while (octalDigit != 0) {
+ int octalDigitRemainder = octalDigit % 2;
+ binaryDigit += octalDigitRemainder * binaryMultiplier;
+
+ octalDigit /= 2;
+ binaryMultiplier *= 10;
+ }
+
+ return binaryDigit;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java b/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java
new file mode 100644
index 000000000000..6c7fe8702b68
--- /dev/null
+++ b/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java
@@ -0,0 +1,15 @@
+package com.thealgorithms.conversions;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+public class OctalToBinaryTest {
+ @Test
+ public void testConvertOctalToBinary() {
+ assertEquals(101, OctalToBinary.convertOctalToBinary(5));
+ assertEquals(1001, OctalToBinary.convertOctalToBinary(11));
+ assertEquals(101010, OctalToBinary.convertOctalToBinary(52));
+ assertEquals(110, OctalToBinary.convertOctalToBinary(6));
+ }
+}
From 4bbc4bd69f2a68963ba733df744c6ea356aba109 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Wed, 31 May 2023 08:07:55 +0200
Subject: [PATCH 0008/1237] Refactor ReverseNumber (#4208)
---
.../thealgorithms/maths/ReverseNumber.java | 43 ++++++++++---------
.../maths/ReverseNumberTest.java | 33 ++++++++++++++
2 files changed, 55 insertions(+), 21 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/ReverseNumberTest.java
diff --git a/src/main/java/com/thealgorithms/maths/ReverseNumber.java b/src/main/java/com/thealgorithms/maths/ReverseNumber.java
index a78c4de82163..8c74bfdf2132 100644
--- a/src/main/java/com/thealgorithms/maths/ReverseNumber.java
+++ b/src/main/java/com/thealgorithms/maths/ReverseNumber.java
@@ -1,30 +1,31 @@
package com.thealgorithms.maths;
-import java.lang.IllegalStateException;
-import java.util.NoSuchElementException;
-import java.util.Scanner;
+import java.lang.IllegalArgumentException;
-public class ReverseNumber {
-
- public static void main(String[] args) {
- int number;
- int reverse = 0;
+/**
+ * @brief utility class reversing numbers
+ */
+final public class ReverseNumber {
+ private ReverseNumber() {
+ }
- try (Scanner sc = new Scanner(System.in)) {
- System.out.println("Enter a number:");
- number = sc.nextInt();
- } catch (NoSuchElementException | IllegalStateException e) {
- System.out.println("ERROR: Invalid input");
- return;
+ /**
+ * @brief reverses the input number
+ * @param number the input number
+ * @exception IllegalArgumentException number is negative
+ * @return the number created by reversing the order of digits of the input number
+ */
+ public static int reverseNumber(int number) {
+ if (number < 0) {
+ throw new IllegalArgumentException("number must be nonnegative.");
}
- while (number != 0) {
- int remainder = number % 10;
-
- reverse = reverse * 10 + remainder;
- number = number / 10;
+ int result = 0;
+ while (number > 0) {
+ result *= 10;
+ result += number % 10;
+ number /= 10;
}
-
- System.out.println("The reverse of the given number is: " + reverse);
+ return result;
}
}
diff --git a/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java b/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java
new file mode 100644
index 000000000000..a6c25df5a541
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java
@@ -0,0 +1,33 @@
+package com.thealgorithms.maths;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.HashMap;
+
+import org.junit.jupiter.api.Test;
+
+public class ReverseNumberTest {
+
+ @Test
+ public void testReverseNumber() {
+ HashMap testCases = new HashMap<>();
+ testCases.put(0, 0);
+ testCases.put(1, 1);
+ testCases.put(10, 1);
+ testCases.put(123, 321);
+ testCases.put(7890, 987);
+
+ for (final var tc : testCases.entrySet()) {
+ assertEquals(ReverseNumber.reverseNumber(tc.getKey()), tc.getValue());
+ }
+ }
+
+ @Test
+ public void testReverseNumberThrowsExceptionForNegativeInput() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> ReverseNumber.reverseNumber(-1)
+ );
+ }
+}
From 22002c9939fdeff1d7ef659a688ad7f396dd564a Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Fri, 2 Jun 2023 13:17:26 +0200
Subject: [PATCH 0009/1237] Generalize NthUglyNumber (#4209)
---
.../thealgorithms/maths/NthUglyNumber.java | 113 +++++++++++-------
.../maths/NthUglyNumberTest.java | 87 ++++++++++++++
2 files changed, 156 insertions(+), 44 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java
diff --git a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java
index 4c040f570448..6daeb2673cd7 100644
--- a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java
+++ b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java
@@ -1,57 +1,82 @@
-// Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers.
-// By convention, 1 is included.
-// A program to find the nth Ugly number
-// Algorithm :
-// Initialize three-pointers two, three, and five pointing to zero.
-// Take 3 variables nm2, nm3, and nm5 to keep track of next multiple of 2,3 and 5.
-// Make an array of size n to store the ugly numbers with 1 at 0th index.
-// Initialize a variable next which stores the value of the last element in the array.
-// Run a loop n-1 times and perform steps 6,7 and 8.
-// Update the values of nm2, nm3, nm5 as ugly[two]*2, ugly[three]*3, ugly[5]*5 respectively.
-// Select the minimum value from nm2, nm3, and nm5 and increment the pointer related to it.
-// Store the minimum value in variable next and array.
-// Return next.
package com.thealgorithms.maths;
-import java.util.*;
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.lang.IllegalArgumentException;
-class NthUglyNumber {
- /* Function to get the nth ugly number*/
- public long getNthUglyNo(int n) {
- long[] ugly = new long[n];
- int two = 0, three = 0, five = 0;
- long nm2 = 2, nm3 = 3, nm5 = 5;
- long next = 1;
+/**
+ * @brief class computing the n-th ugly number (when they are sorted)
+ * @details the ugly numbers with base [2, 3, 5] are all numbers of the form 2^a*3^b^5^c,
+ * where the exponents a, b, c are non-negative integers.
+ * Some properties of ugly numbers:
+ * - base [2, 3, 5] ugly numbers are the 5-smooth numbers, cf. https://oeis.org/A051037
+ * - base [2, 3, 5, 7] ugly numbers are 7-smooth numbers, cf. https://oeis.org/A002473
+ * - base [2] ugly numbers are the non-negative powers of 2,
+ * - the base [2, 3, 5] ugly numbers are the same as base [5, 6, 2, 3, 5] ugly numbers
+ */
+public class NthUglyNumber {
+ ArrayList uglyNumbers = new ArrayList<>(Arrays.asList(1L));
+ final int[] baseNumbers;
+ HashMap positions = new HashMap<>();
- ugly[0] = 1;
+ /**
+ * @brief initialized the object allowing to compute ugly numbers with given base
+ * @param baseNumbers the given base of ugly numbers
+ * @exception IllegalArgumentException baseNumber is empty
+ */
+ NthUglyNumber(int[] baseNumbers) {
+ if (baseNumbers.length == 0) {
+ throw new IllegalArgumentException("baseNumbers must be non-empty.");
+ }
- for (int i = 1; i < n; i++) {
- next = Math.min(nm2, Math.min(nm3, nm5));
+ this.baseNumbers = baseNumbers;
+ for (final var baseNumber : baseNumbers) {
+ this.positions.put(baseNumber, 0);
+ }
+ }
- ugly[i] = next;
- if (next == nm2) {
- two = two + 1;
- nm2 = ugly[two] * 2;
- }
- if (next == nm3) {
- three = three + 1;
- nm3 = ugly[three] * 3;
- }
- if (next == nm5) {
- five = five + 1;
- nm5 = ugly[five] * 5;
+ /**
+ * @param n the zero-based-index of the queried ugly number
+ * @exception IllegalArgumentException n is negative
+ * @return the n-th ugly number (starting from index 0)
+ */
+ public Long get(int n) {
+ if (n < 0) {
+ throw new IllegalArgumentException("n must be non-negative.");
+ }
+
+ while (uglyNumbers.size() <= n) {
+ addUglyNumber();
+ }
+
+ return uglyNumbers.get(n);
+ }
+
+ private void addUglyNumber() {
+ uglyNumbers.add(computeMinimalCandidate());
+ updatePositions();
+ }
+
+ private void updatePositions() {
+ final var lastUglyNumber = uglyNumbers.get(uglyNumbers.size() - 1);
+ for (final var baseNumber : baseNumbers) {
+ if (computeCandidate(baseNumber) == lastUglyNumber) {
+ positions.put(baseNumber, positions.get(baseNumber) + 1);
}
}
- return next;
}
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the value of n : ");
- int n = sc.nextInt();
- NthUglyNumber ob = new NthUglyNumber();
- long ugly = ob.getNthUglyNo(n);
- System.out.println("nth Ugly number is : " + ugly);
+ private long computeCandidate(int candidateBase) {
+ return candidateBase * uglyNumbers.get(positions.get(candidateBase));
+ }
+
+ private long computeMinimalCandidate() {
+ long res = Long.MAX_VALUE;
+ for (final var baseNumber : baseNumbers) {
+ res = Math.min(res, computeCandidate(baseNumber));
+ }
+ return res;
}
}
diff --git a/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java b/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java
new file mode 100644
index 000000000000..597d08922069
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java
@@ -0,0 +1,87 @@
+package com.thealgorithms.maths;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.HashMap;
+
+import org.junit.jupiter.api.Test;
+
+public class NthUglyNumberTest {
+ @Test
+ public void testGetWithNewObject() {
+ HashMap testCases = new HashMap<>();
+ testCases.put(0, 1L);
+ testCases.put(1, 2L);
+ testCases.put(2, 3L);
+ testCases.put(3, 4L);
+ testCases.put(4, 5L);
+ testCases.put(5, 6L);
+ testCases.put(9, 12L);
+ testCases.put(19, 36L);
+ testCases.put(52, 270L);
+ testCases.put(1078, 84934656L);
+ testCases.put(1963, 6973568802L);
+
+ for (final var tc : testCases.entrySet()) {
+ var uglyNumbers = new NthUglyNumber(new int[] {2, 3, 5});
+ assertEquals(uglyNumbers.get(tc.getKey()), tc.getValue());
+
+ var otherUglyNumbers = new NthUglyNumber(new int[] {5, 25, 6, 2, 3, 5});
+ assertEquals(otherUglyNumbers.get(tc.getKey()), tc.getValue());
+ }
+ }
+
+ @Test
+ public void testGetWithSameObject() {
+ HashMap testCases = new HashMap<>();
+ testCases.put(0, 1L);
+ testCases.put(1, 2L);
+ testCases.put(2, 3L);
+ testCases.put(3, 4L);
+ testCases.put(4, 5L);
+ testCases.put(5, 6L);
+ testCases.put(6, 7L);
+ testCases.put(1499, 1984500L);
+ testCases.put(1572, 2449440L);
+ testCases.put(1658, 3072000L);
+ testCases.put(6625, 4300800000L);
+
+ var uglyNumbers = new NthUglyNumber(new int[] {7, 2, 5, 3});
+ for (final var tc : testCases.entrySet()) {
+ assertEquals(uglyNumbers.get(tc.getKey()), tc.getValue());
+ }
+
+ assertEquals(uglyNumbers.get(999), 385875);
+ }
+
+ @Test
+ public void testGetWithBase1() {
+ var uglyNumbers = new NthUglyNumber(new int[] {1});
+ assertEquals(uglyNumbers.get(10), 1);
+ }
+
+ @Test
+ public void testGetWithBase2() {
+ var uglyNumbers = new NthUglyNumber(new int[] {2});
+ assertEquals(uglyNumbers.get(5), 32);
+ }
+
+
+ @Test
+ public void testGetThrowsAnErrorForNegativeInput() {
+ var uglyNumbers = new NthUglyNumber(new int[] {1, 2});
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> uglyNumbers.get(-1)
+ );
+ }
+
+ @Test
+ public void testConstructorThrowsAnErrorForEmptyInput() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> new NthUglyNumber(new int[] {})
+ );
+ }
+}
From ad03086f547854a4c00b1e3a85dde5d315f119b6 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Fri, 2 Jun 2023 18:28:33 +0200
Subject: [PATCH 0010/1237] Remove main and add tests for CountWords (#4210)
---
.../com/thealgorithms/others/CountWords.java | 47 +++++++++----------
.../thealgorithms/others/CountWordsTest.java | 38 +++++++++++++++
2 files changed, 59 insertions(+), 26 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/others/CountWordsTest.java
diff --git a/src/main/java/com/thealgorithms/others/CountWords.java b/src/main/java/com/thealgorithms/others/CountWords.java
index 2bbfe08ef356..5117b83b7e57 100644
--- a/src/main/java/com/thealgorithms/others/CountWords.java
+++ b/src/main/java/com/thealgorithms/others/CountWords.java
@@ -3,32 +3,34 @@
import java.util.Scanner;
/**
- * You enter a string into this program, and it will return how many words were
- * in that particular string
- *
* @author Marcus
*/
-public class CountWords {
-
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.println("Enter your text: ");
- String str = input.nextLine();
-
- System.out.println("Your text has " + wordCount(str) + " word(s)");
- System.out.println(
- "Your text has " + secondaryWordCount(str) + " word(s)"
- );
- input.close();
+final public class CountWords {
+ private CountWords() {
}
- private static int wordCount(String s) {
+ /**
+ * @brief counts the number of words in the input string
+ * @param s the input string
+ * @return the number of words in the input string
+ */
+ public static int wordCount(String s) {
if (s == null || s.isEmpty()) {
return 0;
}
return s.trim().split("[\\s]+").length;
}
+ private static String removeSpecialCharacters(String s) {
+ StringBuilder sb = new StringBuilder();
+ for (char c : s.toCharArray()) {
+ if (Character.isLetterOrDigit(c) || Character.isWhitespace(c)) {
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+
/**
* counts the number of words in a sentence but ignores all potential
* non-alphanumeric characters that do not represent a word. runs in O(n)
@@ -37,17 +39,10 @@ private static int wordCount(String s) {
* @param s String: sentence with word(s)
* @return int: number of words
*/
- private static int secondaryWordCount(String s) {
- if (s == null || s.isEmpty()) {
+ public static int secondaryWordCount(String s) {
+ if (s == null) {
return 0;
}
- StringBuilder sb = new StringBuilder();
- for (char c : s.toCharArray()) {
- if (Character.isLetter(c) || Character.isDigit(c)) {
- sb.append(c);
- }
- }
- s = sb.toString();
- return s.trim().split("[\\s]+").length;
+ return wordCount(removeSpecialCharacters(s));
}
}
diff --git a/src/test/java/com/thealgorithms/others/CountWordsTest.java b/src/test/java/com/thealgorithms/others/CountWordsTest.java
new file mode 100644
index 000000000000..a2b0c03df220
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/CountWordsTest.java
@@ -0,0 +1,38 @@
+package com.thealgorithms.others;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.HashMap;
+import org.junit.jupiter.api.Test;
+
+
+class CountWordsTest {
+ @Test
+ public void testWordCount() {
+ HashMap testCases = new HashMap<>();
+ testCases.put("", 0);
+ testCases.put(null, 0);
+ testCases.put("aaaa bbb cccc", 3);
+ testCases.put("note extra spaces here", 4);
+ testCases.put(" a b c d e ", 5);
+
+ for (final var tc : testCases.entrySet()) {
+ assertEquals(CountWords.wordCount(tc.getKey()), tc.getValue());
+ }
+ }
+
+ @Test
+ public void testSecondaryWordCount() {
+ HashMap testCases = new HashMap<>();
+ testCases.put("", 0);
+ testCases.put(null, 0);
+ testCases.put("aaaa bbb cccc", 3);
+ testCases.put("this-is-one-word!", 1);
+ testCases.put("What, about, this? Hmmm----strange", 4);
+ testCases.put("word1 word-2 word-3- w?o,r.d.@!@#$&*()<>4", 4);
+
+ for (final var tc : testCases.entrySet()) {
+ assertEquals(CountWords.secondaryWordCount(tc.getKey()), tc.getValue());
+ }
+ }
+}
From 00282efd8becbd0612cc710f49bf21a562deb034 Mon Sep 17 00:00:00 2001
From: acbin <44314231+acbin@users.noreply.github.com>
Date: Fri, 9 Jun 2023 18:52:05 +0800
Subject: [PATCH 0011/1237] style: format code (#4212)
close #4204
---
.../thealgorithms/audiofilters/IIRFilter.java | 20 +-
.../AllPathsFromSourceToTarget.java | 33 +-
.../backtracking/ArrayCombination.java | 2 +-
.../backtracking/Combination.java | 6 +-
.../thealgorithms/backtracking/FloodFill.java | 8 +-
.../backtracking/KnightsTour.java | 41 +--
.../backtracking/MazeRecursion.java | 16 +-
.../thealgorithms/backtracking/NQueens.java | 25 +-
.../thealgorithms/backtracking/PowerSum.java | 22 +-
.../backtracking/WordSearch.java | 16 +-
.../java/com/thealgorithms/ciphers/AES.java | 104 ++----
.../thealgorithms/ciphers/AESEncryption.java | 20 +-
.../thealgorithms/ciphers/AffineCipher.java | 19 +-
.../com/thealgorithms/ciphers/Blowfish.java | 57 +--
.../com/thealgorithms/ciphers/Caesar.java | 15 +-
.../ciphers/ColumnarTranspositionCipher.java | 59 +--
.../java/com/thealgorithms/ciphers/DES.java | 266 ++++++--------
.../com/thealgorithms/ciphers/HillCipher.java | 21 +-
.../com/thealgorithms/ciphers/Polybius.java | 13 +-
.../java/com/thealgorithms/ciphers/RSA.java | 10 +-
.../ciphers/SimpleSubCipher.java | 1 -
.../com/thealgorithms/ciphers/Vigenere.java | 28 +-
.../thealgorithms/ciphers/a5/A5Cipher.java | 3 +-
.../ciphers/a5/A5KeyStreamGenerator.java | 15 +-
.../ciphers/a5/CompositeLFSR.java | 8 +-
.../com/thealgorithms/ciphers/a5/Utils.java | 9 +-
.../conversions/AnyBaseToAnyBase.java | 16 +-
.../conversions/DecimalToAnyBase.java | 17 +-
.../conversions/DecimalToBinary.java | 4 +-
.../thealgorithms/conversions/HexToOct.java | 3 +-
.../conversions/RgbHsvConversion.java | 123 ++-----
.../conversions/TurkishToLatinConversion.java | 7 +-
.../buffers/CircularBuffer.java | 11 +-
.../datastructures/caches/LFUCache.java | 3 +-
.../datastructures/caches/LRUCache.java | 12 +-
.../datastructures/caches/MRUCache.java | 12 +-
.../dynamicarray/DynamicArray.java | 18 +-
.../datastructures/graphs/A_Star.java | 170 ++-------
.../datastructures/graphs/BellmanFord.java | 43 ++-
.../graphs/BipartiteGrapfDFS.java | 15 +-
.../graphs/ConnectedComponent.java | 8 +-
.../datastructures/graphs/Cycles.java | 4 +-
.../graphs/DIJSKSTRAS_ALGORITHM.java | 34 +-
.../datastructures/graphs/FloydWarshall.java | 59 +--
.../graphs/HamiltonianCycle.java | 11 +-
.../datastructures/graphs/KahnsAlgorithm.java | 4 +-
.../datastructures/graphs/Kosaraju.java | 73 ++--
.../datastructures/graphs/Kruskal.java | 38 +-
.../datastructures/graphs/MatrixGraphs.java | 26 +-
.../datastructures/graphs/PrimMST.java | 29 +-
.../graphs/TarjansAlgorithm.java | 58 +--
.../hashmap/hashing/HashMapCuckooHashing.java | 65 +---
.../hashmap/hashing/Intersection.java | 7 +-
.../datastructures/hashmap/hashing/Main.java | 46 ++-
.../hashmap/hashing/MainCuckooHashing.java | 88 ++---
.../hashmap/hashing/MajorityElement.java | 29 +-
.../datastructures/hashmap/hashing/Map.java | 1 -
.../datastructures/heaps/FibonacciHeap.java | 61 ++--
.../datastructures/heaps/GenericHeap.java | 14 +-
.../datastructures/heaps/HeapElement.java | 11 +-
.../datastructures/heaps/LeftistHeap.java | 206 ++++++-----
.../datastructures/heaps/MaxHeap.java | 55 +--
.../datastructures/heaps/MinHeap.java | 55 +--
.../heaps/MinPriorityQueue.java | 15 +-
.../lists/CircleLinkedList.java | 8 +-
.../lists/CursorLinkedList.java | 3 +-
.../lists/DoublyLinkedList.java | 20 +-
.../lists/MergeSortedArrayList.java | 6 +-
.../lists/MergeSortedSinglyLinkedList.java | 9 +-
.../lists/Merge_K_SortedLinkedlist.java | 4 +-
.../datastructures/lists/RandomNode.java | 22 +-
.../SearchSinglyLinkedListRecursion.java | 5 +-
.../lists/SinglyLinkedList.java | 34 +-
.../datastructures/lists/SkipList.java | 43 +--
.../datastructures/queues/CircularQueue.java | 7 +-
.../datastructures/queues/LinkedQueue.java | 13 +-
.../datastructures/queues/PriorityQueues.java | 7 +-
.../stacks/BalancedBrackets.java | 44 +--
.../stacks/CalculateMaxOfMin.java | 8 +-
.../stacks/DecimalToAnyUsingStack.java | 7 +-
.../stacks/DuplicateBrackets.java | 3 +-
.../datastructures/stacks/InfixToPostfix.java | 28 +-
.../stacks/LargestRectangle.java | 7 +-
.../stacks/MaximumMinimumWindow.java | 4 +-
.../stacks/NextGraterElement.java | 5 +-
.../stacks/NextSmallerElement.java | 24 +-
.../datastructures/stacks/NodeStack.java | 3 +-
.../datastructures/stacks/PostfixToInfix.java | 22 +-
.../datastructures/stacks/ReverseStack.java | 19 +-
.../stacks/StackOfLinkedList.java | 8 +-
.../datastructures/trees/AVLSimple.java | 46 +--
.../trees/BSTRecursiveGeneric.java | 34 +-
.../datastructures/trees/BinaryTree.java | 6 +-
.../trees/CheckBinaryTreeIsValidBST.java | 4 +-
.../trees/CheckIfBinaryTreeBalanced.java | 17 +-
.../trees/CheckTreeIsSymmetric.java | 6 +-
.../CreateBinaryTreeFromInorderPreorder.java | 59 +--
.../datastructures/trees/GenericTree.java | 4 +-
.../datastructures/trees/KDTree.java | 118 +++---
.../datastructures/trees/LCA.java | 23 +-
.../datastructures/trees/LazySegmentTree.java | 32 +-
.../datastructures/trees/RedBlackBST.java | 20 +-
.../datastructures/trees/SameTreesCheck.java | 5 +-
.../datastructures/trees/SegmentTree.java | 30 +-
.../datastructures/trees/TreeRandomNode.java | 18 +-
.../datastructures/trees/TrieImp.java | 89 +++--
.../trees/VerticalOrderTraversal.java | 38 +-
.../datastructures/trees/ZigzagTraversal.java | 3 +-
.../datastructures/trees/nearestRightKey.java | 2 +-
.../devutils/entities/ProcessDetails.java | 1 -
.../devutils/nodes/LargeTreeNode.java | 5 +-
.../thealgorithms/devutils/nodes/Node.java | 3 +-
.../devutils/nodes/SimpleTreeNode.java | 8 +-
.../BinaryExponentiation.java | 2 +-
.../divideandconquer/ClosestPair.java | 20 +-
.../divideandconquer/SkylineAlgorithm.java | 15 +-
.../StrassenMatrixMultiplication.java | 11 +-
.../dynamicprogramming/BoardPath.java | 20 +-
.../dynamicprogramming/BoundaryFill.java | 124 ++-----
.../BruteForceKnapsack.java | 9 +-
.../dynamicprogramming/CatalanNumber.java | 4 +-
.../dynamicprogramming/ClimbingStairs.java | 7 +-
.../dynamicprogramming/CoinChange.java | 23 +-
.../CountFriendsPairing.java | 6 +-
.../dynamicprogramming/DiceThrow.java | 11 +-
.../DyanamicProgrammingKnapsack.java | 4 +-
.../dynamicprogramming/EditDistance.java | 11 +-
.../dynamicprogramming/EggDropping.java | 4 +-
.../dynamicprogramming/Fibonacci.java | 25 +-
.../dynamicprogramming/FordFulkerson.java | 15 +-
.../dynamicprogramming/KadaneAlgorithm.java | 3 +-
.../dynamicprogramming/Knapsack.java | 13 +-
.../KnapsackMemoization.java | 13 +-
.../LevenshteinDistance.java | 13 +-
.../LongestAlternatingSubsequence.java | 34 +-
.../LongestCommonSubsequence.java | 6 +-
.../LongestIncreasingSubsequence.java | 4 +-
.../LongestPalindromicSubsequence.java | 37 +-
.../LongestValidParentheses.java | 5 +-
.../MatrixChainMultiplication.java | 11 +-
...atrixChainRecursiveTopDownMemoisation.java | 16 +-
.../dynamicprogramming/MinimumPathSum.java | 8 +-
.../MinimumSumPartition.java | 6 +-
.../dynamicprogramming/NewManShanksPrime.java | 3 +-
.../OptimalJobScheduling.java | 58 +--
.../PalindromicPartitioning.java | 26 +-
.../dynamicprogramming/PartitionProblem.java | 12 +-
.../dynamicprogramming/RegexMatching.java | 19 +-
.../dynamicprogramming/RodCutting.java | 2 +-
.../ShortestCommonSupersequenceLength.java | 7 +-
.../dynamicprogramming/SubsetCount.java | 58 ++-
.../dynamicprogramming/SubsetSum.java | 2 +-
.../dynamicprogramming/Sum_Of_Subset.java | 2 +-
.../dynamicprogramming/UniquePaths.java | 18 +-
.../dynamicprogramming/WineProblem.java | 6 +-
.../thealgorithms/geometry/GrahamScan.java | 168 +++++----
.../com/thealgorithms/io/BufferedReader.java | 342 +++++++++---------
.../com/thealgorithms/maths/ADTFraction.java | 10 +-
.../com/thealgorithms/maths/AbsoluteMin.java | 7 +-
.../com/thealgorithms/maths/AliquotSum.java | 20 +-
.../thealgorithms/maths/AmicableNumber.java | 36 +-
.../java/com/thealgorithms/maths/Area.java | 3 +-
.../maths/AutomorphicNumber.java | 12 +-
.../maths/BinomialCoefficient.java | 14 +-
.../maths/CircularConvolutionFFT.java | 10 +-
.../com/thealgorithms/maths/Convolution.java | 5 +-
.../thealgorithms/maths/ConvolutionFFT.java | 11 +-
.../maths/DeterminantOfMatrix.java | 4 +-
.../com/thealgorithms/maths/DigitalRoot.java | 16 +-
.../thealgorithms/maths/DistanceFormula.java | 14 +-
.../thealgorithms/maths/DudeneyNumber.java | 6 +-
.../com/thealgorithms/maths/EulerMethod.java | 47 +--
.../java/com/thealgorithms/maths/FFT.java | 17 +-
.../com/thealgorithms/maths/FFTBluestein.java | 19 +-
.../com/thealgorithms/maths/Factorial.java | 3 +-
.../thealgorithms/maths/FastInverseSqrt.java | 19 +-
.../maths/FibonacciJavaStreams.java | 54 +--
.../thealgorithms/maths/FindMaxRecursion.java | 10 +-
.../thealgorithms/maths/FindMinRecursion.java | 10 +-
.../com/thealgorithms/maths/FrizzyNumber.java | 9 +-
.../java/com/thealgorithms/maths/GCD.java | 8 +-
.../com/thealgorithms/maths/Gaussian.java | 17 +-
.../com/thealgorithms/maths/GenericRoot.java | 3 +-
.../thealgorithms/maths/HarshadNumber.java | 6 +-
.../thealgorithms/maths/JosephusProblem.java | 18 +-
.../thealgorithms/maths/JugglerSequence.java | 5 +-
.../thealgorithms/maths/KaprekarNumbers.java | 39 +-
.../com/thealgorithms/maths/KeithNumber.java | 31 +-
.../maths/KrishnamurthyNumber.java | 34 +-
.../maths/LeastCommonMultiple.java | 4 +-
.../thealgorithms/maths/LeonardoNumber.java | 6 +-
.../LinearDiophantineEquationsSolver.java | 52 +--
.../maths/LiouvilleLambdaFunction.java | 8 +-
.../com/thealgorithms/maths/LongDivision.java | 18 +-
.../com/thealgorithms/maths/LucasSeries.java | 4 +-
.../com/thealgorithms/maths/MagicSquare.java | 10 +-
.../com/thealgorithms/maths/MatrixUtil.java | 173 ++++-----
.../java/com/thealgorithms/maths/Median.java | 5 +-
.../thealgorithms/maths/MobiusFunction.java | 18 +-
.../java/com/thealgorithms/maths/Mode.java | 17 +-
.../maths/NonRepeatingElement.java | 39 +-
.../thealgorithms/maths/NthUglyNumber.java | 5 +-
.../thealgorithms/maths/NumberOfDigits.java | 4 +-
.../com/thealgorithms/maths/ParseInteger.java | 6 +-
.../thealgorithms/maths/PascalTriangle.java | 26 +-
.../com/thealgorithms/maths/PerfectCube.java | 2 +-
.../thealgorithms/maths/PerfectNumber.java | 18 +-
.../com/thealgorithms/maths/Perimeter.java | 17 +-
.../com/thealgorithms/maths/PiNilakantha.java | 14 +-
.../com/thealgorithms/maths/PollardRho.java | 28 +-
.../com/thealgorithms/maths/PrimeCheck.java | 8 +-
.../com/thealgorithms/maths/PronicNumber.java | 9 +-
.../thealgorithms/maths/RomanNumeralUtil.java | 23 +-
.../maths/SimpsonIntegration.java | 10 +-
.../maths/SquareFreeInteger.java | 35 +-
.../SquareRootWithNewtonRaphsonMethod.java | 10 +-
.../maths/SumOfArithmeticSeries.java | 10 +-
.../com/thealgorithms/maths/SumOfDigits.java | 18 +-
.../maths/SumWithoutArithmeticOperators.java | 22 +-
.../maths/TrinomialTriangle.java | 5 +-
.../com/thealgorithms/maths/TwinPrime.java | 31 +-
.../thealgorithms/maths/VampireNumber.java | 26 +-
.../maths/VectorCrossProduct.java | 8 +-
.../matrixexponentiation/Fibonacci.java | 37 +-
.../MinimizingLateness.java | 16 +-
.../misc/ColorContrastRatio.java | 39 +-
.../thealgorithms/misc/InverseOfMatrix.java | 3 +-
.../misc/MedianOfRunningArray.java | 2 +-
.../thealgorithms/misc/PalindromePrime.java | 4 +-
.../misc/RangeInSortedArray.java | 41 +--
.../java/com/thealgorithms/misc/Sort012D.java | 38 +-
.../java/com/thealgorithms/misc/Sparcity.java | 12 +-
.../thealgorithms/misc/ThreeSumProblem.java | 11 +-
.../com/thealgorithms/misc/WordBoggle.java | 93 ++---
.../java/com/thealgorithms/others/BFPRT.java | 3 +-
.../others/BankersAlgorithm.java | 55 +--
.../com/thealgorithms/others/BoyerMoore.java | 3 +-
.../java/com/thealgorithms/others/CRC16.java | 33 +-
.../java/com/thealgorithms/others/Conway.java | 15 +-
.../java/com/thealgorithms/others/Damm.java | 31 +-
.../com/thealgorithms/others/Dijkstra.java | 33 +-
.../thealgorithms/others/FloydTriangle.java | 4 +-
.../thealgorithms/others/HappyNumbersSeq.java | 5 +-
.../com/thealgorithms/others/Huffman.java | 15 +-
...g_auto_completing_features_using_trie.java | 8 +-
.../others/InsertDeleteInArray.java | 4 +-
.../thealgorithms/others/KochSnowflake.java | 44 +--
.../com/thealgorithms/others/LineSweep.java | 22 +-
.../others/LinearCongruentialGenerator.java | 19 +-
.../others/LowestBasePalindrome.java | 15 +-
.../java/com/thealgorithms/others/Luhn.java | 41 +--
.../com/thealgorithms/others/Mandelbrot.java | 97 ++---
.../others/MemoryManagementAlgorithms.java | 106 +++---
.../others/MiniMaxAlgorithm.java | 22 +-
.../com/thealgorithms/others/PageRank.java | 56 +--
.../com/thealgorithms/others/PasswordGen.java | 6 +-
.../com/thealgorithms/others/PerlinNoise.java | 35 +-
.../others/PrintAMatrixInSpiralOrder.java | 3 -
.../others/QueueUsingTwoStacks.java | 3 +-
.../com/thealgorithms/others/RabinKarp.java | 23 +-
.../others/RemoveDuplicateFromString.java | 8 +-
.../others/ReturnSubsequence.java | 18 +-
.../others/SieveOfEratosthenes.java | 6 +-
.../thealgorithms/others/SkylineProblem.java | 10 +-
.../java/com/thealgorithms/others/Sudoku.java | 18 +-
.../com/thealgorithms/others/TopKWords.java | 7 +-
.../thealgorithms/others/TowerOfHanoi.java | 15 +-
.../com/thealgorithms/others/Verhoeff.java | 51 ++-
.../others/cn/HammingDistance.java | 9 +-
.../thealgorithms/others/countSetBits.java | 28 +-
.../scheduling/FCFSScheduling.java | 22 +-
.../scheduling/RRScheduling.java | 43 ++-
.../scheduling/SJFScheduling.java | 92 ++---
.../thealgorithms/searches/BinarySearch.java | 30 +-
.../searches/BinarySearch2dArray.java | 93 ++---
.../searches/DepthFirstSearch.java | 29 +-
.../searches/ExponentalSearch.java | 30 +-
.../searches/FibonacciSearch.java | 14 +-
.../searches/HowManyTimesRotated.java | 20 +-
.../searches/InterpolationSearch.java | 27 +-
.../searches/IterativeBinarySearch.java | 21 +-
.../searches/IterativeTernarySearch.java | 21 +-
.../thealgorithms/searches/JumpSearch.java | 2 +-
.../com/thealgorithms/searches/KMPSearch.java | 8 +-
.../thealgorithms/searches/LinearSearch.java | 15 +-
.../searches/LinearSearchThread.java | 6 +-
.../thealgorithms/searches/LowerBound.java | 30 +-
.../searches/MonteCarloTreeSearch.java | 37 +-
.../searches/OrderAgnosticBinarySearch.java | 69 ++--
.../searches/PerfectBinarySearch.java | 2 +-
.../thealgorithms/searches/QuickSelect.java | 30 +-
.../searches/RabinKarpAlgorithm.java | 2 +-
...owColumnWiseSorted2dArrayBinarySearch.java | 53 +--
.../searches/SaddlebackSearch.java | 2 +-
.../SearchInARowAndColWiseSortedMatrix.java | 3 +-
.../searches/SquareRootBinarySearch.java | 4 +-
.../thealgorithms/searches/TernarySearch.java | 38 +-
.../com/thealgorithms/searches/UnionFind.java | 16 +-
.../thealgorithms/searches/UpperBound.java | 30 +-
.../sortOrderAgnosticBinarySearch.java | 36 +-
.../com/thealgorithms/sorts/BeadSort.java | 45 ++-
.../com/thealgorithms/sorts/BitonicSort.java | 2 +-
.../com/thealgorithms/sorts/BogoSort.java | 4 +-
.../sorts/BubbleSortRecursion.java | 5 +-
.../com/thealgorithms/sorts/BucketSort.java | 2 +-
.../com/thealgorithms/sorts/CircleSort.java | 13 +-
.../sorts/CocktailShakerSort.java | 4 +-
.../com/thealgorithms/sorts/CountingSort.java | 20 +-
.../java/com/thealgorithms/sorts/DNFSort.java | 40 +-
.../sorts/DualPivotQuickSort.java | 20 +-
.../sorts/DutchNationalFlagSort.java | 25 +-
.../thealgorithms/sorts/InsertionSort.java | 18 +-
.../com/thealgorithms/sorts/LinkListSort.java | 181 +++++----
.../com/thealgorithms/sorts/MergeSort.java | 3 +-
.../sorts/MergeSortNoExtraSpace.java | 12 +-
.../sorts/MergeSortRecursive.java | 24 +-
.../com/thealgorithms/sorts/OddEvenSort.java | 2 +-
.../thealgorithms/sorts/PigeonholeSort.java | 2 +-
.../com/thealgorithms/sorts/QuickSort.java | 18 +-
.../com/thealgorithms/sorts/RadixSort.java | 2 +-
.../thealgorithms/sorts/SelectionSort.java | 4 +-
.../com/thealgorithms/sorts/ShellSort.java | 2 +-
.../com/thealgorithms/sorts/SimpleSort.java | 2 +-
.../thealgorithms/sorts/SortAlgorithm.java | 6 +-
.../com/thealgorithms/sorts/SortUtils.java | 4 +-
.../sorts/SortUtilsRandomGenerator.java | 5 +-
.../com/thealgorithms/sorts/StoogeSort.java | 10 +-
.../com/thealgorithms/sorts/StrandSort.java | 21 +-
.../com/thealgorithms/sorts/SwapSort.java | 10 +-
.../java/com/thealgorithms/sorts/TimSort.java | 4 +-
.../thealgorithms/sorts/TopologicalSort.java | 42 +--
.../com/thealgorithms/sorts/TreeSort.java | 16 +-
.../com/thealgorithms/sorts/WiggleSort.java | 35 +-
.../thealgorithms/strings/Alphabetical.java | 5 +-
.../com/thealgorithms/strings/Anagrams.java | 55 +--
.../thealgorithms/strings/CheckVowels.java | 5 +-
.../strings/HammingDistance.java | 7 +-
.../thealgorithms/strings/HorspoolSearch.java | 19 +-
.../LetterCombinationsOfPhoneNumber.java | 25 +-
.../strings/LongestPalindromicSubstring.java | 4 +-
.../java/com/thealgorithms/strings/Lower.java | 7 +-
.../com/thealgorithms/strings/MyAtoi.java | 27 +-
.../com/thealgorithms/strings/Palindrome.java | 4 +-
.../com/thealgorithms/strings/Pangram.java | 2 +-
.../thealgorithms/strings/PermuteString.java | 16 +-
.../strings/ReverseStringRecursive.java | 7 +-
.../strings/StringCompression.java | 104 +++---
.../java/com/thealgorithms/strings/Upper.java | 7 +-
.../strings/ValidParentheses.java | 56 ++-
.../com/thealgorithms/strings/WordLadder.java | 14 +-
.../strings/longestNonRepeativeSubstring.java | 3 +-
.../strings/zigZagPattern/zigZagPattern.java | 12 +-
.../AllPathsFromSourceToTargetTest.java | 41 ++-
.../backtracking/CombinationTest.java | 15 +-
.../backtracking/FloodFillTest.java | 72 ++--
.../backtracking/MazeRecursionTest.java | 34 +-
.../backtracking/PermutationTest.java | 10 +-
.../backtracking/PowerSumTest.java | 4 +-
.../backtracking/WordSearchTest.java | 6 +-
.../thealgorithms/ciphers/BlowfishTest.java | 12 +-
.../com/thealgorithms/ciphers/CaesarTest.java | 5 +-
.../com/thealgorithms/ciphers/DESTest.java | 45 ++-
.../com/thealgorithms/ciphers/RSATest.java | 5 +-
.../ciphers/SimpleSubCipherTest.java | 5 +-
.../ciphers/SimpleSubstitutionCipherTest.java | 4 +-
.../thealgorithms/ciphers/VigenereTest.java | 5 +-
.../thealgorithms/ciphers/a5/LFSRTest.java | 8 +-
.../conversions/BinaryToDecimalTest.java | 4 +-
.../conversions/HexaDecimalToBinaryTest.java | 5 +-
.../conversions/HexaDecimalToDecimalTest.java | 6 +-
.../conversions/RomanToIntegerTest.java | 4 +-
.../buffers/CircularBufferTest.java | 24 +-
.../datastructures/caches/LFUCacheTest.java | 20 +-
.../graphs/HamiltonianCycleTest.java | 34 +-
.../datastructures/graphs/KosarajuTest.java | 12 +-
.../graphs/TarjansAlgorithmTest.java | 14 +-
.../hashmap/HashMapCuckooHashingTest.java | 2 +-
.../hashmap/hashing/MajorityElementTest.java | 13 +-
.../hashmap/hashing/MapTest.java | 5 +-
.../datastructures/heaps/LeftistHeapTest.java | 42 +--
.../lists/SinglyLinkedListTest.java | 120 +++---
.../datastructures/lists/SkipListTest.java | 10 +-
.../queues/LinkedQueueTest.java | 33 +-
.../queues/PriorityQueuesTest.java | 4 +-
.../trees/BSTFromSortedArrayTest.java | 6 +-
.../datastructures/trees/BinaryTreeTest.java | 120 +++---
.../trees/CeilInBinarySearchTreeTest.java | 18 +-
.../trees/CheckBinaryTreeIsValidBSTTest.java | 15 +-
.../trees/CheckTreeIsSymmetricTest.java | 11 +-
...eateBinaryTreeFromInorderPreorderTest.java | 21 +-
.../trees/InorderTraversalTest.java | 10 +-
.../datastructures/trees/KDTreeTest.java | 38 +-
.../trees/LazySegmentTreeTest.java | 21 +-
.../trees/LevelOrderTraversalTest.java | 16 +-
.../trees/PostOrderTraversalTest.java | 10 +-
.../trees/PreOrderTraversalTest.java | 10 +-
.../trees/SameTreesCheckTest.java | 24 +-
.../datastructures/trees/TreeTestUtils.java | 2 +-
.../trees/VerticalOrderTraversalTest.java | 14 +-
.../trees/ZigzagTraversalTest.java | 16 +-
.../BinaryExponentiationTest.java | 1 -
.../StrassenMatrixMultiplicationTest.java | 21 +-
.../dynamicprogramming/EggDroppingTest.java | 20 +-
.../KnapsackMemoizationTest.java | 16 +-
.../LevenshteinDistanceTests.java | 5 +-
.../OptimalJobSchedulingTest.java | 102 ++----
.../PartitionProblemTest.java | 20 +-
.../dynamicprogramming/SubsetCountTest.java | 19 +-
.../dynamicprogramming/climbStairsTest.java | 23 +-
.../geometry/GrahamScanTest.java | 9 +-
.../thealgorithms/io/BufferedReaderTest.java | 177 +++++----
.../thealgorithms/maths/ADTFractionTest.java | 6 +-
.../thealgorithms/maths/AbsoluteMinTest.java | 6 +-
.../maths/AbsoluteValueTest.java | 10 +-
.../com/thealgorithms/maths/AreaTest.java | 70 ++--
.../maths/AutomorphicNumberTest.java | 11 +-
.../com/thealgorithms/maths/AverageTest.java | 1 -
.../maths/CollatzConjectureTest.java | 27 +-
.../maths/DistanceFormulaTest.java | 62 +---
.../maths/DudeneyNumberTest.java | 5 +-
.../com/thealgorithms/maths/FindMaxTest.java | 20 +-
.../com/thealgorithms/maths/FindMinTest.java | 16 +-
.../thealgorithms/maths/FrizzyNumberTest.java | 40 +-
.../java/com/thealgorithms/maths/GCDTest.java | 28 +-
.../maths/HarshadNumberTest.java | 3 +-
.../maths/HeronsFormulaTest.java | 10 +-
.../maths/KaprekarNumbersTest.java | 6 +-
.../maths/LeonardoNumberTest.java | 7 +-
.../maths/LiouvilleLambdaFunctionTest.java | 40 +-
.../thealgorithms/maths/LongDivisionTest.java | 35 +-
.../thealgorithms/maths/LucasSeriesTest.java | 3 +-
.../com/thealgorithms/maths/MedianTest.java | 3 +-
.../maths/MobiusFunctionTest.java | 30 +-
.../maths/NthUglyNumberTest.java | 14 +-
.../maths/PascalTriangleTest.java | 30 +-
.../maths/PerfectNumberTest.java | 5 +-
.../maths/PerfectSquareTest.java | 6 +-
.../thealgorithms/maths/PerimeterTest.java | 2 +-
.../thealgorithms/maths/PollardRhoTest.java | 26 +-
.../maths/PrimeFactorizationTest.java | 10 +-
.../thealgorithms/maths/PronicNumberTest.java | 12 +-
.../maths/ReverseNumberTest.java | 6 +-
.../maths/SquareFreeIntegerTest.java | 181 ++++++---
...SquareRootWithNewtonRaphsonTestMethod.java | 15 +-
.../SquareRootwithBabylonianMethodTest.java | 20 +-
.../maths/StandardDeviationTest.java | 21 +-
.../maths/StandardScoreTest.java | 5 +-
.../SumWithoutArithmeticOperatorsTest.java | 33 +-
.../thealgorithms/maths/TwinPrimeTest.java | 102 +++---
.../com/thealgorithms/maths/VolumeTest.java | 1 +
.../others/ArrayLeftRotationTest.java | 14 +-
.../thealgorithms/others/BestFitCPUTest.java | 30 +-
.../com/thealgorithms/others/CRC16Test.java | 5 +-
.../others/CRCAlgorithmTest.java | 12 +-
.../others/CalculateMaxOfMinTest.java | 14 +-
.../com/thealgorithms/others/ConwayTest.java | 27 +-
.../thealgorithms/others/CountCharTest.java | 7 +-
.../others/CountFriendsPairingTest.java | 16 +-
.../thealgorithms/others/CountWordsTest.java | 1 -
.../thealgorithms/others/FirstFitCPUTest.java | 30 +-
.../others/KadaneAlogrithmTest.java | 16 +-
.../thealgorithms/others/LineSweepTest.java | 21 +-
.../others/LinkListSortTest.java | 16 +-
.../others/LowestBasePalindromeTest.java | 25 +-
.../com/thealgorithms/others/NextFitTest.java | 30 +-
.../thealgorithms/others/PasswordGenTest.java | 16 +-
.../others/TestPrintMatrixInSpiralOrder.java | 21 +-
.../thealgorithms/others/TwoPointersTest.java | 33 +-
.../thealgorithms/others/WorstFitCPUTest.java | 39 +-
.../others/cn/HammingDistanceTest.java | 19 +-
.../scheduling/FCFSSchedulingTest.java | 10 +-
.../scheduling/RRSchedulingTest.java | 7 +-
.../scheduling/SJFSchedulingTest.java | 143 ++++----
.../searches/BinarySearch2dArrayTest.java | 48 +--
.../searches/BreadthFirstSearchTest.java | 27 +-
.../searches/HowManyTimesRotatedTest.java | 5 +-
.../OrderAgnosticBinarySearchTest.java | 119 +++---
.../searches/QuickSelectTest.java | 34 +-
...lumnWiseSorted2dArrayBinarySearchTest.java | 196 +++++-----
...estSearchInARowAndColWiseSortedMatrix.java | 23 +-
.../sortOrderAgnosticBinarySearchTest.java | 19 +-
.../com/thealgorithms/sorts/BeadSortTest.java | 14 +-
.../sorts/BinaryInsertionSortTest.java | 8 +-
.../com/thealgorithms/sorts/BogoSortTest.java | 30 +-
.../thealgorithms/sorts/BubbleSortTest.java | 10 +-
.../thealgorithms/sorts/BucketSortTest.java | 16 +-
.../sorts/CocktailShakerSortTest.java | 14 +-
.../com/thealgorithms/sorts/CombSortTest.java | 62 ++--
.../sorts/DualPivotQuickSortTest.java | 21 +-
.../sorts/DutchNationalFlagSortTest.java | 32 +-
.../sorts/InsertionSortTest.java | 7 +-
.../sorts/IntrospectiveSortTest.java | 9 +-
.../sorts/MergeSortRecursiveTest.java | 46 +--
.../thealgorithms/sorts/OddEvenSortTest.java | 7 +-
.../sorts/SelectionSortTest.java | 14 +-
.../thealgorithms/sorts/ShellSortTest.java | 31 +-
.../thealgorithms/sorts/SimpleSortTest.java | 30 +-
.../com/thealgorithms/sorts/SlowSortTest.java | 6 +-
.../sorts/SortUtilsRandomGeneratorTest.java | 4 +-
.../thealgorithms/sorts/SortUtilsTest.java | 5 +-
.../sorts/SortingAlgorithmTest.java | 31 +-
.../thealgorithms/sorts/StrandSortTest.java | 14 +-
.../com/thealgorithms/sorts/TimSortTest.java | 4 +-
.../sorts/TopologicalSortTest.java | 11 +-
.../com/thealgorithms/sorts/TreeSortTest.java | 56 +--
.../thealgorithms/sorts/WiggleSortTest.java | 28 +-
.../strings/HammingDistanceTest.java | 24 +-
.../strings/HorspoolSearchTest.java | 11 +-
.../LetterCombinationsOfPhoneNumberTest.java | 15 +-
.../com/thealgorithms/strings/LowerTest.java | 6 +-
.../com/thealgorithms/strings/MyAtoiTest.java | 12 +-
.../thealgorithms/strings/PalindromeTest.java | 15 +-
.../thealgorithms/strings/PangramTest.java | 9 +-
.../strings/ReverseStringRecursiveTest.java | 16 +-
.../strings/ReverseStringTest.java | 4 +-
.../thealgorithms/strings/RotationTest.java | 2 +-
.../strings/StringCompressionTest.java | 7 +-
.../strings/ValidParenthesesTest.java | 11 +-
.../thealgorithms/strings/WordLadderTest.java | 8 +-
.../longestNonRepeativeSubstringTest.java | 10 +-
.../zigZagPattern/zigZagPatternTest.java | 10 +-
521 files changed, 5269 insertions(+), 7345 deletions(-)
diff --git a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java
index 4aca8fb40624..21bb5a123f83 100644
--- a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java
+++ b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java
@@ -22,9 +22,7 @@ public class IIRFilter {
*/
public IIRFilter(int order) throws IllegalArgumentException {
if (order < 1) {
- throw new IllegalArgumentException(
- "order must be greater than zero"
- );
+ throw new IllegalArgumentException("order must be greater than zero");
}
this.order = order;
@@ -47,24 +45,19 @@ public IIRFilter(int order) throws IllegalArgumentException {
* @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is
* not of size {@code order}, or if {@code aCoeffs[0]} is 0.0
*/
- public void setCoeffs(double[] aCoeffs, double[] bCoeffs)
- throws IllegalArgumentException {
+ public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException {
if (aCoeffs.length != order) {
throw new IllegalArgumentException(
- "aCoeffs must be of size " + order + ", got " + aCoeffs.length
- );
+ "aCoeffs must be of size " + order + ", got " + aCoeffs.length);
}
if (aCoeffs[0] == 0.0) {
- throw new IllegalArgumentException(
- "aCoeffs.get(0) must not be zero"
- );
+ throw new IllegalArgumentException("aCoeffs.get(0) must not be zero");
}
if (bCoeffs.length != order) {
throw new IllegalArgumentException(
- "bCoeffs must be of size " + order + ", got " + bCoeffs.length
- );
+ "bCoeffs must be of size " + order + ", got " + bCoeffs.length);
}
for (int i = 0; i <= order; i++) {
@@ -84,8 +77,7 @@ public double process(double sample) {
// Process
for (int i = 1; i <= order; i++) {
- result +=
- (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]);
+ result += (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]);
}
result = (result + coeffsB[0] * sample) / coeffsA[0];
diff --git a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
index 8acaa954ce75..b840f6ad5388 100644
--- a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
+++ b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
@@ -1,4 +1,5 @@
-/** Author : Siddhant Swarup Mallick
+/**
+ * Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
@@ -15,13 +16,12 @@ public class AllPathsFromSourceToTarget {
private int v;
// To store the paths from source to destination
- static List> nm=new ArrayList<>();
+ static List> nm = new ArrayList<>();
// adjacency list
private ArrayList[] adjList;
// Constructor
- public AllPathsFromSourceToTarget(int vertices)
- {
+ public AllPathsFromSourceToTarget(int vertices) {
// initialise vertex count
this.v = vertices;
@@ -31,8 +31,7 @@ public AllPathsFromSourceToTarget(int vertices)
}
// utility method to initialise adjacency list
- private void initAdjList()
- {
+ private void initAdjList() {
adjList = new ArrayList[v];
for (int i = 0; i < v; i++) {
@@ -41,15 +40,12 @@ private void initAdjList()
}
// add edge from u to v
- public void addEdge(int u, int v)
- {
+ public void addEdge(int u, int v) {
// Add v to u's list.
adjList[u].add(v);
}
-
- public void storeAllPaths(int s, int d)
- {
+ public void storeAllPaths(int s, int d) {
boolean[] isVisited = new boolean[v];
ArrayList pathList = new ArrayList<>();
@@ -61,9 +57,9 @@ public void storeAllPaths(int s, int d)
// A recursive function to print all paths from 'u' to 'd'.
// isVisited[] keeps track of vertices in current path.
- // localPathList<> stores actual vertices in the current path
- private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List localPathList)
- {
+ // localPathList<> stores actual vertices in the current path
+ private void storeAllPathsUtil(
+ Integer u, Integer d, boolean[] isVisited, List localPathList) {
if (u.equals(d)) {
nm.add(new ArrayList<>(localPathList));
@@ -74,7 +70,7 @@ private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination)
- {
+ public static List> allPathsFromSourceToTarget(
+ int vertices, int[][] a, int source, int destination) {
// Create a sample graph
AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices);
- for(int i=0 ; i> combination(int n, int k) {
length = k;
Integer[] arr = new Integer[n];
for (int i = 1; i <= n; i++) {
- arr[i-1] = i;
+ arr[i - 1] = i;
}
return Combination.combination(arr, length);
}
diff --git a/src/main/java/com/thealgorithms/backtracking/Combination.java b/src/main/java/com/thealgorithms/backtracking/Combination.java
index c2d148a270e8..7c45dffb8630 100644
--- a/src/main/java/com/thealgorithms/backtracking/Combination.java
+++ b/src/main/java/com/thealgorithms/backtracking/Combination.java
@@ -38,11 +38,7 @@ public static List> combination(T[] arr, int n) {
* @param the type of elements in the array.
*/
private static void backtracking(
- T[] arr,
- int index,
- TreeSet currSet,
- List> result
- ) {
+ T[] arr, int index, TreeSet currSet, List> result) {
if (index + length - currSet.size() > arr.length) return;
if (length - 1 == currSet.size()) {
for (int i = index; i < arr.length; i++) {
diff --git a/src/main/java/com/thealgorithms/backtracking/FloodFill.java b/src/main/java/com/thealgorithms/backtracking/FloodFill.java
index 6c4446a40bc4..b6b1c5ee19f8 100644
--- a/src/main/java/com/thealgorithms/backtracking/FloodFill.java
+++ b/src/main/java/com/thealgorithms/backtracking/FloodFill.java
@@ -38,13 +38,7 @@ public static void putPixel(int[][] image, int x, int y, int newColor) {
* @param newColor The new color which to be filled in the image
* @param oldColor The old color which is to be replaced in the image
*/
- public static void floodFill(
- int[][] image,
- int x,
- int y,
- int newColor,
- int oldColor
- ) {
+ public static void floodFill(int[][] image, int x, int y, int newColor, int oldColor) {
if (x < 0 || x >= image.length) return;
if (y < 0 || y >= image[x].length) return;
if (getPixel(image, x, y) != oldColor) return;
diff --git a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
index a2075fd9d778..882b43537b7f 100644
--- a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
+++ b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
@@ -4,9 +4,10 @@
/*
* Problem Statement: -
-
- Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of
- chess knight must visit each square exactly once. Print the order of each cell in which they are visited.
+
+ Given a N*N board with the Knight placed on the first block of an empty board. Moving according
+ to the rules of chess knight must visit each square exactly once. Print the order of each cell in
+ which they are visited.
Example: -
@@ -27,14 +28,14 @@ public class KnightsTour {
private static final int base = 12;
private static final int[][] moves = {
- { 1, -2 },
- { 2, -1 },
- { 2, 1 },
- { 1, 2 },
- { -1, 2 },
- { -2, 1 },
- { -2, -1 },
- { -1, -2 },
+ {1, -2},
+ {2, -1},
+ {2, 1},
+ {1, 2},
+ {-1, 2},
+ {-2, 1},
+ {-2, -1},
+ {-1, -2},
}; // Possible moves by knight on chess
private static int[][] grid; // chess grid
private static int total; // total squares in chess
@@ -75,23 +76,17 @@ private static boolean solve(int row, int column, int count) {
return false;
}
- Collections.sort(
- neighbor,
- new Comparator() {
- public int compare(int[] a, int[] b) {
- return a[2] - b[2];
- }
+ Collections.sort(neighbor, new Comparator() {
+ public int compare(int[] a, int[] b) {
+ return a[2] - b[2];
}
- );
+ });
for (int[] nb : neighbor) {
row = nb[0];
column = nb[1];
grid[row][column] = count;
- if (
- !orphanDetected(count, row, column) &&
- solve(row, column, count + 1)
- ) {
+ if (!orphanDetected(count, row, column) && solve(row, column, count + 1)) {
return true;
}
grid[row][column] = 0;
@@ -109,7 +104,7 @@ private static List neighbors(int row, int column) {
int y = m[1];
if (grid[row + y][column + x] == 0) {
int num = countNeighbors(row + y, column + x);
- neighbour.add(new int[] { row + y, column + x, num });
+ neighbour.add(new int[] {row + y, column + x, num});
}
}
return neighbour;
diff --git a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java
index 0e1cd308d6cb..d66d1482d83e 100644
--- a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java
+++ b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java
@@ -51,9 +51,7 @@ public static void mazeRecursion() {
setWay2(map2, 1, 1);
// Print out the new map1, with the ball footprint
- System.out.println(
- "After the ball goes through the map1,show the current map1 condition"
- );
+ System.out.println("After the ball goes through the map1,show the current map1 condition");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map[i][j] + " ");
@@ -62,9 +60,7 @@ public static void mazeRecursion() {
}
// Print out the new map2, with the ball footprint
- System.out.println(
- "After the ball goes through the map2,show the current map2 condition"
- );
+ System.out.println("After the ball goes through the map2,show the current map2 condition");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map2[i][j] + " ");
@@ -85,7 +81,7 @@ public static void mazeRecursion() {
* means the ball has gone through the path but this path is dead end
* 5. We will need strategy for the ball to pass through the maze for example:
* Down -> Right -> Up -> Left, if the path doesn't work, then backtrack
- *
+ *
* @author OngLipWei
* @version Jun 23, 2021 11:36:14 AM
* @param map The maze
@@ -99,7 +95,8 @@ public static boolean setWay(int[][] map, int i, int j) {
}
if (map[i][j] == 0) { // if the ball haven't gone through this point
// then the ball follows the move strategy : down -> right -> up -> left
- map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。
+ map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2
+ // first。
if (setWay(map, i + 1, j)) { // go down
return true;
} else if (setWay(map, i, j + 1)) { // go right
@@ -129,7 +126,8 @@ public static boolean setWay2(int[][] map, int i, int j) {
}
if (map[i][j] == 0) { // if the ball haven't gone through this point
// then the ball follows the move strategy : up->right->down->left
- map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。
+ map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2
+ // first。
if (setWay2(map, i - 1, j)) { // go up
return true;
} else if (setWay2(map, i, j + 1)) { // go right
diff --git a/src/main/java/com/thealgorithms/backtracking/NQueens.java b/src/main/java/com/thealgorithms/backtracking/NQueens.java
index a567c57b451a..6d45a73a821b 100644
--- a/src/main/java/com/thealgorithms/backtracking/NQueens.java
+++ b/src/main/java/com/thealgorithms/backtracking/NQueens.java
@@ -47,14 +47,8 @@ public static void placeQueens(final int queens) {
List> arrangements = new ArrayList>();
getSolution(queens, arrangements, new int[queens], 0);
if (arrangements.isEmpty()) {
- System.out.println(
- "There is no way to place " +
- queens +
- " queens on board of size " +
- queens +
- "x" +
- queens
- );
+ System.out.println("There is no way to place " + queens + " queens on board of size "
+ + queens + "x" + queens);
} else {
System.out.println("Arrangement for placing " + queens + " queens");
}
@@ -73,11 +67,7 @@ public static void placeQueens(final int queens) {
* @param columnIndex: This is the column in which queen is being placed
*/
private static void getSolution(
- int boardSize,
- List> solutions,
- int[] columns,
- int columnIndex
- ) {
+ int boardSize, List> solutions, int[] columns, int columnIndex) {
if (columnIndex == boardSize) {
// this means that all queens have been placed
List sol = new ArrayList();
@@ -96,7 +86,8 @@ private static void getSolution(
for (int rowIndex = 0; rowIndex < boardSize; rowIndex++) {
columns[columnIndex] = rowIndex;
if (isPlacedCorrectly(columns, rowIndex, columnIndex)) {
- // If queen is placed successfully at rowIndex in column=columnIndex then try placing queen in next column
+ // If queen is placed successfully at rowIndex in column=columnIndex then try
+ // placing queen in next column
getSolution(boardSize, solutions, columns, columnIndex + 1);
}
}
@@ -111,11 +102,7 @@ private static void getSolution(
* @param columnIndex: column in which queen is being placed
* @return true: if queen can be placed safely false: otherwise
*/
- private static boolean isPlacedCorrectly(
- int[] columns,
- int rowIndex,
- int columnIndex
- ) {
+ private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) {
for (int i = 0; i < columnIndex; i++) {
int diff = Math.abs(columns[i] - rowIndex);
if (diff == 0 || columnIndex - i == diff) {
diff --git a/src/main/java/com/thealgorithms/backtracking/PowerSum.java b/src/main/java/com/thealgorithms/backtracking/PowerSum.java
index dc4738583358..72af17d48bd4 100644
--- a/src/main/java/com/thealgorithms/backtracking/PowerSum.java
+++ b/src/main/java/com/thealgorithms/backtracking/PowerSum.java
@@ -1,11 +1,10 @@
package com.thealgorithms.backtracking;
-
/*
* Problem Statement :
- * Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers of unique, natural numbers.
- * For example, if N=100 and X=3, we have to find all combinations of unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3.
- * Therefore output will be 1.
+ * Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers
+ * of unique, natural numbers. For example, if N=100 and X=3, we have to find all combinations of
+ * unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3. Therefore output will be 1.
*/
public class PowerSum {
@@ -16,26 +15,29 @@ public int powSum(int N, int X) {
return count;
}
- //here i is the natural number which will be raised by X and added in sum.
+ // here i is the natural number which will be raised by X and added in sum.
public void Sum(int N, int X, int i) {
- //if sum is equal to N that is one of our answer and count is increased.
+ // if sum is equal to N that is one of our answer and count is increased.
if (sum == N) {
count++;
return;
- } //we will be adding next natural number raised to X only if on adding it in sum the result is less than N.
+ } // we will be adding next natural number raised to X only if on adding it in sum the
+ // result is less than N.
else if (sum + power(i, X) <= N) {
sum += power(i, X);
Sum(N, X, i + 1);
- //backtracking and removing the number added last since no possible combination is there with it.
+ // backtracking and removing the number added last since no possible combination is
+ // there with it.
sum -= power(i, X);
}
if (power(i, X) < N) {
- //calling the sum function with next natural number after backtracking if when it is raised to X is still less than X.
+ // calling the sum function with next natural number after backtracking if when it is
+ // raised to X is still less than X.
Sum(N, X, i + 1);
}
}
- //creating a separate power function so that it can be used again and again when required.
+ // creating a separate power function so that it can be used again and again when required.
private int power(int a, int b) {
return (int) Math.pow(a, b);
}
diff --git a/src/main/java/com/thealgorithms/backtracking/WordSearch.java b/src/main/java/com/thealgorithms/backtracking/WordSearch.java
index affac0ee6ac2..4ab81bfd7d67 100644
--- a/src/main/java/com/thealgorithms/backtracking/WordSearch.java
+++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java
@@ -1,13 +1,12 @@
package com.thealgorithms.backtracking;
-
/*
Word Search Problem (https://en.wikipedia.org/wiki/Word_search)
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
-The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or
-vertically neighboring. The same letter cell may not be used more than once.
+The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are
+those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
@@ -27,8 +26,8 @@ Word Search Problem (https://en.wikipedia.org/wiki/Word_search)
Depth First Search in matrix (as multiple sources possible) with backtracking
like finding cycle in a directed graph. Maintain a record of path
- Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we do it L times
- Sx = O(L) : stack size is max L
+ Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we
+ do it L times Sx = O(L) : stack size is max L
*/
public class WordSearch {
@@ -52,8 +51,7 @@ private boolean doDFS(int x, int y, int nextIdx) {
int yi = y + dy[i];
if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) {
boolean exists = doDFS(xi, yi, nextIdx + 1);
- if (exists)
- return true;
+ if (exists) return true;
}
}
visited[x][y] = false;
@@ -68,12 +66,10 @@ public boolean exist(char[][] board, String word) {
if (board[i][j] == word.charAt(0)) {
visited = new boolean[board.length][board[0].length];
boolean exists = doDFS(i, j, 1);
- if (exists)
- return true;
+ if (exists) return true;
}
}
}
return false;
}
}
-
diff --git a/src/main/java/com/thealgorithms/ciphers/AES.java b/src/main/java/com/thealgorithms/ciphers/AES.java
index c5cb286c7772..46886cbcb366 100644
--- a/src/main/java/com/thealgorithms/ciphers/AES.java
+++ b/src/main/java/com/thealgorithms/ciphers/AES.java
@@ -2395,9 +2395,7 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
// apply S-Box to all 8-Bit Substrings
for (int i = 0; i < 4; i++) {
- StringBuilder currentByteBits = new StringBuilder(
- rBytes.substring(i * 2, (i + 1) * 2)
- );
+ StringBuilder currentByteBits = new StringBuilder(rBytes.substring(i * 2, (i + 1) * 2));
int currentByte = Integer.parseInt(currentByteBits.toString(), 16);
currentByte = SBOX[currentByte];
@@ -2407,8 +2405,7 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
currentByte = currentByte ^ RCON[rconCounter];
}
- currentByteBits =
- new StringBuilder(Integer.toHexString(currentByte));
+ currentByteBits = new StringBuilder(Integer.toHexString(currentByte));
// Add zero padding
while (currentByteBits.length() < 2) {
@@ -2416,12 +2413,8 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
}
// replace bytes in original string
- rBytes =
- new StringBuilder(
- rBytes.substring(0, i * 2) +
- currentByteBits +
- rBytes.substring((i + 1) * 2)
- );
+ rBytes = new StringBuilder(
+ rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2));
}
// t = new BigInteger(rBytes, 16);
@@ -2438,16 +2431,16 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
public static BigInteger[] keyExpansion(BigInteger initialKey) {
BigInteger[] roundKeys = {
initialKey,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
};
// initialize rcon iteration
@@ -2455,23 +2448,18 @@ public static BigInteger[] keyExpansion(BigInteger initialKey) {
for (int i = 1; i < 11; i++) {
// get the previous 32 bits the key
- BigInteger t =
- roundKeys[i - 1].remainder(new BigInteger("100000000", 16));
+ BigInteger t = roundKeys[i - 1].remainder(new BigInteger("100000000", 16));
// split previous key into 8-bit segments
BigInteger[] prevKey = {
roundKeys[i - 1].remainder(new BigInteger("100000000", 16)),
- roundKeys[i - 1].remainder(
- new BigInteger("10000000000000000", 16)
- )
+ roundKeys[i - 1]
+ .remainder(new BigInteger("10000000000000000", 16))
.divide(new BigInteger("100000000", 16)),
- roundKeys[i - 1].remainder(
- new BigInteger("1000000000000000000000000", 16)
- )
+ roundKeys[i - 1]
+ .remainder(new BigInteger("1000000000000000000000000", 16))
.divide(new BigInteger("10000000000000000", 16)),
- roundKeys[i - 1].divide(
- new BigInteger("1000000000000000000000000", 16)
- ),
+ roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)),
};
// run schedule core
@@ -2527,9 +2515,7 @@ public static int[] splitBlockIntoCells(BigInteger block) {
public static BigInteger mergeCellsIntoBlock(int[] cells) {
StringBuilder blockBits = new StringBuilder();
for (int i = 0; i < 16; i++) {
- StringBuilder cellBits = new StringBuilder(
- Integer.toBinaryString(cells[i])
- );
+ StringBuilder cellBits = new StringBuilder(Integer.toBinaryString(cells[i]));
// Append leading 0 for full "8-bit" strings
while (cellBits.length() < 8) {
@@ -2545,10 +2531,7 @@ public static BigInteger mergeCellsIntoBlock(int[] cells) {
/**
* @return ciphertext XOR key
*/
- public static BigInteger addRoundKey(
- BigInteger ciphertext,
- BigInteger key
- ) {
+ public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) {
return ciphertext.xor(key);
}
@@ -2669,14 +2652,10 @@ public static BigInteger mixColumns(BigInteger ciphertext) {
cells[i * 4 + 3],
};
- outputCells[i * 4] =
- MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3];
- outputCells[i * 4 + 1] =
- row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3];
- outputCells[i * 4 + 2] =
- row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]];
- outputCells[i * 4 + 3] =
- MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]];
+ outputCells[i * 4] = MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3];
+ outputCells[i * 4 + 1] = row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3];
+ outputCells[i * 4 + 2] = row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]];
+ outputCells[i * 4 + 3] = MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]];
}
return mergeCellsIntoBlock(outputCells);
}
@@ -2697,26 +2676,13 @@ public static BigInteger mixColumnsDec(BigInteger ciphertext) {
cells[i * 4 + 3],
};
- outputCells[i * 4] =
- MULT14[row[0]] ^
- MULT11[row[1]] ^
- MULT13[row[2]] ^
- MULT9[row[3]];
- outputCells[i * 4 + 1] =
- MULT9[row[0]] ^
- MULT14[row[1]] ^
- MULT11[row[2]] ^
- MULT13[row[3]];
- outputCells[i * 4 + 2] =
- MULT13[row[0]] ^
- MULT9[row[1]] ^
- MULT14[row[2]] ^
- MULT11[row[3]];
- outputCells[i * 4 + 3] =
- MULT11[row[0]] ^
- MULT13[row[1]] ^
- MULT9[row[2]] ^
- MULT14[row[3]];
+ outputCells[i * 4] = MULT14[row[0]] ^ MULT11[row[1]] ^ MULT13[row[2]] ^ MULT9[row[3]];
+ outputCells[i * 4 + 1]
+ = MULT9[row[0]] ^ MULT14[row[1]] ^ MULT11[row[2]] ^ MULT13[row[3]];
+ outputCells[i * 4 + 2]
+ = MULT13[row[0]] ^ MULT9[row[1]] ^ MULT14[row[2]] ^ MULT11[row[3]];
+ outputCells[i * 4 + 3]
+ = MULT11[row[0]] ^ MULT13[row[1]] ^ MULT9[row[2]] ^ MULT14[row[3]];
}
return mergeCellsIntoBlock(outputCells);
}
@@ -2780,9 +2746,7 @@ public static BigInteger decrypt(BigInteger cipherText, BigInteger key) {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
- System.out.println(
- "Enter (e) letter for encrpyt or (d) letter for decrypt :"
- );
+ System.out.println("Enter (e) letter for encrpyt or (d) letter for decrypt :");
char choice = input.nextLine().charAt(0);
String in;
switch (choice) {
diff --git a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java
index 051b34c2293a..c010d532437f 100644
--- a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java
+++ b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java
@@ -1,10 +1,10 @@
package com.thealgorithms.ciphers;
+import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
-import java.security.InvalidAlgorithmParameterException;
/**
* This example program shows how AES encryption and decryption can be done in
@@ -29,12 +29,8 @@ public static void main(String[] args) throws Exception {
String decryptedText = decryptText(cipherText, secKey);
System.out.println("Original Text:" + plainText);
- System.out.println(
- "AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())
- );
- System.out.println(
- "Encrypted Text (Hex Form):" + bytesToHex(cipherText)
- );
+ System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded()));
+ System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText));
System.out.println("Descrypted Text:" + decryptedText);
}
@@ -45,8 +41,7 @@ public static void main(String[] args) throws Exception {
* @return secKey (Secret key that we encrypt using it)
* @throws NoSuchAlgorithmException (from KeyGenrator)
*/
- public static SecretKey getSecretEncryptionKey()
- throws NoSuchAlgorithmException {
+ public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException {
KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES");
aesKeyGenerator.init(128); // The AES key size in number of bits
return aesKeyGenerator.generateKey();
@@ -63,7 +58,8 @@ public static SecretKey getSecretEncryptionKey()
* @throws IllegalBlockSizeException (from Cipher)
*/
public static byte[] encryptText(String plainText, SecretKey secKey)
- throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
+ throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
+ IllegalBlockSizeException, BadPaddingException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
@@ -76,8 +72,8 @@ public static byte[] encryptText(String plainText, SecretKey secKey)
* @return plainText
*/
public static String decryptText(byte[] byteCipherText, SecretKey secKey)
- throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
- IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
+ throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
+ IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV());
diff --git a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
index a6fe0ab9290f..9ff63ddfe7c5 100644
--- a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
@@ -15,8 +15,7 @@ static String encryptMessage(char[] msg) {
{here x is msg[i] and m is 26} and added 'A' to
bring it in range of ascii alphabet[ 65-90 | A-Z ] */
if (msg[i] != ' ') {
- cipher =
- cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
+ cipher = cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
} else { // else simply append space character
cipher += msg[i];
}
@@ -29,8 +28,8 @@ static String decryptCipher(String cipher) {
int a_inv = 0;
int flag = 0;
- //Find a^-1 (the multiplicative inverse of a
- //in the group of integers modulo m.)
+ // Find a^-1 (the multiplicative inverse of a
+ // in the group of integers modulo m.)
for (int i = 0; i < 26; i++) {
flag = (a * i) % 26;
@@ -45,12 +44,8 @@ static String decryptCipher(String cipher) {
{here x is cipher[i] and m is 26} and added 'A'
to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
if (cipher.charAt(i) != ' ') {
- msg =
- msg +
- (char) (
- ((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'
- );
- } else { //else simply append space character
+ msg = msg + (char) (((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
+ } else { // else simply append space character
msg += cipher.charAt(i);
}
}
@@ -67,8 +62,6 @@ public static void main(String[] args) {
System.out.println("Encrypted Message is : " + cipherText);
// Calling Decryption function
- System.out.println(
- "Decrypted Message is: " + decryptCipher(cipherText)
- );
+ System.out.println("Decrypted Message is: " + decryptCipher(cipherText));
}
}
diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
index 8864fc75f342..bce7f699d432 100644
--- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java
+++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
@@ -10,7 +10,7 @@
public class Blowfish {
- //Initializing substitution boxes
+ // Initializing substitution boxes
String[][] S = {
{
"d1310ba6",
@@ -1046,7 +1046,7 @@ public class Blowfish {
},
};
- //Initializing subkeys with digits of pi
+ // Initializing subkeys with digits of pi
String[] P = {
"243f6a88",
"85a308d3",
@@ -1068,7 +1068,7 @@ public class Blowfish {
"8979fb1b",
};
- //Initializing modVal to 2^32
+ // Initializing modVal to 2^32
long modVal = 4294967296L;
/**
@@ -1098,7 +1098,8 @@ private String hexToBin(String hex) {
* This method returns hexadecimal representation of the binary number passed as parameter
*
* @param binary Number for which hexadecimal representation is required
- * @return String object which is a hexadecimal representation of the binary number passed as parameter
+ * @return String object which is a hexadecimal representation of the binary number passed as
+ * parameter
*/
private String binToHex(String binary) {
long num = Long.parseUnsignedLong(binary, 2);
@@ -1109,7 +1110,8 @@ private String binToHex(String binary) {
}
/**
- * This method returns a string obtained by XOR-ing two strings of same length passed a method parameters
+ * This method returns a string obtained by XOR-ing two strings of same length passed a method
+ * parameters
*
* @param String a and b are string objects which will be XORed and are to be of same length
* @return String object obtained by XOR operation on String a and String b
@@ -1118,17 +1120,19 @@ private String xor(String a, String b) {
a = hexToBin(a);
b = hexToBin(b);
String ans = "";
- for (int i = 0; i < a.length(); i++) ans +=
- (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0');
+ for (int i = 0; i < a.length(); i++)
+ ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0');
ans = binToHex(ans);
return ans;
}
/**
- * This method returns addition of two hexadecimal numbers passed as parameters and moded with 2^32
+ * This method returns addition of two hexadecimal numbers passed as parameters and moded with
+ * 2^32
*
* @param String a and b are hexadecimal numbers
- * @return String object which is a is addition that is then moded with 2^32 of hex numbers passed as parameters
+ * @return String object which is a is addition that is then moded with 2^32 of hex numbers
+ * passed as parameters
*/
private String addBin(String a, String b) {
String ans = "";
@@ -1140,20 +1144,17 @@ private String addBin(String a, String b) {
return ans.substring(ans.length() - 8);
}
- /*F-function splits the 32-bit input into four 8-bit quarters
- and uses the quarters as input to the S-boxes.
- The S-boxes accept 8-bit input and produce 32-bit output.
- The outputs are added modulo 232 and XORed to produce the final 32-bit output
- */
+ /*F-function splits the 32-bit input into four 8-bit quarters
+ and uses the quarters as input to the S-boxes.
+ The S-boxes accept 8-bit input and produce 32-bit output.
+ The outputs are added modulo 232 and XORed to produce the final 32-bit output
+ */
private String f(String plainText) {
String[] a = new String[4];
String ans = "";
for (int i = 0; i < 8; i += 2) {
- //column number for S-box is a 8-bit value
- long col = Long.parseUnsignedLong(
- hexToBin(plainText.substring(i, i + 2)),
- 2
- );
+ // column number for S-box is a 8-bit value
+ long col = Long.parseUnsignedLong(hexToBin(plainText.substring(i, i + 2)), 2);
a[i / 2] = S[i / 2][(int) col];
}
ans = addBin(a[0], a[1]);
@@ -1162,30 +1163,30 @@ private String f(String plainText) {
return ans;
}
- //generate subkeys
+ // generate subkeys
private void keyGenerate(String key) {
int j = 0;
for (int i = 0; i < P.length; i++) {
- //XOR-ing 32-bit parts of the key with initial subkeys
+ // XOR-ing 32-bit parts of the key with initial subkeys
P[i] = xor(P[i], key.substring(j, j + 8));
j = (j + 8) % key.length();
}
}
- //round function
+ // round function
private String round(int time, String plainText) {
String left, right;
left = plainText.substring(0, 8);
right = plainText.substring(8, 16);
left = xor(left, P[time]);
- //output from F function
+ // output from F function
String fOut = f(left);
right = xor(fOut, right);
- //swap left and right
+ // swap left and right
return right + left;
}
@@ -1198,12 +1199,12 @@ private String round(int time, String plainText) {
* @return String cipherText is the encrypted value
*/
String encrypt(String plainText, String key) {
- //generating key
+ // generating key
keyGenerate(key);
for (int i = 0; i < 16; i++) plainText = round(i, plainText);
- //postprocessing
+ // postprocessing
String right = plainText.substring(0, 8);
String left = plainText.substring(8, 16);
right = xor(right, P[16]);
@@ -1220,12 +1221,12 @@ String encrypt(String plainText, String key) {
* @return String plainText is the decrypted text
*/
String decrypt(String cipherText, String key) {
- //generating key
+ // generating key
keyGenerate(key);
for (int i = 17; i > 1; i--) cipherText = round(i, cipherText);
- //postprocessing
+ // postprocessing
String right = cipherText.substring(0, 8);
String left = cipherText.substring(8, 16);
right = xor(right, P[1]);
diff --git a/src/main/java/com/thealgorithms/ciphers/Caesar.java b/src/main/java/com/thealgorithms/ciphers/Caesar.java
index a5f89fba7180..6011909abc33 100644
--- a/src/main/java/com/thealgorithms/ciphers/Caesar.java
+++ b/src/main/java/com/thealgorithms/ciphers/Caesar.java
@@ -23,16 +23,19 @@ public String encode(String message, int shift) {
final int length = message.length();
for (int i = 0; i < length; i++) {
- // int current = message.charAt(i); //using char to shift characters because ascii
+ // int current = message.charAt(i); //using char to shift characters because
+ // ascii
// is in-order latin alphabet
char current = message.charAt(i); // Java law : char + int = char
if (isCapitalLatinLetter(current)) {
current += shift;
- encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
+ encoded.append((
+ char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
} else if (isSmallLatinLetter(current)) {
current += shift;
- encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
+ encoded.append((
+ char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
} else {
encoded.append(current);
}
@@ -56,10 +59,12 @@ public String decode(String encryptedMessage, int shift) {
char current = encryptedMessage.charAt(i);
if (isCapitalLatinLetter(current)) {
current -= shift;
- decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
+ decoded.append((
+ char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
} else if (isSmallLatinLetter(current)) {
current -= shift;
- decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
+ decoded.append((
+ char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
} else {
decoded.append(current);
}
diff --git a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
index 35f15e587d2f..70b1f7ea147b 100644
--- a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
@@ -12,9 +12,8 @@ public class ColumnarTranspositionCipher {
private static String keyword;
private static Object[][] table;
private static String abecedarium;
- public static final String ABECEDARIUM =
- "abcdefghijklmnopqrstuvwxyzABCDEFG" +
- "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@";
+ public static final String ABECEDARIUM = "abcdefghijklmnopqrstuvwxyzABCDEFG"
+ + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@";
private static final String ENCRYPTION_FIELD = "≈";
private static final char ENCRYPTION_FIELD_CHAR = '≈';
@@ -50,14 +49,10 @@ public static String encrpyter(String word, String keyword) {
* @return a String with the word encrypted by the Columnar Transposition
* Cipher Rule
*/
- public static String encrpyter(
- String word,
- String keyword,
- String abecedarium
- ) {
+ public static String encrpyter(String word, String keyword, String abecedarium) {
ColumnarTranspositionCipher.keyword = keyword;
- ColumnarTranspositionCipher.abecedarium =
- Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
+ ColumnarTranspositionCipher.abecedarium
+ = Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
table = tableBuilder(word);
Object[][] sortedTable = sortTable(table);
StringBuilder wordEncrypted = new StringBuilder();
@@ -120,9 +115,7 @@ private static Object[][] tableBuilder(String word) {
* order to respect the Columnar Transposition Cipher Rule.
*/
private static int numberOfRows(String word) {
- if (
- word.length() / keyword.length() > word.length() / keyword.length()
- ) {
+ if (word.length() / keyword.length() > word.length() / keyword.length()) {
return (word.length() / keyword.length()) + 1;
} else {
return word.length() / keyword.length();
@@ -147,22 +140,12 @@ private static Object[] findElements() {
private static Object[][] sortTable(Object[][] table) {
Object[][] tableSorted = new Object[table.length][table[0].length];
for (int i = 0; i < tableSorted.length; i++) {
- System.arraycopy(
- table[i],
- 0,
- tableSorted[i],
- 0,
- tableSorted[i].length
- );
+ System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length);
}
for (int i = 0; i < tableSorted[0].length; i++) {
for (int j = i + 1; j < tableSorted[0].length; j++) {
if ((int) tableSorted[0][i] > (int) table[0][j]) {
- Object[] column = getColumn(
- tableSorted,
- tableSorted.length,
- i
- );
+ Object[] column = getColumn(tableSorted, tableSorted.length, i);
switchColumns(tableSorted, j, i, column);
}
}
@@ -182,11 +165,7 @@ private static Object[] getColumn(Object[][] table, int rows, int column) {
}
private static void switchColumns(
- Object[][] table,
- int firstColumnIndex,
- int secondColumnIndex,
- Object[] columnToSwitch
- ) {
+ Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) {
for (int i = 0; i < table.length; i++) {
table[i][secondColumnIndex] = table[i][firstColumnIndex];
table[i][firstColumnIndex] = columnToSwitch[i];
@@ -217,22 +196,12 @@ private static void showTable() {
public static void main(String[] args) {
String keywordForExample = "asd215";
- String wordBeingEncrypted =
- "This is a test of the Columnar Transposition Cipher";
- System.out.println(
- "### Example of Columnar Transposition Cipher ###\n"
- );
+ String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher";
+ System.out.println("### Example of Columnar Transposition Cipher ###\n");
System.out.println("Word being encryped ->>> " + wordBeingEncrypted);
- System.out.println(
- "Word encrypted ->>> " +
- ColumnarTranspositionCipher.encrpyter(
- wordBeingEncrypted,
- keywordForExample
- )
- );
- System.out.println(
- "Word decryped ->>> " + ColumnarTranspositionCipher.decrypter()
- );
+ System.out.println("Word encrypted ->>> "
+ + ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample));
+ System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter());
System.out.println("\n### Encrypted Table ###");
showTable();
}
diff --git a/src/main/java/com/thealgorithms/ciphers/DES.java b/src/main/java/com/thealgorithms/ciphers/DES.java
index aae8282eae42..b6ca8fb8a87d 100644
--- a/src/main/java/com/thealgorithms/ciphers/DES.java
+++ b/src/main/java/com/thealgorithms/ciphers/DES.java
@@ -1,8 +1,9 @@
package com.thealgorithms.ciphers;
/**
- * This class is build to demonstrate the application of the DES-algorithm (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a
- * plain English message. The supplied key must be in form of a 64 bit binary String.
+ * This class is build to demonstrate the application of the DES-algorithm
+ * (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a plain English message. The supplied
+ * key must be in form of a 64 bit binary String.
*/
public class DES {
@@ -12,7 +13,8 @@ public class DES {
private void sanitize(String key) {
int length = key.length();
if (length != 64) {
- throw new IllegalArgumentException("DES key must be supplied as a 64 character binary string");
+ throw new IllegalArgumentException(
+ "DES key must be supplied as a 64 character binary string");
}
}
@@ -30,170 +32,102 @@ public void setKey(String key) {
sanitize(key);
this.key = key;
}
-
- //Permutation table to convert initial 64 bit key to 56 bit key
- private static int[] PC1 =
- {
- 57, 49, 41, 33, 25, 17, 9,
- 1, 58, 50, 42, 34, 26, 18,
- 10, 2, 59, 51, 43, 35, 27,
- 19, 11, 3, 60, 52, 44, 36,
- 63, 55, 47, 39, 31, 23, 15,
- 7, 62, 54, 46, 38, 30, 22,
- 14, 6, 61, 53, 45, 37, 29,
- 21, 13, 5, 28, 20, 12, 4
- };
-
- //Lookup table used to shift the initial key, in order to generate the subkeys
- private static int[] KEY_SHIFTS =
- {
- 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
- };
-
- //Table to convert the 56 bit subkeys to 48 bit subkeys
- private static int[] PC2 =
- {
- 14, 17, 11, 24, 1, 5,
- 3, 28, 15, 6, 21, 10,
- 23, 19, 12, 4, 26, 8,
- 16, 7, 27, 20, 13, 2,
- 41, 52, 31, 37, 47, 55,
- 30, 40, 51, 45, 33, 48,
- 44, 49, 39, 56, 34, 53,
- 46, 42, 50, 36, 29, 32
- };
-
- //Initial permutatation of each 64 but message block
- private static int[] IP =
- {
- 58, 50, 42, 34, 26, 18, 10 , 2,
- 60, 52, 44, 36, 28, 20, 12, 4,
- 62, 54, 46, 38, 30, 22, 14, 6,
- 64, 56, 48, 40, 32, 24, 16, 8,
- 57, 49, 41, 33, 25, 17, 9, 1,
- 59, 51, 43, 35, 27, 19, 11, 3,
- 61, 53, 45, 37, 29, 21, 13, 5,
- 63, 55, 47, 39, 31, 23, 15, 7
- };
-
- //Expansion table to convert right half of message blocks from 32 bits to 48 bits
- private static int[] expansion =
- {
- 32, 1, 2, 3, 4, 5,
- 4, 5, 6, 7, 8, 9,
- 8, 9, 10, 11, 12, 13,
- 12, 13, 14, 15, 16, 17,
- 16, 17, 18, 19, 20, 21,
- 20, 21, 22, 23, 24, 25,
- 24, 25, 26, 27, 28, 29,
- 28, 29, 30, 31, 32, 1
- };
-
- //The eight substitution boxes are defined below
- private static int[][] s1 = {
- {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
- {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
- {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
- {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}
- };
-
- private static int[][] s2 = {
- {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
- {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
- {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
- {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}
- };
-
- private static int[][] s3 = {
- {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
- {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
- {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
- {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}
- };
-
- private static int[][] s4 = {
- {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
- {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
- {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
- {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}
- };
-
- private static int[][] s5 = {
- {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
- {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
- {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
- {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}
- };
-
- private static int[][] s6 = {
- {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
- {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
- {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
- {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}
- };
-
- private static int[][] s7 = {
- {4, 11, 2, 14, 15, 0, 8, 13 , 3, 12, 9 , 7, 5, 10, 6, 1},
- {13 , 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
- {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
- {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}
- };
-
- private static int[][] s8 = {
- {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
- {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6 ,11, 0, 14, 9, 2},
- {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10 ,13, 15, 3, 5, 8},
- {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6 ,11}
- };
-
- private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8};
-
- //Permutation table, used in the feistel function post s-box usage
- static int[] permutation =
- {
- 16, 7, 20, 21,
- 29, 12, 28, 17,
- 1, 15, 23, 26,
- 5, 18, 31, 10,
- 2, 8, 24, 14,
- 32, 27, 3, 9,
- 19, 13, 30, 6,
- 22, 11, 4, 25
- };
-
- //Table used for final inversion of the message box after 16 rounds of Feistel Function
- static int[] IPinverse =
- {
- 40, 8, 48, 16, 56, 24, 64, 32,
- 39, 7, 47, 15, 55, 23, 63, 31,
- 38, 6, 46, 14, 54, 22, 62, 30,
- 37, 5, 45, 13, 53, 21, 61, 29,
- 36, 4, 44, 12, 52, 20, 60, 28,
- 35, 3, 43 ,11, 51, 19, 59, 27,
- 34, 2, 42, 10, 50, 18, 58, 26,
- 33, 1, 41, 9, 49, 17, 57, 25
- };
+
+ // Permutation table to convert initial 64 bit key to 56 bit key
+ private static int[] PC1 = {57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51,
+ 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30,
+ 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4};
+
+ // Lookup table used to shift the initial key, in order to generate the subkeys
+ private static int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
+
+ // Table to convert the 56 bit subkeys to 48 bit subkeys
+ private static int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8,
+ 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34,
+ 53, 46, 42, 50, 36, 29, 32};
+
+ // Initial permutatation of each 64 but message block
+ private static int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54,
+ 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51,
+ 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7};
+
+ // Expansion table to convert right half of message blocks from 32 bits to 48 bits
+ private static int[] expansion = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12,
+ 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29,
+ 28, 29, 30, 31, 32, 1};
+
+ // The eight substitution boxes are defined below
+ private static int[][] s1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
+ {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
+ {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
+ {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}};
+
+ private static int[][] s2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
+ {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
+ {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
+ {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}};
+
+ private static int[][] s3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
+ {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
+ {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
+ {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}};
+
+ private static int[][] s4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
+ {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
+ {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
+ {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}};
+
+ private static int[][] s5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
+ {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
+ {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
+ {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}};
+
+ private static int[][] s6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
+ {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
+ {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
+ {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}};
+
+ private static int[][] s7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1},
+ {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
+ {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
+ {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}};
+
+ private static int[][] s8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
+ {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},
+ {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},
+ {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}};
+
+ private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8};
+
+ // Permutation table, used in the feistel function post s-box usage
+ static int[] permutation = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8,
+ 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25};
+
+ // Table used for final inversion of the message box after 16 rounds of Feistel Function
+ static int[] IPinverse = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6,
+ 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3,
+ 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25};
private String[] getSubkeys(String originalKey) {
- StringBuilder permutedKey = new StringBuilder(); //Initial permutation of keys via PC1
+ StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via PC1
int i, j;
for (i = 0; i < 56; i++) {
- permutedKey.append(originalKey.charAt(PC1[i] - 1));
+ permutedKey.append(originalKey.charAt(PC1[i] - 1));
}
String subKeys[] = new String[16];
String initialPermutedKey = permutedKey.toString();
String C0 = initialPermutedKey.substring(0, 28), D0 = initialPermutedKey.substring(28);
-
- //We will now operate on the left and right halves of the permutedKey
+
+ // We will now operate on the left and right halves of the permutedKey
for (i = 0; i < 16; i++) {
String Cn = C0.substring(KEY_SHIFTS[i]) + C0.substring(0, KEY_SHIFTS[i]);
String Dn = D0.substring(KEY_SHIFTS[i]) + D0.substring(0, KEY_SHIFTS[i]);
subKeys[i] = Cn + Dn;
- C0 = Cn; //Re-assign the values to create running permutation
+ C0 = Cn; // Re-assign the values to create running permutation
D0 = Dn;
}
- //Let us shrink the keys to 48 bits (well, characters here) using PC2
+ // Let us shrink the keys to 48 bits (well, characters here) using PC2
for (i = 0; i < 16; i++) {
String key = subKeys[i];
permutedKey.setLength(0);
@@ -244,16 +178,17 @@ private String feistel(String messageBlock, String key) {
String mixedKey = XOR(expandedKey.toString(), key);
StringBuilder substitutedString = new StringBuilder();
- //Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits
+ // Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits
for (i = 0; i < 48; i += 6) {
String block = mixedKey.substring(i, i + 6);
int row = (block.charAt(0) - 48) * 2 + (block.charAt(5) - 48);
- int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48);
+ int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4
+ + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48);
String substitutedBlock = pad(Integer.toBinaryString(s[i / 6][row][col]), 4);
substitutedString.append(substitutedBlock);
}
- StringBuilder permutedString = new StringBuilder();
+ StringBuilder permutedString = new StringBuilder();
for (i = 0; i < 32; i++) {
permutedString.append(substitutedString.charAt(permutation[i] - 1));
}
@@ -269,7 +204,7 @@ private String encryptBlock(String message, String keys[]) {
}
String L0 = permutedMessage.substring(0, 32), R0 = permutedMessage.substring(32);
- //Iterate 16 times
+ // Iterate 16 times
for (i = 0; i < 16; i++) {
String Ln = R0; // Previous Right block
String Rn = XOR(L0, feistel(R0, keys[i]));
@@ -277,7 +212,7 @@ private String encryptBlock(String message, String keys[]) {
R0 = Rn;
}
- String combinedBlock = R0 + L0; //Reverse the 16th block
+ String combinedBlock = R0 + L0; // Reverse the 16th block
permutedMessage.setLength(0);
for (i = 0; i < 64; i++) {
permutedMessage.append(combinedBlock.charAt(IPinverse[i] - 1));
@@ -285,7 +220,7 @@ private String encryptBlock(String message, String keys[]) {
return permutedMessage.toString();
}
- //To decode, we follow the same process as encoding, but with reversed keys
+ // To decode, we follow the same process as encoding, but with reversed keys
private String decryptBlock(String message, String keys[]) {
String reversedKeys[] = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
@@ -307,7 +242,7 @@ public String encrypt(String message) {
message = padLast(message, desiredLength);
}
- for (i = 0; i < l; i+= 8) {
+ for (i = 0; i < l; i += 8) {
String block = message.substring(i, i + 8);
StringBuilder bitBlock = new StringBuilder();
byte[] bytes = block.getBytes();
@@ -327,18 +262,19 @@ public String decrypt(String message) {
StringBuilder decryptedMessage = new StringBuilder();
int l = message.length(), i, j;
if (l % 64 != 0) {
- throw new IllegalArgumentException("Encrypted message should be a multiple of 64 characters in length");
+ throw new IllegalArgumentException(
+ "Encrypted message should be a multiple of 64 characters in length");
}
- for (i = 0; i < l; i+= 64) {
+ for (i = 0; i < l; i += 64) {
String block = message.substring(i, i + 64);
String result = decryptBlock(block.toString(), subKeys);
byte res[] = new byte[8];
- for (j = 0; j < 64; j+=8) {
- res[j / 8] = (byte)Integer.parseInt(result.substring(j, j + 8), 2);
+ for (j = 0; j < 64; j += 8) {
+ res[j / 8] = (byte) Integer.parseInt(result.substring(j, j + 8), 2);
}
decryptedMessage.append(new String(res));
}
- return decryptedMessage.toString().replace("\0", ""); // Get rid of the null bytes used for padding
+ return decryptedMessage.toString().replace(
+ "\0", ""); // Get rid of the null bytes used for padding
}
-
}
diff --git a/src/main/java/com/thealgorithms/ciphers/HillCipher.java b/src/main/java/com/thealgorithms/ciphers/HillCipher.java
index ffc7e08bedf7..a3226cef7de1 100644
--- a/src/main/java/com/thealgorithms/ciphers/HillCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/HillCipher.java
@@ -4,10 +4,11 @@
/*
* Java Implementation of Hill Cipher
- * Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number belonging to the set Z26 where A=0 , B=1, ..... Z=25.
- * To encrypt a message, each block of n letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against modulus 26.
- * To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption.
- * The cipher key and plaintext/ciphertext are user inputs.
+ * Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number
+ * belonging to the set Z26 where A=0 , B=1, ..... Z=25. To encrypt a message, each block of n
+ * letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against
+ * modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used
+ * for encryption. The cipher key and plaintext/ciphertext are user inputs.
* @author Ojasva Jain
*/
public class HillCipher {
@@ -28,7 +29,7 @@ static void encrypt(String message) {
keyMatrix[i][j] = userInput.nextInt();
}
}
- //check if det = 0
+ // check if det = 0
validateDeterminant(keyMatrix, matrixSize);
int[][] messageVector = new int[matrixSize][1];
@@ -62,7 +63,7 @@ static void encrypt(String message) {
System.out.println("Ciphertext: " + CipherText);
}
- //Following function decrypts a message
+ // Following function decrypts a message
static void decrypt(String message) {
message = message.toUpperCase();
// Get key matrix
@@ -75,10 +76,10 @@ static void decrypt(String message) {
keyMatrix[i][j] = userInput.nextInt();
}
}
- //check if det = 0
+ // check if det = 0
validateDeterminant(keyMatrix, n);
- //solving for the required plaintext message
+ // solving for the required plaintext message
int[][] messageVector = new int[n][1];
String PlainText = "";
int[][] plainMatrix = new int[n][1];
@@ -157,9 +158,7 @@ static void hillCipher(String message) {
static void validateDeterminant(int[][] keyMatrix, int n) {
if (determinant(keyMatrix, n) % 26 == 0) {
- System.out.println(
- "Invalid key, as determinant = 0. Program Terminated"
- );
+ System.out.println("Invalid key, as determinant = 0. Program Terminated");
}
}
diff --git a/src/main/java/com/thealgorithms/ciphers/Polybius.java b/src/main/java/com/thealgorithms/ciphers/Polybius.java
index 30eba49807f7..7b5a27807bc4 100644
--- a/src/main/java/com/thealgorithms/ciphers/Polybius.java
+++ b/src/main/java/com/thealgorithms/ciphers/Polybius.java
@@ -7,7 +7,8 @@
* Letters in alphabet takes place to two dimension table.
* Encrypted text is created according to row and column in two dimension table
* Decrypted text is generated by looking at the row and column respectively
- * Additionally, some letters in english alphabet deliberately throws such as U because U is very similar with V
+ * Additionally, some letters in english alphabet deliberately throws such as U because U is very
+ * similar with V
*
* @author Hikmet ÇAKIR
* @since 08-07-2022+03:00
@@ -16,11 +17,11 @@ public class Polybius {
private static final char[][] key = {
// 0 1 2 3 4
- /* 0 */{ 'A', 'B', 'C', 'D', 'E' },
- /* 1 */{ 'F', 'G', 'H', 'I', 'J' },
- /* 2 */{ 'K', 'L', 'M', 'N', 'O' },
- /* 3 */{ 'P', 'Q', 'R', 'S', 'T' },
- /* 4 */{ 'V', 'W', 'X', 'Y', 'Z' },
+ /* 0 */ {'A', 'B', 'C', 'D', 'E'},
+ /* 1 */ {'F', 'G', 'H', 'I', 'J'},
+ /* 2 */ {'K', 'L', 'M', 'N', 'O'},
+ /* 3 */ {'P', 'Q', 'R', 'S', 'T'},
+ /* 4 */ {'V', 'W', 'X', 'Y', 'Z'},
};
private static String findLocationByCharacter(final char character) {
diff --git a/src/main/java/com/thealgorithms/ciphers/RSA.java b/src/main/java/com/thealgorithms/ciphers/RSA.java
index 08f4e1980f92..e28eaecb3d1b 100644
--- a/src/main/java/com/thealgorithms/ciphers/RSA.java
+++ b/src/main/java/com/thealgorithms/ciphers/RSA.java
@@ -20,8 +20,7 @@ public RSA(int bits) {
* @return encrypted message
*/
public synchronized String encrypt(String message) {
- return (new BigInteger(message.getBytes())).modPow(publicKey, modulus)
- .toString();
+ return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString();
}
/**
@@ -36,9 +35,7 @@ public synchronized BigInteger encrypt(BigInteger message) {
*/
public synchronized String decrypt(String encryptedMessage) {
return new String(
- (new BigInteger(encryptedMessage)).modPow(privateKey, modulus)
- .toByteArray()
- );
+ (new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
}
/**
@@ -57,8 +54,7 @@ public synchronized void generateKeys(int bits) {
BigInteger q = new BigInteger(bits / 2, 100, r);
modulus = p.multiply(q);
- BigInteger m =
- (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
+ BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
publicKey = BigInteger.valueOf(3L);
diff --git a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
index 32b08f0cc38b..f6c88ef730ec 100644
--- a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
@@ -82,5 +82,4 @@ public String decode(String encryptedMessage, String cipherSmall) {
return decoded.toString();
}
-
}
diff --git a/src/main/java/com/thealgorithms/ciphers/Vigenere.java b/src/main/java/com/thealgorithms/ciphers/Vigenere.java
index fe7ff8d03dca..1702f1abb94c 100644
--- a/src/main/java/com/thealgorithms/ciphers/Vigenere.java
+++ b/src/main/java/com/thealgorithms/ciphers/Vigenere.java
@@ -16,21 +16,9 @@ public String encrypt(final String message, final String key) {
char c = message.charAt(i);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
- result.append(
- (char) (
- (c + key.toUpperCase().charAt(j) - 2 * 'A') %
- 26 +
- 'A'
- )
- );
+ result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A'));
} else {
- result.append(
- (char) (
- (c + key.toLowerCase().charAt(j) - 2 * 'a') %
- 26 +
- 'a'
- )
- );
+ result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a'));
}
} else {
result.append(c);
@@ -48,17 +36,9 @@ public String decrypt(final String message, final String key) {
char c = message.charAt(i);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
- result.append(
- (char) (
- 'Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26
- )
- );
+ result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26));
} else {
- result.append(
- (char) (
- 'z' - (25 - (c - key.toLowerCase().charAt(j))) % 26
- )
- );
+ result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26));
}
} else {
result.append(c);
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
index b7d36db5c809..809f85072e48 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
@@ -6,7 +6,8 @@
public class A5Cipher {
private final A5KeyStreamGenerator keyStreamGenerator;
- private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
+ private static final int KEY_STREAM_LENGTH
+ = 228; // 28.5 bytes so we need to pad bytes or something
public A5Cipher(BitSet sessionKey, BitSet frameCounter) {
keyStreamGenerator = new A5KeyStreamGenerator();
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
index 7788efc17774..148a49cf0959 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
@@ -9,7 +9,8 @@ public class A5KeyStreamGenerator extends CompositeLFSR {
private BitSet frameCounter;
private BitSet sessionKey;
private static final int INITIAL_CLOCKING_CYCLES = 100;
- private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
+ private static final int KEY_STREAM_LENGTH
+ = 228; // 28.5 bytes so we need to pad bytes or something
@Override
public void initialize(BitSet sessionKey, BitSet frameCounter) {
@@ -17,9 +18,9 @@ public void initialize(BitSet sessionKey, BitSet frameCounter) {
this.frameCounter = (BitSet) frameCounter.clone();
this.initialFrameCounter = (BitSet) frameCounter.clone();
registers.clear();
- LFSR lfsr1 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 });
- LFSR lfsr2 = new LFSR(22, 10, new int[] { 20, 21 });
- LFSR lfsr3 = new LFSR(23, 10, new int[] { 7, 20, 21, 22 });
+ LFSR lfsr1 = new LFSR(19, 8, new int[] {13, 16, 17, 18});
+ LFSR lfsr2 = new LFSR(22, 10, new int[] {20, 21});
+ LFSR lfsr3 = new LFSR(23, 10, new int[] {7, 20, 21, 22});
registers.add(lfsr1);
registers.add(lfsr2);
registers.add(lfsr3);
@@ -31,11 +32,7 @@ public void reInitialize() {
}
public BitSet getNextKeyStream() {
- for (
- int cycle = 1;
- cycle <= INITIAL_CLOCKING_CYCLES;
- ++cycle
- ) this.clock();
+ for (int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle) this.clock();
BitSet result = new BitSet(KEY_STREAM_LENGTH);
for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) {
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
index 050657166e77..2d0309a98482 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
@@ -29,12 +29,8 @@ private boolean getMajorityBit() {
bitCount.put(false, 0);
bitCount.put(true, 0);
- registers.forEach(lfsr ->
- bitCount.put(
- lfsr.getClockBit(),
- bitCount.get(lfsr.getClockBit()) + 1
- )
- );
+ registers.forEach(
+ lfsr -> bitCount.put(lfsr.getClockBit(), bitCount.get(lfsr.getClockBit()) + 1));
return bitCount.get(false) <= bitCount.get(true);
}
}
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/Utils.java b/src/main/java/com/thealgorithms/ciphers/a5/Utils.java
index b9220d11f868..abdd11d6b72d 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/Utils.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/Utils.java
@@ -1,8 +1,9 @@
package com.thealgorithms.ciphers.a5;
-// Source http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html
-//package com.java2s;
-//License from project: Open Source License
+// Source
+// http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html
+// package com.java2s;
+// License from project: Open Source License
import java.util.BitSet;
@@ -11,7 +12,7 @@ public class Utils {
public static boolean increment(BitSet bits, int size) {
int i = size - 1;
while (i >= 0 && bits.get(i)) {
- bits.set(i--, false);/*from w w w . j a v a 2s .c o m*/
+ bits.set(i--, false); /*from w w w . j a v a 2s .c o m*/
}
if (i < 0) {
return false;
diff --git a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
index b5974dd65f3b..c6450a4555ce 100644
--- a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
+++ b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
@@ -30,13 +30,8 @@ public static void main(String[] args) {
try {
System.out.print("Enter number: ");
n = in.next();
- System.out.print(
- "Enter beginning base (between " +
- MINIMUM_BASE +
- " and " +
- MAXIMUM_BASE +
- "): "
- );
+ System.out.print("Enter beginning base (between " + MINIMUM_BASE + " and "
+ + MAXIMUM_BASE + "): ");
b1 = in.nextInt();
if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) {
System.out.println("Invalid base!");
@@ -47,12 +42,7 @@ public static void main(String[] args) {
continue;
}
System.out.print(
- "Enter end base (between " +
- MINIMUM_BASE +
- " and " +
- MAXIMUM_BASE +
- "): "
- );
+ "Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
b2 = in.nextInt();
if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) {
System.out.println("Invalid base!");
diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java
index df547ffb5610..a77be2f50e07 100644
--- a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java
+++ b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java
@@ -11,9 +11,7 @@
public class DecimalToAnyBase {
public static void main(String[] args) throws Exception {
- BufferedReader br = new BufferedReader(
- new InputStreamReader(System.in)
- );
+ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the decimal input below: ");
int decInput = Integer.parseInt(br.readLine());
System.out.println();
@@ -22,15 +20,10 @@ public static void main(String[] args) throws Exception {
int base = Integer.parseInt(br.readLine());
System.out.println();
- System.out.println("Decimal Input" + " is: " + decInput);
- System.out.println(
- "Value of " +
- decInput +
- " in base " +
- base +
- " is: " +
- convertToAnyBase(decInput, base)
- );
+ System.out.println("Decimal Input"
+ + " is: " + decInput);
+ System.out.println("Value of " + decInput + " in base " + base
+ + " is: " + convertToAnyBase(decInput, base));
br.close();
}
diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
index c87508c62e86..a6119cfbc9bc 100644
--- a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
+++ b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
@@ -24,9 +24,7 @@ public static void main(String[] args) {
public static void conventionalConversion() {
int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in);
- System.out.printf(
- "Conventional conversion.%n Enter the decimal number: "
- );
+ System.out.printf("Conventional conversion.%n Enter the decimal number: ");
n = input.nextInt();
while (n != 0) {
d = n % 2;
diff --git a/src/main/java/com/thealgorithms/conversions/HexToOct.java b/src/main/java/com/thealgorithms/conversions/HexToOct.java
index 2a57fbde5c41..69707c80530a 100644
--- a/src/main/java/com/thealgorithms/conversions/HexToOct.java
+++ b/src/main/java/com/thealgorithms/conversions/HexToOct.java
@@ -61,7 +61,8 @@ public static void main(String[] args) {
hexadecnum = scan.nextLine();
// first convert hexadecimal to decimal
- decnum = hex2decimal(hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
+ decnum = hex2decimal(
+ hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
// variable decnum
// convert decimal to octal
diff --git a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java
index 4fad34ec8844..dc7310061009 100644
--- a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java
+++ b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java
@@ -19,69 +19,30 @@ public static void main(String[] args) {
// Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html
// Test hsvToRgb-method
- assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] { 0, 0, 0 });
- assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] { 255, 255, 255 });
- assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] { 255, 0, 0 });
- assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] { 255, 255, 0 });
- assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] { 0, 255, 0 });
- assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] { 0, 0, 255 });
- assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] { 255, 0, 255 });
- assert Arrays.equals(
- hsvToRgb(180, 0.5, 0.5),
- new int[] { 64, 128, 128 }
- );
- assert Arrays.equals(
- hsvToRgb(234, 0.14, 0.88),
- new int[] { 193, 196, 224 }
- );
- assert Arrays.equals(
- hsvToRgb(330, 0.75, 0.5),
- new int[] { 128, 32, 80 }
- );
+ assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] {0, 0, 0});
+ assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] {255, 255, 255});
+ assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] {255, 0, 0});
+ assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] {255, 255, 0});
+ assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] {0, 255, 0});
+ assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] {0, 0, 255});
+ assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] {255, 0, 255});
+ assert Arrays.equals(hsvToRgb(180, 0.5, 0.5), new int[] {64, 128, 128});
+ assert Arrays.equals(hsvToRgb(234, 0.14, 0.88), new int[] {193, 196, 224});
+ assert Arrays.equals(hsvToRgb(330, 0.75, 0.5), new int[] {128, 32, 80});
// Test rgbToHsv-method
// approximate-assertions needed because of small deviations due to converting between
// int-values and double-values.
- assert approximatelyEqualHsv(
- rgbToHsv(0, 0, 0),
- new double[] { 0, 0, 0 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(255, 255, 255),
- new double[] { 0, 0, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(255, 0, 0),
- new double[] { 0, 1, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(255, 255, 0),
- new double[] { 60, 1, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(0, 255, 0),
- new double[] { 120, 1, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(0, 0, 255),
- new double[] { 240, 1, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(255, 0, 255),
- new double[] { 300, 1, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(64, 128, 128),
- new double[] { 180, 0.5, 0.5 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(193, 196, 224),
- new double[] { 234, 0.14, 0.88 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(128, 32, 80),
- new double[] { 330, 0.75, 0.5 }
- );
+ assert approximatelyEqualHsv(rgbToHsv(0, 0, 0), new double[] {0, 0, 0});
+ assert approximatelyEqualHsv(rgbToHsv(255, 255, 255), new double[] {0, 0, 1});
+ assert approximatelyEqualHsv(rgbToHsv(255, 0, 0), new double[] {0, 1, 1});
+ assert approximatelyEqualHsv(rgbToHsv(255, 255, 0), new double[] {60, 1, 1});
+ assert approximatelyEqualHsv(rgbToHsv(0, 255, 0), new double[] {120, 1, 1});
+ assert approximatelyEqualHsv(rgbToHsv(0, 0, 255), new double[] {240, 1, 1});
+ assert approximatelyEqualHsv(rgbToHsv(255, 0, 255), new double[] {300, 1, 1});
+ assert approximatelyEqualHsv(rgbToHsv(64, 128, 128), new double[] {180, 0.5, 0.5});
+ assert approximatelyEqualHsv(rgbToHsv(193, 196, 224), new double[] {234, 0.14, 0.88});
+ assert approximatelyEqualHsv(rgbToHsv(128, 32, 80), new double[] {330, 0.75, 0.5});
}
/**
@@ -94,35 +55,23 @@ assert approximatelyEqualHsv(
*/
public static int[] hsvToRgb(double hue, double saturation, double value) {
if (hue < 0 || hue > 360) {
- throw new IllegalArgumentException(
- "hue should be between 0 and 360"
- );
+ throw new IllegalArgumentException("hue should be between 0 and 360");
}
if (saturation < 0 || saturation > 1) {
- throw new IllegalArgumentException(
- "saturation should be between 0 and 1"
- );
+ throw new IllegalArgumentException("saturation should be between 0 and 1");
}
if (value < 0 || value > 1) {
- throw new IllegalArgumentException(
- "value should be between 0 and 1"
- );
+ throw new IllegalArgumentException("value should be between 0 and 1");
}
double chroma = value * saturation;
double hueSection = hue / 60;
- double secondLargestComponent =
- chroma * (1 - Math.abs(hueSection % 2 - 1));
+ double secondLargestComponent = chroma * (1 - Math.abs(hueSection % 2 - 1));
double matchValue = value - chroma;
- return getRgbBySection(
- hueSection,
- chroma,
- matchValue,
- secondLargestComponent
- );
+ return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent);
}
/**
@@ -135,21 +84,15 @@ public static int[] hsvToRgb(double hue, double saturation, double value) {
*/
public static double[] rgbToHsv(int red, int green, int blue) {
if (red < 0 || red > 255) {
- throw new IllegalArgumentException(
- "red should be between 0 and 255"
- );
+ throw new IllegalArgumentException("red should be between 0 and 255");
}
if (green < 0 || green > 255) {
- throw new IllegalArgumentException(
- "green should be between 0 and 255"
- );
+ throw new IllegalArgumentException("green should be between 0 and 255");
}
if (blue < 0 || blue > 255) {
- throw new IllegalArgumentException(
- "blue should be between 0 and 255"
- );
+ throw new IllegalArgumentException("blue should be between 0 and 255");
}
double dRed = (double) red / 255;
@@ -172,7 +115,7 @@ public static double[] rgbToHsv(int red, int green, int blue) {
hue = (hue + 360) % 360;
- return new double[] { hue, saturation, value };
+ return new double[] {hue, saturation, value};
}
private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) {
@@ -184,11 +127,7 @@ private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) {
}
private static int[] getRgbBySection(
- double hueSection,
- double chroma,
- double matchValue,
- double secondLargestComponent
- ) {
+ double hueSection, double chroma, double matchValue, double secondLargestComponent) {
int red;
int green;
int blue;
@@ -219,7 +158,7 @@ private static int[] getRgbBySection(
blue = convertToInt(secondLargestComponent + matchValue);
}
- return new int[] { red, green, blue };
+ return new int[] {red, green, blue};
}
private static int convertToInt(double input) {
diff --git a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
index 81c8d9bd1f3c..39e0c4438a6e 100644
--- a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
+++ b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
@@ -58,11 +58,8 @@ public static String convertTurkishToLatin(String param) {
'G',
};
for (int i = 0; i < turkishChars.length; i++) {
- param =
- param.replaceAll(
- new String(new char[] { turkishChars[i] }),
- new String(new char[] { latinChars[i] })
- );
+ param = param.replaceAll(
+ new String(new char[] {turkishChars[i]}), new String(new char[] {latinChars[i]}));
}
return param;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java
index 96c72fc04d6a..5e1c815ff9b3 100644
--- a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java
+++ b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java
@@ -9,7 +9,7 @@ public class CircularBuffer- {
private final AtomicInteger size = new AtomicInteger(0);
public CircularBuffer(int size) {
- //noinspection unchecked
+ // noinspection unchecked
this.buffer = (Item[]) new Object[size];
this.putPointer = new CircularPointer(0, size);
this.getPointer = new CircularPointer(0, size);
@@ -24,8 +24,7 @@ public boolean isFull() {
}
public Item get() {
- if (isEmpty())
- return null;
+ if (isEmpty()) return null;
Item item = buffer[getPointer.getAndIncrement()];
size.decrementAndGet();
@@ -33,8 +32,7 @@ public Item get() {
}
public boolean put(Item item) {
- if (isFull())
- return false;
+ if (isFull()) return false;
buffer[putPointer.getAndIncrement()] = item;
size.incrementAndGet();
@@ -51,8 +49,7 @@ public CircularPointer(int pointer, int max) {
}
public int getAndIncrement() {
- if (pointer == max)
- pointer = 0;
+ if (pointer == max) pointer = 0;
int tmp = pointer;
pointer++;
return tmp;
diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java
index de1f6af64de0..03a1d59e1b20 100644
--- a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java
+++ b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java
@@ -43,7 +43,8 @@ public LFUCache(Integer capacity) {
* This method returns value present in the cache corresponding to the key passed as parameter
*
* @param key for which value is to be retrieved
- * @returns object corresponding to the key passed as parameter, returns null if key is not present in the cache
+ * @returns object corresponding to the key passed as parameter, returns null if key is
+ * not present in the cache
*/
public V get(K key) {
if (this.map.get(key) == null) {
diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java
index 976a4fef1c29..fcb7d975bdb4 100644
--- a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java
+++ b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java
@@ -126,14 +126,10 @@ static final class Entry {
private I key;
private J value;
- public Entry() {}
-
- public Entry(
- Entry preEntry,
- Entry nextEntry,
- I key,
- J value
- ) {
+ public Entry() {
+ }
+
+ public Entry(Entry preEntry, Entry nextEntry, I key, J value) {
this.preEntry = preEntry;
this.nextEntry = nextEntry;
this.key = key;
diff --git a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java
index fc55c4e4d730..30f914968c3b 100644
--- a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java
+++ b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java
@@ -124,14 +124,10 @@ static final class Entry {
private I key;
private J value;
- public Entry() {}
-
- public Entry(
- Entry preEntry,
- Entry nextEntry,
- I key,
- J value
- ) {
+ public Entry() {
+ }
+
+ public Entry(Entry preEntry, Entry nextEntry, I key, J value) {
this.preEntry = preEntry;
this.nextEntry = nextEntry;
this.key = key;
diff --git a/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java b/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java
index 1b6dd0c5470f..fb7783575e57 100644
--- a/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java
+++ b/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java
@@ -44,8 +44,7 @@ public DynamicArray() {
*/
public void add(final E element) {
if (this.size == this.elements.length) {
- this.elements =
- Arrays.copyOf(this.elements, newCapacity(2 * this.capacity));
+ this.elements = Arrays.copyOf(this.elements, newCapacity(2 * this.capacity));
}
this.elements[this.size] = element;
@@ -84,8 +83,7 @@ public E remove(final int index) {
fastRemove(this.elements, index);
if (this.capacity > DEFAULT_CAPACITY && size * 4 <= this.capacity) {
- this.elements =
- Arrays.copyOf(this.elements, newCapacity(this.capacity / 2));
+ this.elements = Arrays.copyOf(this.elements, newCapacity(this.capacity / 2));
}
return oldElement;
}
@@ -116,13 +114,7 @@ private void fastRemove(final Object[] elements, final int index) {
final int newSize = this.size - 1;
if (newSize > index) {
- System.arraycopy(
- elements,
- index + 1,
- elements,
- index,
- newSize - index
- );
+ System.arraycopy(elements, index + 1, elements, index, newSize - index);
}
elements[this.size = newSize] = null;
@@ -144,9 +136,7 @@ private int newCapacity(int capacity) {
*/
@Override
public String toString() {
- return Arrays.toString(
- Arrays.stream(this.elements).filter(Objects::nonNull).toArray()
- );
+ return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray());
}
/**
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java
index fe01cecde42e..ea75e067f949 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java
@@ -1,5 +1,5 @@
/*
- Time Complexity = O(E), where E is equal to the number of edges
+ Time Complexity = O(E), where E is equal to the number of edges
*/
package com.thealgorithms.datastructures.graphs;
@@ -64,13 +64,10 @@ private static class PathAndDistance {
private int distance; // distance advanced so far.
private ArrayList path; // list of visited nodes in this path.
- private int estimated; // heuristic value associated to the last node od the path (current node).
+ private int
+ estimated; // heuristic value associated to the last node od the path (current node).
- public PathAndDistance(
- int distance,
- ArrayList path,
- int estimated
- ) {
+ public PathAndDistance(int distance, ArrayList path, int estimated) {
this.distance = distance;
this.path = path;
this.estimated = estimated;
@@ -90,25 +87,16 @@ public int getEstimated() {
private void printSolution() {
if (this.path != null) {
- System.out.println(
- "Optimal path: " +
- this.path +
- ", distance: " +
- this.distance
- );
+ System.out.println("Optimal path: " + this.path + ", distance: " + this.distance);
} else {
- System.out.println(
- "There is no path available to connect the points"
- );
+ System.out.println("There is no path available to connect the points");
}
}
}
private static void initializeGraph(Graph graph, ArrayList data) {
for (int i = 0; i < data.size(); i += 4) {
- graph.addEdge(
- new Edge(data.get(i), data.get(i + 1), data.get(i + 2))
- );
+ graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2)));
}
/*
.x. node
@@ -165,123 +153,24 @@ public static void main(String[] args) {
};
Graph graph = new Graph(20);
- ArrayList graphData = new ArrayList<>(
- Arrays.asList(
- 0,
- 19,
- 75,
- null,
- 0,
- 15,
- 140,
- null,
- 0,
- 16,
- 118,
- null,
- 19,
- 12,
- 71,
- null,
- 12,
- 15,
- 151,
- null,
- 16,
- 9,
- 111,
- null,
- 9,
- 10,
- 70,
- null,
- 10,
- 3,
- 75,
- null,
- 3,
- 2,
- 120,
- null,
- 2,
- 14,
- 146,
- null,
- 2,
- 13,
- 138,
- null,
- 2,
- 6,
- 115,
- null,
- 15,
- 14,
- 80,
- null,
- 15,
- 5,
- 99,
- null,
- 14,
- 13,
- 97,
- null,
- 5,
- 1,
- 211,
- null,
- 13,
- 1,
- 101,
- null,
- 6,
- 1,
- 160,
- null,
- 1,
- 17,
- 85,
- null,
- 17,
- 7,
- 98,
- null,
- 7,
- 4,
- 86,
- null,
- 17,
- 18,
- 142,
- null,
- 18,
- 8,
- 92,
- null,
- 8,
- 11,
- 87
- )
- );
+ ArrayList graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null, 0, 15, 140,
+ null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null, 16, 9, 111, null, 9, 10,
+ 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, 146, null, 2, 13, 138, null, 2, 6,
+ 115, null, 15, 14, 80, null, 15, 5, 99, null, 14, 13, 97, null, 5, 1, 211, null, 13, 1,
+ 101, null, 6, 1, 160, null, 1, 17, 85, null, 17, 7, 98, null, 7, 4, 86, null, 17, 18,
+ 142, null, 18, 8, 92, null, 8, 11, 87));
initializeGraph(graph, graphData);
PathAndDistance solution = aStar(3, 1, graph, heuristic);
solution.printSolution();
}
- public static PathAndDistance aStar(
- int from,
- int to,
- Graph graph,
- int[] heuristic
- ) {
+ public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) {
// nodes are prioritised by the less value of the current distance of their paths, and the
// estimated value
// given by the heuristic function to reach the destination point from the current point.
PriorityQueue queue = new PriorityQueue<>(
- Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))
- );
+ Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
// dummy data to start the algorithm from the beginning point
queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0));
@@ -290,34 +179,25 @@ public static PathAndDistance aStar(
PathAndDistance currentData = new PathAndDistance(-1, null, -1);
while (!queue.isEmpty() && !solutionFound) {
currentData = queue.poll(); // first in the queue, best node so keep exploring.
- int currentPosition = currentData
- .getPath()
- .get(currentData.getPath().size() - 1); // current node.
+ int currentPosition
+ = currentData.getPath().get(currentData.getPath().size() - 1); // current node.
if (currentPosition == to) {
solutionFound = true;
} else {
for (Edge edge : graph.getNeighbours(currentPosition)) {
if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles
- ArrayList updatedPath = new ArrayList<>(
- currentData.getPath()
- );
- updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance,
+ ArrayList updatedPath = new ArrayList<>(currentData.getPath());
+ updatedPath.add(
+ edge.getTo()); // Add the new node to the path, update the distance,
// and the heuristic function value associated to that path.
- queue.add(
- new PathAndDistance(
- currentData.getDistance() + edge.getWeight(),
- updatedPath,
- heuristic[edge.getTo()]
- )
- );
+ queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(),
+ updatedPath, heuristic[edge.getTo()]));
}
}
}
}
- return (solutionFound)
- ? currentData
- : new PathAndDistance(-1, null, -1);
- // Out of while loop, if there is a solution, the current Data stores the optimal path, and its
- // distance
+ return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1);
+ // Out of while loop, if there is a solution, the current Data stores the optimal path, and
+ // its distance
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
index aba377329aa0..2998f7e90b52 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
@@ -2,8 +2,10 @@
import java.util.*;
-class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have
-start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{
+class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs
+in form of edges which have start vertex, end vertex and weights. Vertices should be labelled with a
+number between 0 and total number of vertices-1,both inclusive*/
+{
int vertex, edge;
private Edge[] edges;
@@ -49,7 +51,8 @@ public static void main(String[] args) {
obj.go();
}
- public void go() { // shows distance to all vertices // Interactive run for understanding the class first time. Assumes source vertex is 0 and
+ public void go() { // shows distance to all vertices // Interactive run for understanding the
+ // class first time. Assumes source vertex is 0 and
Scanner sc = new Scanner(System.in); // Grab scanner object for user input
int i, v, e, u, ve, w, j, neg = 0;
System.out.println("Enter no. of vertices and edges please");
@@ -63,7 +66,8 @@ public void go() { // shows distance to all vertices // Interactive run for unde
w = sc.nextInt();
arr[i] = new Edge(u, ve, w);
}
- int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance between source
+ int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance
+ // between source
// and all vertices
int[] p = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) {
@@ -73,10 +77,8 @@ public void go() { // shows distance to all vertices // Interactive run for unde
p[0] = -1;
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
- if (
- dist[arr[j].u] != Integer.MAX_VALUE &&
- dist[arr[j].v] > dist[arr[j].u] + arr[j].w
- ) {
+ if (dist[arr[j].u] != Integer.MAX_VALUE
+ && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u;
}
@@ -84,10 +86,7 @@ public void go() { // shows distance to all vertices // Interactive run for unde
}
// Final cycle for negative checking
for (j = 0; j < e; j++) {
- if (
- dist[arr[j].u] != Integer.MAX_VALUE &&
- dist[arr[j].v] > dist[arr[j].u] + arr[j].w
- ) {
+ if (dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
neg = 1;
System.out.println("Negative cycle");
break;
@@ -113,9 +112,13 @@ public void go() { // shows distance to all vertices // Interactive run for unde
* @param end Ending vertex
* @param Edge Array of edges
*/
- public void show(int source, int end, Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should
+ public void show(int source, int end,
+ Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray()
+ // method // Just shows results of computation, if graph is passed to it. The
+ // graph should
int i, j, v = vertex, e = edge, neg = 0;
- double[] dist = new double[v]; // Distance array for holding the finalized shortest path distance between source
+ double[] dist = new double[v]; // Distance array for holding the finalized shortest path
+ // distance between source
// and all vertices
int[] p = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) {
@@ -125,10 +128,8 @@ public void show(int source, int end, Edge[] arr) { // be created by using addEd
p[source] = -1;
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
- if (
- (int) dist[arr[j].u] != Integer.MAX_VALUE &&
- dist[arr[j].v] > dist[arr[j].u] + arr[j].w
- ) {
+ if ((int) dist[arr[j].u] != Integer.MAX_VALUE
+ && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u;
}
@@ -136,10 +137,8 @@ public void show(int source, int end, Edge[] arr) { // be created by using addEd
}
// Final cycle for negative checking
for (j = 0; j < e; j++) {
- if (
- (int) dist[arr[j].u] != Integer.MAX_VALUE &&
- dist[arr[j].v] > dist[arr[j].u] + arr[j].w
- ) {
+ if ((int) dist[arr[j].u] != Integer.MAX_VALUE
+ && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
neg = 1;
System.out.println("Negative cycle");
break;
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java
index 651b3e617794..0bdc5340f897 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java
@@ -17,11 +17,7 @@
public class BipartiteGrapfDFS {
private static boolean bipartite(
- int V,
- ArrayList> adj,
- int[] color,
- int node
- ) {
+ int V, ArrayList> adj, int[] color, int node) {
if (color[node] == -1) {
color[node] = 1;
}
@@ -38,10 +34,7 @@ private static boolean bipartite(
return true;
}
- public static boolean isBipartite(
- int V,
- ArrayList> adj
- ) {
+ public static boolean isBipartite(int V, ArrayList> adj) {
// Code here
int[] color = new int[V + 1];
Arrays.fill(color, -1);
@@ -57,9 +50,7 @@ public static boolean isBipartite(
}
public static void main(String[] args) throws IOException {
- BufferedReader read = new BufferedReader(
- new InputStreamReader(System.in)
- );
+ BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine().trim());
while (t-- > 0) {
String[] S = read.readLine().trim().split(" ");
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java
index 306abd7e39df..b0add255f59a 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java
@@ -137,11 +137,7 @@ public static void main(String[] args) {
graphInts.addEdge(8, 10);
graphInts.addEdge(10, 8);
- System.out.println(
- "Amount of different char-graphs: " + graphChars.countGraphs()
- );
- System.out.println(
- "Amount of different int-graphs: " + graphInts.countGraphs()
- );
+ System.out.println("Amount of different char-graphs: " + graphChars.countGraphs());
+ System.out.println("Amount of different int-graphs: " + graphInts.countGraphs());
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java
index 3d6e8a51ebd6..5d5bd3c7469c 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java
@@ -24,9 +24,7 @@ public Cycle() {
visited[i] = false;
}
- System.out.println(
- "Enter the details of each edges "
- );
+ System.out.println("Enter the details of each edges ");
for (int i = 0; i < edges; i++) {
int start, end;
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
index 31ed7ef2de2a..1811d4a109ca 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
@@ -1,6 +1,6 @@
/*
Refer https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/
-for better understanding
+for better understanding
*/
package com.thealgorithms.datastructures.graphs;
@@ -45,12 +45,8 @@ void dijkstra(int[][] graph, int src) {
Set[u] = true;
for (int v = 0; v < k; v++) {
- if (
- !Set[v] &&
- graph[u][v] != 0 &&
- dist[u] != Integer.MAX_VALUE &&
- dist[u] + graph[u][v] < dist[v]
- ) {
+ if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE
+ && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
@@ -61,23 +57,23 @@ void dijkstra(int[][] graph, int src) {
public static void main(String[] args) {
int[][] graph = new int[][] {
- { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
- { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
- { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
- { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
- { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
- { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
- { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
- { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
- { 0, 0, 2, 0, 0, 0, 6, 7, 0 },
+ {0, 4, 0, 0, 0, 0, 0, 8, 0},
+ {4, 0, 8, 0, 0, 0, 0, 11, 0},
+ {0, 8, 0, 7, 0, 4, 0, 0, 2},
+ {0, 0, 7, 0, 9, 14, 0, 0, 0},
+ {0, 0, 0, 9, 0, 10, 0, 0, 0},
+ {0, 0, 4, 14, 10, 0, 2, 0, 0},
+ {0, 0, 0, 0, 0, 2, 0, 1, 6},
+ {8, 11, 0, 0, 0, 0, 1, 0, 7},
+ {0, 0, 2, 0, 0, 0, 6, 7, 0},
};
dijkstras t = new dijkstras();
t.dijkstra(graph, 0);
- } //main
-} //djikstras
+ } // main
+} // djikstras
/*
OUTPUT :
-Vertex Distance
+Vertex Distance
0 0
1 4
2 12
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
index bf3ef8e6eab9..673b795b1563 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
@@ -9,42 +9,32 @@ public class FloydWarshall {
public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices) {
- DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source
+ DistanceMatrix = new int[numberofvertices + 1][numberofvertices
+ + 1]; // stores the value of distance from all the possible path form the source
// vertex to destination vertex
// The matrix is initialized with 0's by default
this.numberofvertices = numberofvertices;
}
- public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
+ public void floydwarshall(
+ int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
for (int source = 1; source <= numberofvertices; source++) {
- for (
- int destination = 1;
- destination <= numberofvertices;
- destination++
- ) {
- DistanceMatrix[source][destination] =
- AdjacencyMatrix[source][destination];
+ for (int destination = 1; destination <= numberofvertices; destination++) {
+ DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination];
}
}
- for (
- int intermediate = 1;
- intermediate <= numberofvertices;
- intermediate++
- ) {
+ for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) {
for (int source = 1; source <= numberofvertices; source++) {
- for (
- int destination = 1;
- destination <= numberofvertices;
- destination++
- ) {
- if (
- DistanceMatrix[source][intermediate] +
- DistanceMatrix[intermediate][destination] <
- DistanceMatrix[source][destination]
- ) { // calculated distance it get replaced as new shortest distance // if the new distance calculated is less then the earlier shortest
- DistanceMatrix[source][destination] =
- DistanceMatrix[source][intermediate] +
- DistanceMatrix[intermediate][destination];
+ for (int destination = 1; destination <= numberofvertices; destination++) {
+ if (DistanceMatrix[source][intermediate]
+ + DistanceMatrix[intermediate][destination]
+ < DistanceMatrix[source]
+ [destination]) { // calculated distance it get replaced as
+ // new shortest distance // if the new
+ // distance calculated is less then the
+ // earlier shortest
+ DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate]
+ + DistanceMatrix[intermediate][destination];
}
}
}
@@ -55,11 +45,7 @@ public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the dista
System.out.println();
for (int source = 1; source <= numberofvertices; source++) {
System.out.print(source + "\t");
- for (
- int destination = 1;
- destination <= numberofvertices;
- destination++
- ) {
+ for (int destination = 1; destination <= numberofvertices; destination++) {
System.out.print(DistanceMatrix[source][destination] + "\t");
}
System.out.println();
@@ -70,15 +56,10 @@ public static void main(String... arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of vertices");
int numberOfVertices = scan.nextInt();
- int[][] adjacencyMatrix = new int[numberOfVertices +
- 1][numberOfVertices + 1];
+ int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int source = 1; source <= numberOfVertices; source++) {
- for (
- int destination = 1;
- destination <= numberOfVertices;
- destination++
- ) {
+ for (int destination = 1; destination <= numberOfVertices; destination++) {
adjacencyMatrix[source][destination] = scan.nextInt();
if (source == destination) {
adjacencyMatrix[source][destination] = 0;
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
index 1430f1a246dd..d4d6a381e89e 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
@@ -21,7 +21,7 @@ public int[] findHamiltonianCycle(int[][] graph) {
this.V = graph.length;
this.cycle = new int[this.V + 1];
- //Initialize path array with -1 value
+ // Initialize path array with -1 value
for (int i = 0; i < this.cycle.length; i++) {
this.cycle[i] = -1;
}
@@ -41,13 +41,15 @@ public int[] findHamiltonianCycle(int[][] graph) {
return cycle;
}
- /** function to find paths recursively
+ /**
+ * function to find paths recursively
* Find paths recursively from given vertex
* @param vertex Vertex from which path is to be found
* @returns true if path is found false otherwise
*/
public boolean isPathFound(int vertex) {
- boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.V;
+ boolean isLastVertexConnectedToStart
+ = this.graph[vertex][0] == 1 && this.pathCount == this.V;
if (isLastVertexConnectedToStart) {
return true;
}
@@ -83,7 +85,8 @@ public boolean isPathFound(int vertex) {
return false;
}
- /** function to check if path is already selected
+ /**
+ * function to check if path is already selected
* Check if path is already selected
* @param vertex Starting vertex
*/
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
index 350d7d270b2e..e978ddc1e764 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
@@ -133,7 +133,7 @@ ArrayList topSortOrder() {
public class KahnsAlgorithm {
public static void main(String[] args) {
- //Graph definition and initialization
+ // Graph definition and initialization
AdjacencyList graph = new AdjacencyList<>();
graph.addEdge("a", "b");
graph.addEdge("c", "a");
@@ -144,7 +144,7 @@ public static void main(String[] args) {
TopologicalSort topSort = new TopologicalSort<>(graph);
- //Printing the order
+ // Printing the order
for (String s : topSort.topSortOrder()) {
System.out.print(s + " ");
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
index f24791dce596..c24046f510af 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
@@ -7,17 +7,18 @@
/**
* Java program that implements Kosaraju Algorithm.
* @author Shivanagouda S A (https://github.com/shivu2002a)
- *
+ *
*/
/**
- * Kosaraju algorithm is a linear time algorithm to find the strongly connected components of a
- directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the transpose
- graph (same graph with all the edges reversed) has exactly the same SCCs as the original graph.
-
- * A graph is said to be strongly connected if every vertex is reachable from every other vertex.
- The SCCs of a directed graph form a partition into subgraphs that are themselves strongly connected.
- Single node is always a SCC.
+ * Kosaraju algorithm is a linear time algorithm to find the strongly connected components of a
+ directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the
+ transpose graph (same graph with all the edges reversed) has exactly the same SCCs as the original
+ graph.
+
+ * A graph is said to be strongly connected if every vertex is reachable from every other vertex.
+ The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
+ connected. Single node is always a SCC.
* Example:
@@ -26,19 +27,20 @@
| / | \ /
| / | \ /
v / v \ /
- 1 5 --> 6
+ 1 5 --> 6
For the above graph, the SCC list goes as follows:
- 0, 1, 2
+ 0, 1, 2
3
4, 5, 6
7
-
+
We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
{@summary}
- * Kosaraju Algorithm:
- 1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges sorted by lowest finish time.
+ * Kosaraju Algorithm:
+ 1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges
+ sorted by lowest finish time.
2. Find the transpose graph by reversing the edges.
3. Pop nodes one by one from the stack and again to DFS on the modified graph.
@@ -48,7 +50,7 @@
| / | \ /
| / | \ /
| v | v v
- 1 5 <--- 6
+ 1 5 <--- 6
We can observe that this graph has the same SCC as that of original graph.
@@ -59,33 +61,33 @@ public class Kosaraju {
// Sort edges according to lowest finish time
Stack stack = new Stack();
- //Store each component
+ // Store each component
private List scc = new ArrayList<>();
- //All the strongly connected components
+ // All the strongly connected components
private List
> sccsList = new ArrayList<>();
/**
- *
+ *
* @param v Node count
* @param list Adjacency list of graph
* @return List of SCCs
*/
- public List> kosaraju(int v, List> list){
-
+ public List> kosaraju(int v, List> list) {
+
sortEdgesByLowestFinishTime(v, list);
-
+
List> transposeGraph = createTransposeMatrix(v, list);
findStronglyConnectedComponents(v, transposeGraph);
-
+
return sccsList;
}
- private void sortEdgesByLowestFinishTime(int v, List> list){
+ private void sortEdgesByLowestFinishTime(int v, List> list) {
int[] vis = new int[v];
for (int i = 0; i < v; i++) {
- if(vis[i] == 0){
+ if (vis[i] == 0) {
dfs(i, vis, list);
}
}
@@ -105,15 +107,15 @@ private List> createTransposeMatrix(int v, List> lis
}
/**
- *
+ *
* @param v Node count
* @param transposeGraph Transpose of the given adjacency list
*/
- public void findStronglyConnectedComponents(int v, List> transposeGraph){
+ public void findStronglyConnectedComponents(int v, List> transposeGraph) {
int[] vis = new int[v];
while (!stack.isEmpty()) {
var node = stack.pop();
- if(vis[node] == 0){
+ if (vis[node] == 0) {
dfs2(node, vis, transposeGraph);
sccsList.add(scc);
scc = new ArrayList<>();
@@ -121,24 +123,21 @@ public void findStronglyConnectedComponents(int v, List> transpose
}
}
- //Dfs to store the nodes in order of lowest finish time
- private void dfs(int node, int[] vis, List> list){
+ // Dfs to store the nodes in order of lowest finish time
+ private void dfs(int node, int[] vis, List> list) {
vis[node] = 1;
- for(Integer neighbour : list.get(node)){
- if(vis[neighbour] == 0)
- dfs(neighbour, vis, list);
+ for (Integer neighbour : list.get(node)) {
+ if (vis[neighbour] == 0) dfs(neighbour, vis, list);
}
stack.push(node);
}
- //Dfs to find all the nodes of each strongly connected component
- private void dfs2(int node, int[] vis, List> list){
+ // Dfs to find all the nodes of each strongly connected component
+ private void dfs2(int node, int[] vis, List> list) {
vis[node] = 1;
- for(Integer neighbour : list.get(node)){
- if(vis[neighbour] == 0)
- dfs2(neighbour, vis, list);
+ for (Integer neighbour : list.get(node)) {
+ if (vis[neighbour] == 0) dfs2(neighbour, vis, list);
}
scc.add(node);
}
-
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java
index 5d326576ffec..3c41a30b86a8 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java
@@ -15,8 +15,8 @@
public class Kruskal {
- // Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number of
- // vertices
+ // Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number
+ // of vertices
private static class Edge {
private int from;
@@ -30,12 +30,7 @@ public Edge(int from, int to, int weight) {
}
}
- private static void addEdge(
- HashSet[] graph,
- int from,
- int to,
- int weight
- ) {
+ private static void addEdge(HashSet[] graph, int from, int to, int weight) {
graph[from].add(new Edge(from, to, weight));
}
@@ -58,9 +53,7 @@ public static void main(String[] args) {
System.out.println("Initial Graph: ");
for (int i = 0; i < graph.length; i++) {
for (Edge edge : graph[i]) {
- System.out.println(
- i + " <-- weight " + edge.weight + " --> " + edge.to
- );
+ System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to);
}
}
@@ -70,9 +63,7 @@ public static void main(String[] args) {
System.out.println("\nMinimal Graph: ");
for (int i = 0; i < solGraph.length; i++) {
for (Edge edge : solGraph[i]) {
- System.out.println(
- i + " <-- weight " + edge.weight + " --> " + edge.to
- );
+ System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to);
}
}
}
@@ -83,9 +74,8 @@ public HashSet[] kruskal(HashSet[] graph) {
// captain of i, stores the set with all the connected nodes to i
HashSet[] connectedGroups = new HashSet[nodes];
HashSet[] minGraph = new HashSet[nodes];
- PriorityQueue edges = new PriorityQueue<>(
- (Comparator.comparingInt(edge -> edge.weight))
- );
+ PriorityQueue edges
+ = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight)));
for (int i = 0; i < nodes; i++) {
minGraph[i] = new HashSet<>();
connectedGroups[i] = new HashSet<>();
@@ -98,18 +88,12 @@ public HashSet[] kruskal(HashSet[] graph) {
while (connectedElements != nodes && !edges.isEmpty()) {
Edge edge = edges.poll();
// This if avoids cycles
- if (
- !connectedGroups[captain[edge.from]].contains(edge.to) &&
- !connectedGroups[captain[edge.to]].contains(edge.from)
- ) {
+ if (!connectedGroups[captain[edge.from]].contains(edge.to)
+ && !connectedGroups[captain[edge.to]].contains(edge.from)) {
// merge sets of the captains of each point connected by the edge
- connectedGroups[captain[edge.from]].addAll(
- connectedGroups[captain[edge.to]]
- );
+ connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]);
// update captains of the elements merged
- connectedGroups[captain[edge.from]].forEach(i ->
- captain[i] = captain[edge.from]
- );
+ connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]);
// add Edge to minimal graph
addEdge(minGraph, edge.from, edge.to, edge.weight);
// count how many elements have been merged
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
index 7593a9cfc253..701eec60b7bf 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
@@ -71,9 +71,7 @@ class AdjacencyMatrixGraph {
public AdjacencyMatrixGraph(int givenNumberOfVertices) {
this.setNumberOfVertices(givenNumberOfVertices);
this.setNumberOfEdges(0);
- this.setAdjacency(
- new int[givenNumberOfVertices][givenNumberOfVertices]
- );
+ this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
for (int i = 0; i < givenNumberOfVertices; i++) {
for (int j = 0; j < givenNumberOfVertices; j++) {
this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
@@ -247,11 +245,7 @@ public List depthFirstOrder(int startVertex) {
* has been visited
* @param orderList the list to add vertices to as they are visited
*/
- private void depthFirstOrder(
- int currentVertex,
- boolean[] visited,
- List orderList
- ) {
+ private void depthFirstOrder(int currentVertex, boolean[] visited, List orderList) {
// If this vertex has already been visited, do nothing and return
if (visited[currentVertex]) {
return;
@@ -264,11 +258,9 @@ private void depthFirstOrder(
// Get the adjacency array for this vertex
int[] adjacent = _adjacency[currentVertex];
- for (
- int i = 0;
- i < adjacent.length;
- i++
- ) { // we are considering exploring, recurse on it // If an edge exists between the currentVertex and the vertex
+ for (int i = 0; i < adjacent.length;
+ i++) { // we are considering exploring, recurse on it // If an edge exists between the
+ // currentVertex and the vertex
if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) {
depthFirstOrder(i, visited, orderList);
}
@@ -317,11 +309,9 @@ public List breadthFirstOrder(int startVertex) {
// Get the adjacency array for the currentVertex and
// check each node
int[] adjacent = _adjacency[currentVertex];
- for (
- int vertex = 0;
- vertex < adjacent.length;
- vertex++
- ) { // vertex we are considering exploring, we add it to the queue // If an edge exists between the current vertex and the
+ for (int vertex = 0; vertex < adjacent.length;
+ vertex++) { // vertex we are considering exploring, we add it to the queue // If an
+ // edge exists between the current vertex and the
if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) {
queue.add(vertex);
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java
index 893b835e0ed9..e187628928d4 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java
@@ -31,9 +31,7 @@ int minKey(int[] key, Boolean[] mstSet) {
void printMST(int[] parent, int n, int[][] graph) {
System.out.println("Edge Weight");
for (int i = 1; i < V; i++) {
- System.out.println(
- parent[i] + " - " + i + " " + graph[i][parent[i]]
- );
+ System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]);
}
}
@@ -72,17 +70,12 @@ void primMST(int[][] graph) {
// Update key value and parent index of the adjacent
// vertices of the picked vertex. Consider only those
// vertices which are not yet included in MST
- for (
- int v = 0;
- v < V;
- v++
- ) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is false for vertices not yet included in MST // graph[u][v] is non zero only for adjacent vertices of m
+ for (int v = 0; v < V;
+ v++) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is
+ // false for vertices not yet included in MST // graph[u][v] is non zero only
+ // for adjacent vertices of m
{
- if (
- graph[u][v] != 0 &&
- !mstSet[v] &&
- graph[u][v] < key[v]
- ) {
+ if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
@@ -104,11 +97,11 @@ public static void main(String[] args) {
9 */
PrimMST t = new PrimMST();
int[][] graph = new int[][] {
- { 0, 2, 0, 6, 0 },
- { 2, 0, 3, 8, 5 },
- { 0, 3, 0, 0, 7 },
- { 6, 8, 0, 0, 9 },
- { 0, 5, 7, 9, 0 },
+ {0, 2, 0, 6, 0},
+ {2, 0, 3, 8, 5},
+ {0, 3, 0, 0, 7},
+ {6, 8, 0, 0, 9},
+ {0, 5, 7, 9, 0},
};
// Print the solution
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
index 497daeca4428..e63de0ad9ad3 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
@@ -8,16 +8,16 @@
/**
* Java program that implements Tarjan's Algorithm.
* @author Shivanagouda S A (https://github.com/shivu2002a)
- *
+ *
*/
/**
- * Tarjan's algorithm is a linear time algorithm to find the strongly connected components of a
- directed graph, which, from here onwards will be referred as SCC.
-
- * A graph is said to be strongly connected if every vertex is reachable from every other vertex.
- The SCCs of a directed graph form a partition into subgraphs that are themselves strongly connected.
- Single node is always a SCC.
+ * Tarjan's algorithm is a linear time algorithm to find the strongly connected components of a
+ directed graph, which, from here onwards will be referred as SCC.
+
+ * A graph is said to be strongly connected if every vertex is reachable from every other vertex.
+ The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
+ connected. Single node is always a SCC.
* Example:
0 --------> 1 -------> 3 --------> 4
@@ -38,24 +38,25 @@
1, 2, 0
3
4
-
+
We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
{@summary}
- Tarjan's Algorithm:
- * DFS search produces a DFS tree
- * Strongly Connected Components form subtrees of the DFS tree.
- * If we can find the head of these subtrees, we can get all the nodes in that subtree (including the head)
- and that will be one SCC.
- * There is no back edge from one SCC to another (here can be cross edges, but they will not be used).
+ Tarjan's Algorithm:
+ * DFS search produces a DFS tree
+ * Strongly Connected Components form subtrees of the DFS tree.
+ * If we can find the head of these subtrees, we can get all the nodes in that subtree (including
+ the head) and that will be one SCC.
+ * There is no back edge from one SCC to another (here can be cross edges, but they will not be
+ used).
- * Kosaraju Algorithm aims at doing the same but uses two DFS traversalse whereas Tarjan’s algorithm does
- the same in a single DFS, which leads to much lower constant factors in the latter.
+ * Kosaraju Algorithm aims at doing the same but uses two DFS traversalse whereas Tarjan’s
+ algorithm does the same in a single DFS, which leads to much lower constant factors in the latter.
*/
public class TarjansAlgorithm {
- //Timer for tracking lowtime and insertion time
+ // Timer for tracking lowtime and insertion time
private int Time;
private List> SCClist = new ArrayList>();
@@ -66,15 +67,15 @@ public List> stronglyConnectedComponents(int V, List
// insertionTime:Time when a node is visited 1st time while DFS traversal
- // lowTime: indicates the earliest visited vertex (the vertex with minimum insertion time) that can
- // be reached from a subtree rooted with a particular node.
+ // lowTime: indicates the earliest visited vertex (the vertex with minimum insertion time)
+ // that can be reached from a subtree rooted with a particular node.
int[] lowTime = new int[V];
int[] insertionTime = new int[V];
for (int i = 0; i < V; i++) {
insertionTime[i] = -1;
lowTime[i] = -1;
}
-
+
// To check if element is present in stack
boolean[] isInStack = new boolean[V];
@@ -90,36 +91,36 @@ public List> stronglyConnectedComponents(int V, List
}
private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime,
- boolean[] isInStack, Stack st, List> graph) {
+ boolean[] isInStack, Stack st, List> graph) {
// Initialize insertion time and lowTime value of current node
insertionTime[u] = Time;
lowTime[u] = Time;
Time += 1;
- //Push current node into stack
+ // Push current node into stack
isInStack[u] = true;
st.push(u);
// Go through all vertices adjacent to this
for (Integer vertex : graph.get(u)) {
- //If the adjacent node is unvisited, do DFS
+ // If the adjacent node is unvisited, do DFS
if (insertionTime[vertex] == -1) {
stronglyConnCompsUtil(vertex, lowTime, insertionTime, isInStack, st, graph);
- //update lowTime for the current node comparing lowtime of adj node
+ // update lowTime for the current node comparing lowtime of adj node
lowTime[u] = Math.min(lowTime[u], lowTime[vertex]);
} else if (isInStack[vertex]) {
- //If adj node is in stack, update low
+ // If adj node is in stack, update low
lowTime[u] = Math.min(lowTime[u], insertionTime[vertex]);
}
}
- //If lowtime and insertion time are same, current node is the head of an SCC
- // head node found, get all the nodes in this SCC
+ // If lowtime and insertion time are same, current node is the head of an SCC
+ // head node found, get all the nodes in this SCC
if (lowTime[u] == insertionTime[u]) {
int w = -1;
var scc = new ArrayList();
- //Stack has all the nodes of the current SCC
+ // Stack has all the nodes of the current SCC
while (w != u) {
w = st.pop();
scc.add(w);
@@ -128,5 +129,4 @@ private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime,
SCClist.add(scc);
}
}
-
}
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java
index a7f1cbf14b37..d4f8cda9e74d 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java
@@ -33,7 +33,8 @@ public HashMapCuckooHashing(int tableSize) {
}
/**
- * The 2 Hash Functions takes a given key and finds an index based on its data, 2 distinctive ways to minimize collisions
+ * The 2 Hash Functions takes a given key and finds an index based on its data, 2 distinctive
+ * ways to minimize collisions
*
* @param key the desired key to be converted
* @return int an index corresponding to the key
@@ -57,10 +58,10 @@ public int hashFunction2(int key) {
}
/**
- * inserts the key into the hash map by wrapping it as an Integer object, then uses while loop to insert new key
- * if desired place is empty, return.
- * if already occupied, continue while loop over the new key that has just been pushed out.
- * if while loop continues more than Thresh, rehash table to new size, then push again.
+ * inserts the key into the hash map by wrapping it as an Integer object, then uses while loop
+ * to insert new key if desired place is empty, return. if already occupied, continue while loop
+ * over the new key that has just been pushed out. if while loop continues more than Thresh,
+ * rehash table to new size, then push again.
*
* @param key the desired key to be inserted in the hash map
*/
@@ -70,26 +71,19 @@ public void insertKey2HashTable(int key) {
int hash, loopCounter = 0;
if (isFull()) {
- System.out.println(
- "Hash table is full, lengthening & rehashing table"
- );
+ System.out.println("Hash table is full, lengthening & rehashing table");
reHashTableIncreasesTableSize();
}
if (checkTableContainsKey(key)) {
- throw new IllegalArgumentException(
- "Key already inside, no duplicates allowed"
- );
+ throw new IllegalArgumentException("Key already inside, no duplicates allowed");
}
while (loopCounter <= thresh) {
loopCounter++;
hash = hashFunction1(key);
- if (
- (buckets[hash] == null) ||
- Objects.equals(buckets[hash], AVAILABLE)
- ) {
+ if ((buckets[hash] == null) || Objects.equals(buckets[hash], AVAILABLE)) {
buckets[hash] = wrappedInt;
size++;
checkLoadFactor();
@@ -116,16 +110,14 @@ public void insertKey2HashTable(int key) {
buckets[hash] = wrappedInt;
wrappedInt = temp;
}
- System.out.println(
- "Infinite loop occurred, lengthening & rehashing table"
- );
+ System.out.println("Infinite loop occurred, lengthening & rehashing table");
reHashTableIncreasesTableSize();
insertKey2HashTable(key);
}
/**
- * creates new HashMapCuckooHashing object, then inserts each of the elements in the previous table to it with its new hash functions.
- * then refers current array to new table.
+ * creates new HashMapCuckooHashing object, then inserts each of the elements in the previous
+ * table to it with its new hash functions. then refers current array to new table.
*
*/
public void reHashTableIncreasesTableSize() {
@@ -164,9 +156,7 @@ public void deleteKeyFromHashTable(int key) {
size--;
return;
}
- throw new IllegalArgumentException(
- "Key " + key + " already inside, no duplicates allowed"
- );
+ throw new IllegalArgumentException("Key " + key + " already inside, no duplicates allowed");
}
/**
@@ -177,9 +167,7 @@ public void displayHashtable() {
if ((buckets[i] == null) || Objects.equals(buckets[i], AVAILABLE)) {
System.out.println("Bucket " + i + ": Empty");
} else {
- System.out.println(
- "Bucket " + i + ": " + buckets[i].toString()
- );
+ System.out.println("Bucket " + i + ": " + buckets[i].toString());
}
}
System.out.println();
@@ -202,11 +190,9 @@ public int findKeyInTable(int key) {
if (Objects.equals(buckets[hash], wrappedInt)) return hash;
hash = hashFunction2(key);
- if (
- !Objects.equals(buckets[hash], wrappedInt)
- ) throw new IllegalArgumentException(
- "Key " + key + " not found in table"
- ); else {
+ if (!Objects.equals(buckets[hash], wrappedInt))
+ throw new IllegalArgumentException("Key " + key + " not found in table");
+ else {
return hash;
}
}
@@ -218,16 +204,8 @@ public int findKeyInTable(int key) {
* @return int the index where the key is located
*/
public boolean checkTableContainsKey(int key) {
- return (
- (
- buckets[hashFunction1(key)] != null &&
- buckets[hashFunction1(key)].equals(key)
- ) ||
- (
- buckets[hashFunction2(key)] != null &&
- buckets[hashFunction2(key)] == key
- )
- );
+ return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key))
+ || (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key));
}
/**
@@ -237,10 +215,7 @@ public boolean checkTableContainsKey(int key) {
public double checkLoadFactor() {
double factor = (double) size / tableSize;
if (factor > .7) {
- System.out.printf(
- "Load factor is %.2f , rehashing table\n",
- factor
- );
+ System.out.printf("Load factor is %.2f , rehashing table\n", factor);
reHashTableIncreasesTableSize();
}
return factor;
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java
index f89f9204299b..ad3f617cef5a 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java
@@ -15,9 +15,7 @@
public class Intersection {
public static List intersection(int[] arr1, int[] arr2) {
- if (
- arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0
- ) {
+ if (arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0) {
return Collections.emptyList();
}
Map cnt = new HashMap<>(16);
@@ -34,5 +32,6 @@ public static List intersection(int[] arr1, int[] arr2) {
return res;
}
- private Intersection() {}
+ private Intersection() {
+ }
}
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java
index f6aa18b4c60b..d68e01284ddd 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java
@@ -20,31 +20,27 @@ public static void main(String[] args) {
choice = In.nextInt();
switch (choice) {
- case 1:
- {
- System.out.println("Enter the Key: ");
- key = In.nextInt();
- h.insertHash(key);
- break;
- }
- case 2:
- {
- System.out.println("Enter the Key delete: ");
- key = In.nextInt();
- h.deleteHash(key);
- break;
- }
- case 3:
- {
- System.out.println("Print table");
- h.displayHashtable();
- break;
- }
- case 4:
- {
- In.close();
- return;
- }
+ case 1: {
+ System.out.println("Enter the Key: ");
+ key = In.nextInt();
+ h.insertHash(key);
+ break;
+ }
+ case 2: {
+ System.out.println("Enter the Key delete: ");
+ key = In.nextInt();
+ h.deleteHash(key);
+ break;
+ }
+ case 3: {
+ System.out.println("Print table");
+ h.displayHashtable();
+ break;
+ }
+ case 4: {
+ In.close();
+ return;
+ }
}
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java
index 90ff839c7ce1..94d370b66976 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java
@@ -24,59 +24,41 @@ public static void main(String[] args) {
choice = In.nextInt();
switch (choice) {
- case 1:
- {
- System.out.println("Enter the Key: ");
- key = In.nextInt();
- h.insertKey2HashTable(key);
- break;
- }
- case 2:
- {
- System.out.println("Enter the Key delete: ");
- key = In.nextInt();
- h.deleteKeyFromHashTable(key);
- break;
- }
- case 3:
- {
- System.out.println("Print table:\n");
- h.displayHashtable();
- break;
- }
- case 4:
- {
- In.close();
- return;
- }
- case 5:
- {
- System.out.println(
- "Enter the Key to find and print: "
- );
- key = In.nextInt();
- System.out.println(
- "Key: " +
- key +
- " is at index: " +
- h.findKeyInTable(key) +
- "\n"
- );
- break;
- }
- case 6:
- {
- System.out.printf(
- "Load factor is: %.2f\n",
- h.checkLoadFactor()
- );
- break;
- }
- case 7:
- {
- h.reHashTableIncreasesTableSize();
- break;
- }
+ case 1: {
+ System.out.println("Enter the Key: ");
+ key = In.nextInt();
+ h.insertKey2HashTable(key);
+ break;
+ }
+ case 2: {
+ System.out.println("Enter the Key delete: ");
+ key = In.nextInt();
+ h.deleteKeyFromHashTable(key);
+ break;
+ }
+ case 3: {
+ System.out.println("Print table:\n");
+ h.displayHashtable();
+ break;
+ }
+ case 4: {
+ In.close();
+ return;
+ }
+ case 5: {
+ System.out.println("Enter the Key to find and print: ");
+ key = In.nextInt();
+ System.out.println("Key: " + key + " is at index: " + h.findKeyInTable(key) + "\n");
+ break;
+ }
+ case 6: {
+ System.out.printf("Load factor is: %.2f\n", h.checkLoadFactor());
+ break;
+ }
+ case 7: {
+ h.reHashTableIncreasesTableSize();
+ break;
+ }
}
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java
index 5231431e9bf7..e3364b0e16fb 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java
@@ -1,31 +1,32 @@
package com.thealgorithms.datastructures.hashmap.hashing;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
-import java.util.ArrayList;
/*
This class finds the majority element(s) in an array of integers.
-A majority element is an element that appears more than or equal to n/2 times, where n is the length of the array.
+A majority element is an element that appears more than or equal to n/2 times, where n is the length
+of the array.
*/
public class MajorityElement {
- /*
- This method returns the majority element(s) in the given array of integers.
- @param nums: an array of integers
- @return a list of majority elements
- */
- public static List majority(int[] nums){
- HashMap numToCount = new HashMap<>();
+ /*
+ This method returns the majority element(s) in the given array of integers.
+ @param nums: an array of integers
+ @return a list of majority elements
+ */
+ public static List majority(int[] nums) {
+ HashMap numToCount = new HashMap<>();
int n = nums.length;
for (int i = 0; i < n; i++) {
- if (numToCount.containsKey(nums[i])){
- numToCount.put(nums[i],numToCount.get(nums[i])+1);
+ if (numToCount.containsKey(nums[i])) {
+ numToCount.put(nums[i], numToCount.get(nums[i]) + 1);
} else {
- numToCount.put(nums[i],1);
+ numToCount.put(nums[i], 1);
}
}
List majorityElements = new ArrayList<>();
- for (int key: numToCount.keySet()) {
- if (numToCount.get(key) >= n/2){
+ for (int key : numToCount.keySet()) {
+ if (numToCount.get(key) >= n / 2) {
majorityElements.add(key);
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java
index cd27b0a795b2..4605883fbbb1 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java
@@ -19,5 +19,4 @@ public boolean contains(Key key) {
protected int hash(Key key, int size) {
return (key.hashCode() & Integer.MAX_VALUE) % size;
}
-
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
index eeeb591c2e02..34afa4206b23 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
@@ -47,10 +47,10 @@ public boolean empty() {
* $ret = the HeapNode we inserted
*/
public HeapNode insert(int key) {
- HeapNode toInsert = new HeapNode(key); //creates the node
+ HeapNode toInsert = new HeapNode(key); // creates the node
if (this.empty()) {
this.min = toInsert;
- } else { //tree is not empty
+ } else { // tree is not empty
min.setNext(toInsert);
this.updateMin(toInsert);
}
@@ -69,14 +69,14 @@ public void deleteMin() {
if (this.empty()) {
return;
}
- if (this.numOfHeapNodes == 1) { //if there is only one tree
+ if (this.numOfHeapNodes == 1) { // if there is only one tree
this.min = null;
this.numOfTrees--;
this.numOfHeapNodes--;
return;
}
- //change all children's parent to null//
- if (this.min.child != null) { //min has a child
+ // change all children's parent to null//
+ if (this.min.child != null) { // min has a child
HeapNode child = this.min.child;
HeapNode tmpChild = child;
child.parent = null;
@@ -85,14 +85,14 @@ public void deleteMin() {
child.parent = null;
}
}
- //delete the node//
+ // delete the node//
if (this.numOfTrees > 1) {
(this.min.prev).next = this.min.next;
(this.min.next).prev = this.min.prev;
if (this.min.child != null) {
(this.min.prev).setNext(this.min.child);
}
- } else { //this.numOfTrees = 1
+ } else { // this.numOfTrees = 1
this.min = this.min.child;
}
this.numOfHeapNodes--;
@@ -136,17 +136,15 @@ public int size() {
}
/**
- * Return a counters array, where the value of the i-th index is the number of trees with rank i in the heap.
- * returns an empty array for an empty heap
+ * Return a counters array, where the value of the i-th index is the number of trees with rank i
+ * in the heap. returns an empty array for an empty heap
*/
public int[] countersRep() {
if (this.empty()) {
- return new int[0]; ///return an empty array
+ return new int[0]; /// return an empty array
}
- int[] rankArray = new int[(int) Math.floor(
- Math.log(this.size()) / Math.log(GOLDEN_RATIO)
- ) +
- 1]; //creates the array
+ int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO))
+ + 1]; // creates the array
rankArray[this.min.rank]++;
HeapNode curr = this.min.next;
while (curr != this.min) {
@@ -163,8 +161,8 @@ public int[] countersRep() {
* @post (numOfnodes = = $prev numOfnodes - 1)
*/
public void delete(HeapNode x) {
- this.decreaseKey(x, x.getKey() + 1); //change key to be the minimal (-1)
- this.deleteMin(); //delete it
+ this.decreaseKey(x, x.getKey() + 1); // change key to be the minimal (-1)
+ this.deleteMin(); // delete it
}
/**
@@ -176,13 +174,13 @@ public void delete(HeapNode x) {
private void decreaseKey(HeapNode x, int delta) {
int newKey = x.getKey() - delta;
x.key = newKey;
- if (x.isRoot()) { //no parent to x
+ if (x.isRoot()) { // no parent to x
this.updateMin(x);
return;
}
if (x.getKey() >= x.parent.getKey()) {
return;
- } //we don't need to cut
+ } // we don't need to cut
HeapNode prevParent = x.parent;
this.cut(x);
this.cascadingCuts(prevParent);
@@ -197,17 +195,18 @@ public int potential() {
}
/**
- * This static function returns the total number of link operations made during the run-time of the program.
- * A link operation is the operation which gets as input two trees of the same rank, and generates a tree of
- * rank bigger by one.
+ * This static function returns the total number of link operations made during the run-time of
+ * the program. A link operation is the operation which gets as input two trees of the same
+ * rank, and generates a tree of rank bigger by one.
*/
public static int totalLinks() {
return totalLinks;
}
/**
- * This static function returns the total number of cut operations made during the run-time of the program.
- * A cut operation is the operation which disconnects a subtree from its parent (during decreaseKey/delete methods).
+ * This static function returns the total number of cut operations made during the run-time of
+ * the program. A cut operation is the operation which disconnects a subtree from its parent
+ * (during decreaseKey/delete methods).
*/
public static int totalCuts() {
return totalCuts;
@@ -231,7 +230,7 @@ private void updateMin(HeapNode posMin) {
* @post (numOfnodes == $prev numOfnodes)
*/
private void cascadingCuts(HeapNode curr) {
- if (!curr.isMarked()) { //stop the recursion
+ if (!curr.isMarked()) { // stop the recursion
curr.mark();
if (!curr.isRoot()) this.markedHeapNoodesCounter++;
} else {
@@ -255,10 +254,10 @@ private void cut(HeapNode curr) {
this.markedHeapNoodesCounter--;
curr.marked = false;
}
- if (curr.parent.child == curr) { //we should change the parent's child
- if (curr.next == curr) { //curr do not have brothers
+ if (curr.parent.child == curr) { // we should change the parent's child
+ if (curr.next == curr) { // curr do not have brothers
curr.parent.child = null;
- } else { //curr have brothers
+ } else { // curr have brothers
curr.parent.child = curr.next;
}
}
@@ -285,10 +284,8 @@ private void successiveLink(HeapNode curr) {
*
*/
private HeapNode[] toBuckets(HeapNode curr) {
- HeapNode[] buckets = new HeapNode[(int) Math.floor(
- Math.log(this.size()) / Math.log(GOLDEN_RATIO)
- ) +
- 1];
+ HeapNode[] buckets
+ = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
curr.prev.next = null;
HeapNode tmpCurr;
while (curr != null) {
@@ -398,7 +395,7 @@ private boolean isMarked() {
private void mark() {
if (this.isRoot()) {
return;
- } //check if the node is a root
+ } // check if the node is a root
this.marked = true;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java
index 2ceb86a727e9..23c26cfd0aab 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java
@@ -45,16 +45,10 @@ private void downHeapify(int pi) {
int lci = 2 * pi + 1;
int rci = 2 * pi + 2;
int mini = pi;
- if (
- lci < this.size() &&
- isLarger(this.data.get(lci), this.data.get(mini)) > 0
- ) {
+ if (lci < this.size() && isLarger(this.data.get(lci), this.data.get(mini)) > 0) {
mini = lci;
}
- if (
- rci < this.size() &&
- isLarger(this.data.get(rci), this.data.get(mini)) > 0
- ) {
+ if (rci < this.size() && isLarger(this.data.get(rci), this.data.get(mini)) > 0) {
mini = rci;
}
if (mini != pi) {
@@ -67,7 +61,7 @@ public T get() {
return this.data.get(0);
}
- //t has higher property then return +ve
+ // t has higher property then return +ve
private int isLarger(T t, T o) {
return t.compareTo(o);
}
@@ -83,7 +77,7 @@ private void swap(int i, int j) {
public void updatePriority(T item) {
int index = map.get(item);
- //because we enter lesser value then old vale
+ // because we enter lesser value then old vale
upHeapify(index);
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java
index bf095706a5a5..be5e42c900e2 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java
@@ -122,10 +122,8 @@ public boolean equals(Object o) {
return false;
}
HeapElement otherHeapElement = (HeapElement) o;
- return (
- (this.key == otherHeapElement.key) &&
- (this.additionalInfo.equals(otherHeapElement.additionalInfo))
- );
+ return ((this.key == otherHeapElement.key)
+ && (this.additionalInfo.equals(otherHeapElement.additionalInfo)));
}
return false;
}
@@ -134,10 +132,7 @@ public boolean equals(Object o) {
public int hashCode() {
int result = 0;
result = 31 * result + (int) key;
- result =
- 31 *
- result +
- (additionalInfo != null ? additionalInfo.hashCode() : 0);
+ result = 31 * result + (additionalInfo != null ? additionalInfo.hashCode() : 0);
return result;
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java
index 66861ac1d111..f64781f19857 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java
@@ -2,117 +2,113 @@
import java.util.ArrayList;
-/*
+/*
* This is a leftist heap that follows the same operations as a
* binary min heap, but may be unbalanced at times and follows a
* leftist property, in which the left side is more heavy on the
* right based on the null-path length (npl) values.
- *
+ *
* Source: https://iq.opengenus.org/leftist-heap/
- *
+ *
*/
public class LeftistHeap {
- private class Node {
- private int element, npl;
- private Node left, right;
-
- // Node constructor setting the data element and left/right pointers to null
- private Node(int element) {
- this.element = element;
- left = right = null;
- npl = 0;
- }
- }
-
- private Node root;
-
- // Constructor
- public LeftistHeap() {
- root = null;
- }
-
- // Checks if heap is empty
- public boolean isEmpty() {
- return root == null;
- }
-
- // Resets structure to initial state
- public void clear() {
- // We will put head is null
- root = null;
- }
-
- // Merge function that merges the contents of another leftist heap with the
- // current one
- public void merge(LeftistHeap h1) {
- // If the present function is rhs then we ignore the merge
- root = merge(root, h1.root);
- h1.root = null;
- }
-
- // Function merge with two Nodes a and b
- public Node merge(Node a, Node b) {
- if (a == null)
- return b;
-
- if (b == null)
- return a;
-
- // Violates leftist property, so must do a swap
- if (a.element > b.element) {
- Node temp = a;
- a = b;
- b = temp;
- }
-
- // Now we call the function merge to merge a and b
- a.right = merge(a.right, b);
-
- // Violates leftist property so must swap here
- if (a.left == null) {
- a.left = a.right;
- a.right = null;
- } else {
- if (a.left.npl < a.right.npl) {
- Node temp = a.left;
- a.left = a.right;
- a.right = temp;
- }
- a.npl = a.right.npl + 1;
- }
- return a;
- }
-
- // Function insert. Uses the merge function to add the data
- public void insert(int a) {
- root = merge(new Node(a), root);
- }
-
- // Returns and removes the minimum element in the heap
- public int extract_min() {
- // If is empty return -1
- if (isEmpty())
- return -1;
-
- int min = root.element;
- root = merge(root.left, root.right);
- return min;
- }
-
- // Function returning a list of an in order traversal of the data structure
- public ArrayList in_order() {
- ArrayList lst = new ArrayList<>();
- in_order_aux(root, lst);
- return new ArrayList<>(lst);
- }
-
- // Auxiliary function for in_order
- private void in_order_aux(Node n, ArrayList lst) {
- if (n == null)
- return;
- in_order_aux(n.left, lst);
- lst.add(n.element);
- in_order_aux(n.right, lst);
- }
+ private class Node {
+ private int element, npl;
+ private Node left, right;
+
+ // Node constructor setting the data element and left/right pointers to null
+ private Node(int element) {
+ this.element = element;
+ left = right = null;
+ npl = 0;
+ }
+ }
+
+ private Node root;
+
+ // Constructor
+ public LeftistHeap() {
+ root = null;
+ }
+
+ // Checks if heap is empty
+ public boolean isEmpty() {
+ return root == null;
+ }
+
+ // Resets structure to initial state
+ public void clear() {
+ // We will put head is null
+ root = null;
+ }
+
+ // Merge function that merges the contents of another leftist heap with the
+ // current one
+ public void merge(LeftistHeap h1) {
+ // If the present function is rhs then we ignore the merge
+ root = merge(root, h1.root);
+ h1.root = null;
+ }
+
+ // Function merge with two Nodes a and b
+ public Node merge(Node a, Node b) {
+ if (a == null) return b;
+
+ if (b == null) return a;
+
+ // Violates leftist property, so must do a swap
+ if (a.element > b.element) {
+ Node temp = a;
+ a = b;
+ b = temp;
+ }
+
+ // Now we call the function merge to merge a and b
+ a.right = merge(a.right, b);
+
+ // Violates leftist property so must swap here
+ if (a.left == null) {
+ a.left = a.right;
+ a.right = null;
+ } else {
+ if (a.left.npl < a.right.npl) {
+ Node temp = a.left;
+ a.left = a.right;
+ a.right = temp;
+ }
+ a.npl = a.right.npl + 1;
+ }
+ return a;
+ }
+
+ // Function insert. Uses the merge function to add the data
+ public void insert(int a) {
+ root = merge(new Node(a), root);
+ }
+
+ // Returns and removes the minimum element in the heap
+ public int extract_min() {
+ // If is empty return -1
+ if (isEmpty()) return -1;
+
+ int min = root.element;
+ root = merge(root.left, root.right);
+ return min;
+ }
+
+ // Function returning a list of an in order traversal of the data structure
+ public ArrayList in_order() {
+ ArrayList lst = new ArrayList<>();
+ in_order_aux(root, lst);
+ return new ArrayList<>(lst);
+ }
+
+ // Auxiliary function for in_order
+ private void in_order_aux(Node n, ArrayList lst) {
+ if (n == null) return;
+ in_order_aux(n.left, lst);
+ lst.add(n.element);
+ in_order_aux(n.right, lst);
+ }
}
\ No newline at end of file
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
index 64731fd2f5ba..591b4439c397 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
@@ -70,30 +70,20 @@ private void toggleUp(int elementIndex) {
// than any of its children's
private void toggleDown(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey();
- boolean wrongOrder =
- (key < getElementKey(elementIndex * 2)) ||
- (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
+ boolean wrongOrder = (key < getElementKey(elementIndex * 2))
+ || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any.
- if (
- (2 * elementIndex < maxHeap.size()) &&
- (
- getElementKey(elementIndex * 2 + 1) >
- getElementKey(elementIndex * 2)
- )
- ) {
+ if ((2 * elementIndex < maxHeap.size())
+ && (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) {
swap(elementIndex, 2 * elementIndex + 1);
elementIndex = 2 * elementIndex + 1;
} else {
swap(elementIndex, 2 * elementIndex);
elementIndex = 2 * elementIndex;
}
- wrongOrder =
- (key < getElementKey(elementIndex * 2)) ||
- (
- key <
- getElementKey(Math.min(elementIndex * 2, maxHeap.size()))
- );
+ wrongOrder = (key < getElementKey(elementIndex * 2))
+ || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
}
}
@@ -112,12 +102,10 @@ public void insertElement(HeapElement element) {
@Override
public void deleteElement(int elementIndex) {
if (maxHeap.isEmpty()) try {
- throw new EmptyHeapException(
- "Attempt to delete an element from an empty heap"
- );
- } catch (EmptyHeapException e) {
- e.printStackTrace();
- }
+ throw new EmptyHeapException("Attempt to delete an element from an empty heap");
+ } catch (EmptyHeapException e) {
+ e.printStackTrace();
+ }
if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) {
throw new IndexOutOfBoundsException("Index out of heap range");
}
@@ -125,22 +113,13 @@ public void deleteElement(int elementIndex) {
maxHeap.set(elementIndex - 1, getElement(maxHeap.size()));
maxHeap.remove(maxHeap.size());
// Shall the new element be moved up...
- if (
- getElementKey(elementIndex) >
- getElementKey((int) Math.floor(elementIndex / 2.0))
- ) {
+ if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) {
toggleUp(elementIndex);
} // ... or down ?
- else if (
- (
- (2 * elementIndex <= maxHeap.size()) &&
- (getElementKey(elementIndex) < getElementKey(elementIndex * 2))
- ) ||
- (
- (2 * elementIndex < maxHeap.size()) &&
- (getElementKey(elementIndex) < getElementKey(elementIndex * 2))
- )
- ) {
+ else if (((2 * elementIndex <= maxHeap.size())
+ && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))
+ || ((2 * elementIndex < maxHeap.size())
+ && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) {
toggleDown(elementIndex);
}
}
@@ -150,9 +129,7 @@ public HeapElement getElement() throws EmptyHeapException {
try {
return extractMax();
} catch (Exception e) {
- throw new EmptyHeapException(
- "Heap is empty. Error retrieving element"
- );
+ throw new EmptyHeapException("Heap is empty. Error retrieving element");
}
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
index a28a8e5f1cf9..5c2cb5ccd69d 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
@@ -64,30 +64,20 @@ private void toggleUp(int elementIndex) {
// than any of its children's
private void toggleDown(int elementIndex) {
double key = minHeap.get(elementIndex - 1).getKey();
- boolean wrongOrder =
- (key > getElementKey(elementIndex * 2)) ||
- (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
+ boolean wrongOrder = (key > getElementKey(elementIndex * 2))
+ || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
while ((2 * elementIndex <= minHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any.
- if (
- (2 * elementIndex < minHeap.size()) &&
- (
- getElementKey(elementIndex * 2 + 1) <
- getElementKey(elementIndex * 2)
- )
- ) {
+ if ((2 * elementIndex < minHeap.size())
+ && (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) {
swap(elementIndex, 2 * elementIndex + 1);
elementIndex = 2 * elementIndex + 1;
} else {
swap(elementIndex, 2 * elementIndex);
elementIndex = 2 * elementIndex;
}
- wrongOrder =
- (key > getElementKey(elementIndex * 2)) ||
- (
- key >
- getElementKey(Math.min(elementIndex * 2, minHeap.size()))
- );
+ wrongOrder = (key > getElementKey(elementIndex * 2))
+ || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
}
}
@@ -106,12 +96,10 @@ public void insertElement(HeapElement element) {
@Override
public void deleteElement(int elementIndex) {
if (minHeap.isEmpty()) try {
- throw new EmptyHeapException(
- "Attempt to delete an element from an empty heap"
- );
- } catch (EmptyHeapException e) {
- e.printStackTrace();
- }
+ throw new EmptyHeapException("Attempt to delete an element from an empty heap");
+ } catch (EmptyHeapException e) {
+ e.printStackTrace();
+ }
if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) {
throw new IndexOutOfBoundsException("Index out of heap range");
}
@@ -119,22 +107,13 @@ public void deleteElement(int elementIndex) {
minHeap.set(elementIndex - 1, getElement(minHeap.size()));
minHeap.remove(minHeap.size());
// Shall the new element be moved up...
- if (
- getElementKey(elementIndex) <
- getElementKey((int) Math.floor(elementIndex / 2.0))
- ) {
+ if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) {
toggleUp(elementIndex);
} // ... or down ?
- else if (
- (
- (2 * elementIndex <= minHeap.size()) &&
- (getElementKey(elementIndex) > getElementKey(elementIndex * 2))
- ) ||
- (
- (2 * elementIndex < minHeap.size()) &&
- (getElementKey(elementIndex) > getElementKey(elementIndex * 2))
- )
- ) {
+ else if (((2 * elementIndex <= minHeap.size())
+ && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))
+ || ((2 * elementIndex < minHeap.size())
+ && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) {
toggleDown(elementIndex);
}
}
@@ -144,9 +123,7 @@ public HeapElement getElement() throws EmptyHeapException {
try {
return extractMin();
} catch (Exception e) {
- throw new EmptyHeapException(
- "Heap is empty. Error retrieving element"
- );
+ throw new EmptyHeapException("Heap is empty. Error retrieving element");
}
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java
index 23ac5d3aaabf..2ad4ed5320c9 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java
@@ -82,10 +82,7 @@ private void sink() {
while (2 * k <= this.size || 2 * k + 1 <= this.size) {
int minIndex;
if (this.heap[2 * k] >= this.heap[k]) {
- if (
- 2 * k + 1 <= this.size &&
- this.heap[2 * k + 1] >= this.heap[k]
- ) {
+ if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) {
break;
} else if (2 * k + 1 > this.size) {
break;
@@ -94,14 +91,8 @@ private void sink() {
if (2 * k + 1 > this.size) {
minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k;
} else {
- if (
- this.heap[k] > this.heap[2 * k] ||
- this.heap[k] > this.heap[2 * k + 1]
- ) {
- minIndex =
- this.heap[2 * k] < this.heap[2 * k + 1]
- ? 2 * k
- : 2 * k + 1;
+ if (this.heap[k] > this.heap[2 * k] || this.heap[k] > this.heap[2 * k + 1]) {
+ minIndex = this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1;
} else {
minIndex = k;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java
index f5edc6c09811..5d9f0b3a1d28 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java
@@ -38,9 +38,7 @@ public int getSize() {
public void append(E value) {
if (value == null) {
// we do not want to add null elements to the list.
- throw new NullPointerException(
- "Cannot add null element to the list"
- );
+ throw new NullPointerException("Cannot add null element to the list");
}
// head.next points to the last element;
if (tail == null) {
@@ -70,9 +68,7 @@ public String toString() {
public E remove(int pos) {
if (pos > size || pos < 0) {
// catching errors
- throw new IndexOutOfBoundsException(
- "position cannot be greater than size or negative"
- );
+ throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
}
// we need to keep track of the element before the element we want to remove we can see why
// bellow.
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java
index 6ed317d6d4ef..cefc47c27169 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java
@@ -120,8 +120,7 @@ public void remove(T element) {
while (current_index != -1) {
T current_element = cursorSpace[current_index].element;
if (current_element.equals(element)) {
- cursorSpace[prev_index].next =
- cursorSpace[current_index].next;
+ cursorSpace[prev_index].next = cursorSpace[current_index].next;
free(current_index);
break;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java
index 2d048d9967b5..74aa4b8b1ae0 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java
@@ -217,7 +217,8 @@ public void insertHead(int x, DoublyLinkedList doublyLinkedList) {
public void insertTail(int x, DoublyLinkedList doublyLinkedList) {
Link newLink = new Link(x);
newLink.next = null; // currentTail(tail) newlink -->
- if (doublyLinkedList.isEmpty()) { // Check if there are no elements in list then it adds first element
+ if (doublyLinkedList
+ .isEmpty()) { // Check if there are no elements in list then it adds first element
tail = newLink;
head = tail;
} else {
@@ -234,15 +235,9 @@ public void insertTail(int x, DoublyLinkedList doublyLinkedList) {
* @param x Element to be inserted
* @param index Index(from start) at which the element x to be inserted
*/
- public void insertElementByIndex(
- int x,
- int index,
- DoublyLinkedList doublyLinkedList
- ) {
+ public void insertElementByIndex(int x, int index, DoublyLinkedList doublyLinkedList) {
if (index > size) {
- throw new IndexOutOfBoundsException(
- "Index: " + index + ", Size: " + size
- );
+ throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
if (index == 0) {
insertHead(x, doublyLinkedList);
@@ -277,7 +272,8 @@ public Link deleteHead() {
if (head == null) {
tail = null;
} else {
- head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
+ head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so
+ // will be removed
}
--size;
return temp;
@@ -314,9 +310,7 @@ public void delete(int x) {
if (current != tail) {
current = current.next;
} else { // If we reach the tail and the element is still not found
- throw new RuntimeException(
- "The element to be deleted does not exist!"
- );
+ throw new RuntimeException("The element to be deleted does not exist!");
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java
index f9a80d984cc7..80b36b8e4ab1 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java
@@ -36,11 +36,7 @@ public static void main(String[] args) {
* @param listB the second list to merge
* @param listC the result list after merging
*/
- public static void merge(
- List listA,
- List listB,
- List listC
- ) {
+ public static void merge(List listA, List listB, List listC) {
int pa = 0;
/* the index of listA */
int pb = 0;
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java
index 4ea0127f4ae0..2bee945c9db6 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java
@@ -12,9 +12,7 @@ public static void main(String[] args) {
}
assert listA.toString().equals("2->4->6->8->10");
assert listB.toString().equals("1->3->5->7->9");
- assert merge(listA, listB)
- .toString()
- .equals("1->2->3->4->5->6->7->8->9->10");
+ assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10");
}
/**
@@ -24,10 +22,7 @@ assert merge(listA, listB)
* @param listB the second sored list
* @return merged sorted list
*/
- public static SinglyLinkedList merge(
- SinglyLinkedList listA,
- SinglyLinkedList listB
- ) {
+ public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) {
Node headA = listA.getHead();
Node headB = listB.getHead();
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java b/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java
index 840b935ef84a..9d26645c2f9c 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java
@@ -18,9 +18,7 @@ public class Merge_K_SortedLinkedlist {
*/
Node mergeKList(Node[] a, int N) {
// Min Heap
- PriorityQueue min = new PriorityQueue<>(
- Comparator.comparingInt(x -> x.data)
- );
+ PriorityQueue min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data));
// adding head of all linkedList in min heap
min.addAll(Arrays.asList(a).subList(0, N));
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java
index e173da2fb4f7..7318b8027f8c 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java
@@ -1,25 +1,30 @@
-/** Author : Suraj Kumar
+/**
+ * Author : Suraj Kumar
* Github : https://github.com/skmodi649
*/
-/** PROBLEM DESCRIPTION :
+/**
+ * PROBLEM DESCRIPTION :
* There is a single linked list and we are supposed to find a random node in the given linked list
*/
-/** ALGORITHM :
+/**
+ * ALGORITHM :
* Step 1 : START
* Step 2 : Create an arraylist of type integer
* Step 3 : Declare an integer type variable for size and linked list type for head
- * Step 4 : We will use two methods, one for traversing through the linked list using while loop and also increase the size by 1
+ * Step 4 : We will use two methods, one for traversing through the linked list using while loop and
+ * also increase the size by 1
*
* (a) RandomNode(head)
* (b) run a while loop till null;
* (c) add the value to arraylist;
* (d) increase the size;
*
- * Step 5 : Now use another method for getting random values using Math.random() and return the value present in arraylist for the calculated index
- * Step 6 : Now in main() method we will simply insert nodes in the linked list and then call the appropriate method and then print the random node generated
- * Step 7 : STOP
+ * Step 5 : Now use another method for getting random values using Math.random() and return the
+ * value present in arraylist for the calculated index Step 6 : Now in main() method we will simply
+ * insert nodes in the linked list and then call the appropriate method and then print the random
+ * node generated Step 7 : STOP
*/
package com.thealgorithms.datastructures.lists;
@@ -86,6 +91,7 @@ public static void main(String[] args) {
* Time Complexity : O(n)
* Auxiliary Space Complexity : O(1)
*/
-/** Time Complexity : O(n)
+/**
+ * Time Complexity : O(n)
* Auxiliary Space Complexity : O(1)
*/
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java b/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java
index bd3dd51ba39a..35f8c9a95b56 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java
@@ -23,10 +23,7 @@ public static void main(String[] args) {
* {@code false}.
*/
private boolean searchRecursion(Node node, int key) {
- return (
- node != null &&
- (node.value == key || searchRecursion(node.next, key))
- );
+ return (node != null && (node.value == key || searchRecursion(node.next, key)));
}
@Override
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
index df460938390a..8d15059367f1 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
@@ -125,19 +125,20 @@ public void swapNodes(int valueFirst, int valueSecond) {
public Node reverseList(Node node) {
Node prev = null;
Node curr = node;
-
+
while (curr != null && curr.next != null) {
- Node next=curr.next;
+ Node next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
- //when curr.next==null, the current element is left without pointing it to its prev,so
- if(curr != null){
+ // when curr.next==null, the current element is left without pointing it to its prev,so
+ if (curr != null) {
curr.next = prev;
- prev=curr;
+ prev = curr;
}
- //prev will be pointing to the last element in the Linkedlist, it will be the new head of the reversed linkedlist
+ // prev will be pointing to the last element in the Linkedlist, it will be the new head of
+ // the reversed linkedlist
return prev;
}
@@ -244,9 +245,7 @@ public void deleteDuplicates() {
// skip all duplicates
if (newHead.next != null && newHead.value == newHead.next.value) {
// move till the end of duplicates sublist
- while (
- newHead.next != null && newHead.value == newHead.next.value
- ) {
+ while (newHead.next != null && newHead.value == newHead.next.value) {
newHead = newHead.next;
}
// skip all duplicates
@@ -412,15 +411,10 @@ public static void main(String[] arg) {
assert list.toString().equals("10->7->5->3->1");
System.out.println(list);
/* Test search function */
- assert list.search(10) &&
- list.search(5) &&
- list.search(1) &&
- !list.search(100);
+ assert list.search(10) && list.search(5) && list.search(1) && !list.search(100);
/* Test get function */
- assert list.getNth(0) == 10 &&
- list.getNth(2) == 5 &&
- list.getNth(4) == 1;
+ assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1;
/* Test delete function */
list.deleteHead();
@@ -443,10 +437,7 @@ public static void main(String[] arg) {
}
SinglyLinkedList instance = new SinglyLinkedList();
- Node head = new Node(
- 0,
- new Node(2, new Node(3, new Node(3, new Node(4))))
- );
+ Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4)))));
instance.setHead(head);
instance.deleteDuplicates();
instance.print();
@@ -469,7 +460,8 @@ class Node {
*/
Node next;
- Node() {}
+ Node() {
+ }
/**
* Constructor
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java
index 34efde769ed9..6a079ac879a3 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java
@@ -189,25 +189,23 @@ public String toString() {
}
Collections.reverse(layers);
- String result = layers
- .stream()
- .map(layer -> {
- StringBuilder acc = new StringBuilder();
- for (boolean b : layer) {
- if (b) {
- acc.append("[ ]");
- } else {
- acc.append("---");
- }
- acc.append(" ");
- }
- return acc.toString();
- })
- .collect(Collectors.joining("\n"));
- String positions = IntStream
- .range(0, sizeWithHeader - 1)
- .mapToObj(i -> String.format("%3d", i))
- .collect(Collectors.joining(" "));
+ String result = layers.stream()
+ .map(layer -> {
+ StringBuilder acc = new StringBuilder();
+ for (boolean b : layer) {
+ if (b) {
+ acc.append("[ ]");
+ } else {
+ acc.append("---");
+ }
+ acc.append(" ");
+ }
+ return acc.toString();
+ })
+ .collect(Collectors.joining("\n"));
+ String positions = IntStream.range(0, sizeWithHeader - 1)
+ .mapToObj(i -> String.format("%3d", i))
+ .collect(Collectors.joining(" "));
return result + String.format("%n H %s%n", positions);
}
@@ -299,17 +297,14 @@ public BernoulliHeightStrategy() {
public BernoulliHeightStrategy(double probability) {
if (probability <= 0 || probability >= 1) {
throw new IllegalArgumentException(
- "Probability should be from 0 to 1. But was: " + probability
- );
+ "Probability should be from 0 to 1. But was: " + probability);
}
this.probability = probability;
}
@Override
public int height(int expectedSize) {
- long height = Math.round(
- Math.log10(expectedSize) / Math.log10(1 / probability)
- );
+ long height = Math.round(Math.log10(expectedSize) / Math.log10(1 / probability));
if (height > Integer.MAX_VALUE) {
throw new IllegalArgumentException();
}
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
index e5bedd9beae3..9530c5a69d8c 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
@@ -1,7 +1,7 @@
package com.thealgorithms.datastructures.queues;
-//This program implements the concept of CircularQueue in Java
-//Link to the concept: (https://en.wikipedia.org/wiki/Circular_buffer)
+// This program implements the concept of CircularQueue in Java
+// Link to the concept: (https://en.wikipedia.org/wiki/Circular_buffer)
public class CircularQueue {
int[] arr;
@@ -23,7 +23,8 @@ public boolean isEmpty() {
public boolean isFull() {
if (topOfQueue + 1 == beginningOfQueue) {
return true;
- } else return topOfQueue == size - 1 && beginningOfQueue == 0;
+ } else
+ return topOfQueue == size - 1 && beginningOfQueue == 0;
}
public void enQueue(int value) {
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java
index 79fddb0ef518..7fa769c615ce 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java
@@ -124,11 +124,9 @@ public T peekRear() {
public T peek(int pos) {
if (pos > size)
- throw new IndexOutOfBoundsException(
- "Position %s out of range!".formatted(pos));
+ throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos));
Node node = front;
- while (pos-- > 0)
- node = node.next;
+ while (pos-- > 0) node = node.next;
return node.data;
}
@@ -140,7 +138,6 @@ public T peek(int pos) {
@Override
public Iterator iterator() {
return new Iterator<>() {
-
Node node = front;
@Override
@@ -168,16 +165,14 @@ public int size() {
* Clear all nodes in queue
*/
public void clear() {
- while (size > 0)
- dequeue();
+ while (size > 0) dequeue();
}
@Override
public String toString() {
StringJoiner join = new StringJoiner(", "); // separator of ', '
Node travel = front;
- while ((travel = travel.next) != null)
- join.add(String.valueOf(travel.data));
+ while ((travel = travel.next) != null) join.add(String.valueOf(travel.data));
return '[' + join.toString() + ']';
}
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java
index 21432a53ce5c..dec25d2ff694 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java
@@ -1,8 +1,5 @@
package com.thealgorithms.datastructures.queues;
-
-
-
/**
* This class implements a PriorityQueue.
*
@@ -126,7 +123,8 @@ public int remove() {
if (isEmpty()) {
throw new RuntimeException("Queue is Empty");
} else {
- int max = queueArray[1]; // By defintion of our max-heap, value at queueArray[1] pos is the greatest
+ int max = queueArray[1]; // By defintion of our max-heap, value at queueArray[1] pos is
+ // the greatest
// Swap max and last element
int temp = queueArray[1];
@@ -175,4 +173,3 @@ public int getSize() {
return nItems;
}
}
-
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java b/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java
index 2e2b572c1054..d80502d88e22 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java
@@ -28,16 +28,13 @@ class BalancedBrackets {
*/
public static boolean isPaired(char leftBracket, char rightBracket) {
char[][] pairedBrackets = {
- { '(', ')' },
- { '[', ']' },
- { '{', '}' },
- { '<', '>' },
+ {'(', ')'},
+ {'[', ']'},
+ {'{', '}'},
+ {'<', '>'},
};
for (char[] pairedBracket : pairedBrackets) {
- if (
- pairedBracket[0] == leftBracket &&
- pairedBracket[1] == rightBracket
- ) {
+ if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) {
return true;
}
}
@@ -58,24 +55,21 @@ public static boolean isBalanced(String brackets) {
Stack bracketsStack = new Stack<>();
for (char bracket : brackets.toCharArray()) {
switch (bracket) {
- case '(':
- case '[':
- case '{':
- bracketsStack.push(bracket);
- break;
- case ')':
- case ']':
- case '}':
- if (
- bracketsStack.isEmpty() ||
- !isPaired(bracketsStack.pop(), bracket)
- ) {
- return false;
- }
- break;
- default:
- /* other character is invalid */
+ case '(':
+ case '[':
+ case '{':
+ bracketsStack.push(bracket);
+ break;
+ case ')':
+ case ']':
+ case '}':
+ if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) {
return false;
+ }
+ break;
+ default:
+ /* other character is invalid */
+ return false;
}
}
return bracketsStack.isEmpty();
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java b/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java
index 7a76c62e8964..df7279bb217e 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java
@@ -1,8 +1,12 @@
-/** Author : Siddhant Swarup Mallick
+/**
+ * Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
-/** Program description - Given an integer array. The task is to find the maximum of the minimum of the array */
+/**
+ * Program description - Given an integer array. The task is to find the maximum of the minimum of
+ * the array
+ */
package com.thealgorithms.datastructures.stacks;
import java.util.*;
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java
index 28302793977a..a0d364136bcd 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java
@@ -24,12 +24,7 @@ public static void main(String[] args) {
private static String convert(int number, int radix) {
if (radix < 2 || radix > 16) {
throw new ArithmeticException(
- String.format(
- "Invalid input -> number:%d,radius:%d",
- number,
- radix
- )
- );
+ String.format("Invalid input -> number:%d,radius:%d", number, radix));
}
char[] tables = {
'0',
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java b/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java
index d47f5b193077..fb976360c9f5 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java
@@ -1,7 +1,8 @@
package com.thealgorithms.datastructures.stacks;
// 1. You are given a string exp representing an expression.
-// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each other.
+// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each
+// other.
// 3. But, some of the pair of brackets maybe extra/needless.
// 4. You are required to print true if you detect extra brackets and false otherwise.
// e.g.'
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java b/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java
index 9df7330d808b..b009223330f0 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java
@@ -10,8 +10,7 @@ public static void main(String[] args) throws Exception {
assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6"));
}
- public static String infix2PostFix(String infixExpression)
- throws Exception {
+ public static String infix2PostFix(String infixExpression) throws Exception {
if (!BalancedBrackets.isBalanced(infixExpression)) {
throw new Exception("invalid expression");
}
@@ -28,10 +27,7 @@ public static String infix2PostFix(String infixExpression)
}
stack.pop();
} else {
- while (
- !stack.isEmpty() &&
- precedence(element) <= precedence(stack.peek())
- ) {
+ while (!stack.isEmpty() && precedence(element) <= precedence(stack.peek())) {
output.append(stack.pop());
}
stack.push(element);
@@ -45,16 +41,16 @@ public static String infix2PostFix(String infixExpression)
private static int precedence(char operator) {
switch (operator) {
- case '+':
- case '-':
- return 0;
- case '*':
- case '/':
- return 1;
- case '^':
- return 2;
- default:
- return -1;
+ case '+':
+ case '-':
+ return 0;
+ case '*':
+ case '/':
+ return 1;
+ case '^':
+ return 2;
+ default:
+ return -1;
}
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java b/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java
index 9cc4f0f7035c..f076d5d6a97e 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java
@@ -19,7 +19,7 @@ public static String largestRectanglehistogram(int[] heights) {
maxArea = Math.max(maxArea, tmp[1] * (i - tmp[0]));
start = tmp[0];
}
- st.push(new int[] { start, heights[i] });
+ st.push(new int[] {start, heights[i]});
}
while (!st.isEmpty()) {
int[] tmp = st.pop();
@@ -29,8 +29,7 @@ public static String largestRectanglehistogram(int[] heights) {
}
public static void main(String[] args) {
- assert largestRectanglehistogram(new int[] { 2, 1, 5, 6, 2, 3 })
- .equals("10");
- assert largestRectanglehistogram(new int[] { 2, 4 }).equals("4");
+ assert largestRectanglehistogram(new int[] {2, 1, 5, 6, 2, 3}).equals("10");
+ assert largestRectanglehistogram(new int[] {2, 4}).equals("4");
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java b/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java
index 53a502798caa..88228000e904 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java
@@ -97,8 +97,8 @@ public static int[] calculateMaxOfMin(int[] arr, int n) {
}
public static void main(String[] args) {
- int[] arr = new int[] { 10, 20, 30, 50, 10, 70, 30 };
- int[] target = new int[] { 70, 30, 20, 10, 10, 10, 10 };
+ int[] arr = new int[] {10, 20, 30, 50, 10, 70, 30};
+ int[] target = new int[] {70, 30, 20, 10, 10, 10, 10};
int[] res = calculateMaxOfMin(arr, arr.length);
assert Arrays.equals(target, res);
}
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java b/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java
index 2497158a20bb..294e436c24a2 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java
@@ -37,7 +37,8 @@ Next Grater element between (6 to n) is -1
popped elements.
d. Finally, push the next in the stack.
- 3. If elements are left in stack after completing while loop then their Next Grater element is -1.
+ 3. If elements are left in stack after completing while loop then their Next Grater element is
+ -1.
*/
public class NextGraterElement {
@@ -61,7 +62,7 @@ public static int[] findNextGreaterElements(int[] array) {
}
public static void main(String[] args) {
- int[] input = { 2, 7, 3, 5, 4, 6, 8 };
+ int[] input = {2, 7, 3, 5, 4, 6, 8};
int[] result = findNextGreaterElements(input);
System.out.println(Arrays.toString(result));
}
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java b/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java
index 6073d4819361..b25e5346d574 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java
@@ -4,10 +4,10 @@
import java.util.Stack;
/*
- Given an array "input" you need to print the first smaller element for each element to the left side of an array.
- For a given element x of an array, the Next Smaller element of that element is the
- first smaller element to the left side of it. If no such element is present print -1.
-
+ Given an array "input" you need to print the first smaller element for each element to the left
+ side of an array. For a given element x of an array, the Next Smaller element of that element is
+ the first smaller element to the left side of it. If no such element is present print -1.
+
Example
input = { 2, 7, 3, 5, 4, 6, 8 };
At i = 0
@@ -24,17 +24,17 @@ Next smaller element between (0 , 3) is 3
Next smaller element between (0 , 4) is 4
At i = 6
Next smaller element between (0 , 5) is 6
-
+
result : [-1, 2, 2, 3, 3, 4, 6]
-
+
1) Create a new empty stack st
-
+
2) Iterate over array "input" , where "i" goes from 0 to input.length -1.
- a) We are looking for value just smaller than `input[i]`. So keep popping from "stack"
+ a) We are looking for value just smaller than `input[i]`. So keep popping from "stack"
till elements in "stack.peek() >= input[i]" or stack becomes empty.
- b) If the stack is non-empty, then the top element is our previous element. Else the previous element does not exist.
- c) push input[i] in stack.
- 3) If elements are left then their answer is -1
+ b) If the stack is non-empty, then the top element is our previous element. Else the
+ previous element does not exist. c) push input[i] in stack. 3) If elements are left then their
+ answer is -1
*/
public class NextSmallerElement {
@@ -61,7 +61,7 @@ public static int[] findNextSmallerElements(int[] array) {
}
public static void main(String[] args) {
- int[] input = { 2, 7, 3, 5, 4, 6, 8 };
+ int[] input = {2, 7, 3, 5, 4, 6, 8};
int[] result = findNextSmallerElements(input);
System.out.println(Arrays.toString(result));
}
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java
index b4ab7860ddd0..ffdfc962224d 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java
@@ -50,7 +50,8 @@ public static void main(String[] args) {
/**
* Constructors for the NodeStack.
*/
- public NodeStack() {}
+ public NodeStack() {
+ }
private NodeStack(Item item) {
this.data = item;
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java b/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java
index 868aa778a626..0d67a7939513 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java
@@ -20,12 +20,12 @@ public class PostfixToInfix {
public static boolean isOperator(char token) {
switch (token) {
- case '+':
- case '-':
- case '/':
- case '*':
- case '^':
- return true;
+ case '+':
+ case '-':
+ case '/':
+ case '*':
+ case '^':
+ return true;
}
return false;
@@ -42,7 +42,8 @@ public static boolean isValidPostfixExpression(String postfix) {
int operandCount = 0;
int operatorCount = 0;
- /* Traverse the postfix string to check if --> Number of operands = Number of operators + 1 */
+ /* Traverse the postfix string to check if --> Number of operands = Number of operators + 1
+ */
for (int i = 0; i < postfix.length(); i++) {
char token = postfix.charAt(i);
@@ -59,8 +60,8 @@ public static boolean isValidPostfixExpression(String postfix) {
/* Operand count is set to 2 because:-
*
- * 1) the previous set of operands & operators combined have become a single valid expression,
- * which could be considered/assigned as a single operand.
+ * 1) the previous set of operands & operators combined have become a single valid
+ * expression, which could be considered/assigned as a single operand.
*
* 2) the operand in the current iteration.
*/
@@ -123,7 +124,6 @@ public static void main(String[] args) {
assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))");
assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)");
assert getPostfixToInfix("ABCDE^*/-").equals("(A-(B/(C*(D^E))))");
- assert getPostfixToInfix("AB+CD^/E*FGH+-^")
- .equals("((((A+B)/(C^D))*E)^(F-(G+H)))");
+ assert getPostfixToInfix("AB+CD^/E*FGH+-^").equals("((((A+B)/(C^D))*E)^(F-(G+H)))");
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java
index 1dd9fe11d891..f269d08b5678 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java
@@ -12,9 +12,7 @@ public class ReverseStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
- System.out.println(
- "Enter the number of elements you wish to insert in the stack"
- );
+ System.out.println("Enter the number of elements you wish to insert in the stack");
int n = sc.nextInt();
int i;
Stack stack = new Stack();
@@ -36,28 +34,29 @@ private static void reverseStack(Stack stack) {
return;
}
- //Store the topmost element
+ // Store the topmost element
int element = stack.peek();
- //Remove the topmost element
+ // Remove the topmost element
stack.pop();
- //Reverse the stack for the leftover elements
+ // Reverse the stack for the leftover elements
reverseStack(stack);
- //Insert the topmost element to the bottom of the stack
+ // Insert the topmost element to the bottom of the stack
insertAtBottom(stack, element);
}
private static void insertAtBottom(Stack stack, int element) {
if (stack.isEmpty()) {
- //When stack is empty, insert the element so it will be present at the bottom of the stack
+ // When stack is empty, insert the element so it will be present at the bottom of the
+ // stack
stack.push(element);
return;
}
int ele = stack.peek();
- /*Keep popping elements till stack becomes empty. Push the elements once the topmost element has
- moved to the bottom of the stack.
+ /*Keep popping elements till stack becomes empty. Push the elements once the topmost element
+ has moved to the bottom of the stack.
*/
stack.pop();
insertAtBottom(stack, element);
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java
index 8f8931d1e972..0463018fde82 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java
@@ -23,9 +23,7 @@ public static void main(String[] args) {
assert stack.pop() == 5;
assert stack.pop() == 4;
- System.out.println(
- "Top element of stack currently is: " + stack.peek()
- );
+ System.out.println("Top element of stack currently is: " + stack.peek());
}
}
@@ -120,9 +118,7 @@ public String toString() {
builder.append(cur.data).append("->");
cur = cur.next;
}
- return builder
- .replace(builder.length() - 2, builder.length(), "")
- .toString();
+ return builder.replace(builder.length() - 2, builder.length(), "").toString();
}
/**
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
index 85c44707ea24..1032daa240f8 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
@@ -3,23 +3,23 @@
/*
* Avl is algo that balance itself while adding new alues to tree
* by rotating branches of binary tree and make itself Binary seaarch tree
-* there are four cases which has to tackle
-* rotating - left right ,left left,right right,right left
+* there are four cases which has to tackle
+* rotating - left right ,left left,right right,right left
Test Case:
AVLTree tree=new AVLTree();
- tree.insert(20);
- tree.insert(25);
- tree.insert(30);
- tree.insert(10);
- tree.insert(5);
- tree.insert(15);
- tree.insert(27);
- tree.insert(19);
- tree.insert(16);
-
- tree.display();
+ tree.insert(20);
+ tree.insert(25);
+ tree.insert(30);
+ tree.insert(10);
+ tree.insert(5);
+ tree.insert(15);
+ tree.insert(27);
+ tree.insert(19);
+ tree.insert(16);
+
+ tree.display();
@@ -59,16 +59,16 @@ private Node insert(Node node, int item) {
}
node.height = Math.max(height(node.left), height(node.right)) + 1;
int bf = bf(node);
- //LL case
+ // LL case
if (bf > 1 && item < node.left.data) return rightRotate(node);
- //RR case
+ // RR case
if (bf < -1 && item > node.right.data) return leftRotate(node);
- //RL case
+ // RL case
if (bf < -1 && item < node.right.data) {
node.right = rightRotate(node.right);
return leftRotate(node);
}
- //LR case
+ // LR case
if (bf > 1 && item > node.left.data) {
node.left = leftRotate(node.left);
return rightRotate(node);
@@ -84,11 +84,15 @@ public void display() {
private void display(Node node) {
String str = "";
- if (node.left != null) str += node.left.data + "=>"; else str +=
- "END=>";
+ if (node.left != null)
+ str += node.left.data + "=>";
+ else
+ str += "END=>";
str += node.data + "";
- if (node.right != null) str += "<=" + node.right.data; else str +=
- "<=END";
+ if (node.right != null)
+ str += "<=" + node.right.data;
+ else
+ str += "<=END";
System.out.println(str);
if (node.left != null) display(node.left);
if (node.right != null) display(node.right);
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java
index f7fecdb3fe86..b70fcb280ac3 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java
@@ -39,17 +39,20 @@ public static void main(String[] args) {
integerTree.add(5);
integerTree.add(10);
integerTree.add(9);
- assert !integerTree.find(4) : "4 is not yet present in BST";
- assert integerTree.find(10) : "10 should be present in BST";
+ assert !integerTree.find(4)
+ : "4 is not yet present in BST";
+ assert integerTree.find(10)
+ : "10 should be present in BST";
integerTree.remove(9);
- assert !integerTree.find(9) : "9 was just deleted from BST";
+ assert !integerTree.find(9)
+ : "9 was just deleted from BST";
integerTree.remove(1);
- assert !integerTree.find(
- 1
- ) : "Since 1 was not present so find deleting would do no change";
+ assert !integerTree.find(1)
+ : "Since 1 was not present so find deleting would do no change";
integerTree.add(20);
integerTree.add(70);
- assert integerTree.find(70) : "70 was inserted but not found";
+ assert integerTree.find(70)
+ : "70 was inserted but not found";
/*
Will print in following order
5 10 20 70
@@ -63,17 +66,20 @@ public static void main(String[] args) {
stringTree.add("banana");
stringTree.add("pineapple");
stringTree.add("date");
- assert !stringTree.find("girl") : "girl is not yet present in BST";
- assert stringTree.find("pineapple") : "10 should be present in BST";
+ assert !stringTree.find("girl")
+ : "girl is not yet present in BST";
+ assert stringTree.find("pineapple")
+ : "10 should be present in BST";
stringTree.remove("date");
- assert !stringTree.find("date") : "date was just deleted from BST";
+ assert !stringTree.find("date")
+ : "date was just deleted from BST";
stringTree.remove("boy");
- assert !stringTree.find(
- "boy"
- ) : "Since boy was not present so deleting would do no change";
+ assert !stringTree.find("boy")
+ : "Since boy was not present so deleting would do no change";
stringTree.add("india");
stringTree.add("hills");
- assert stringTree.find("hills") : "hills was inserted but not found";
+ assert stringTree.find("hills")
+ : "hills was inserted but not found";
/*
Will print in following order
banana hills india pineapple
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java
index fc0db9b8cd92..d86130dff470 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java
@@ -143,7 +143,8 @@ public boolean remove(int value) {
if (temp.right == null && temp.left == null) {
if (temp == root) {
root = null;
- } // This if/else assigns the new node to be either the left or right child of the parent
+ } // This if/else assigns the new node to be either the left or right child of the
+ // parent
else if (temp.parent.data < temp.data) {
temp.parent.right = null;
} else {
@@ -179,7 +180,8 @@ else if (temp.left != null && temp.right != null) {
else {
successor.parent = temp.parent;
- // This if/else assigns the new node to be either the left or right child of the parent
+ // This if/else assigns the new node to be either the left or right child of the
+ // parent
if (temp.parent.data < temp.data) {
temp.parent.right = successor;
} else {
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java
index 13246944737c..19fbb6a8357f 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java
@@ -24,8 +24,6 @@ private static boolean isBSTUtil(BinaryTree.Node node, int min, int max) {
}
return (
- isBSTUtil(node.left, min, node.data - 1) &&
- isBSTUtil(node.right, node.data + 1, max)
- );
+ isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java
index e953a37d1c82..c4d6ff94ae61 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java
@@ -80,11 +80,7 @@ public boolean isBalancedRecursive(BinaryTree binaryTree) {
* @param depth The current depth of the node
* @param isBalanced The array of length 1 keeping track of our balance
*/
- private int isBalancedRecursive(
- BTNode node,
- int depth,
- boolean[] isBalanced
- ) {
+ private int isBalancedRecursive(BTNode node, int depth, boolean[] isBalanced) {
// If the node is null, we should not explore it and the height is 0
// If the tree is already not balanced, might as well stop because we
// can't make it balanced now!
@@ -94,11 +90,7 @@ private int isBalancedRecursive(
// Visit the left and right children, incrementing their depths by 1
int leftHeight = isBalancedRecursive(node.left, depth + 1, isBalanced);
- int rightHeight = isBalancedRecursive(
- node.right,
- depth + 1,
- isBalanced
- );
+ int rightHeight = isBalancedRecursive(node.right, depth + 1, isBalanced);
// If the height of either of the left or right subtrees differ by more
// than 1, we cannot be balanced
@@ -174,10 +166,7 @@ public boolean isBalancedIterative(BinaryTree binaryTree) {
// The height of the subtree containing this node is the
// max of the left and right subtree heighs plus 1
- subtreeHeights.put(
- node,
- Math.max(rightHeight, leftHeight) + 1
- );
+ subtreeHeights.put(node, Math.max(rightHeight, leftHeight) + 1);
// We've now visited this node, so we pop it from the stack
nodeStack.pop();
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java
index 0df93cefb9e3..bb592bd4131a 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java
@@ -48,10 +48,12 @@ private static boolean isSymmetric(Node leftSubtreeRoot, Node rightSubtreRoot) {
return false;
}
- return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left) && isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right);
+ return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left)
+ && isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right);
}
private static boolean isInvalidSubtree(Node leftSubtreeRoot, Node rightSubtreeRoot) {
- return leftSubtreeRoot == null || rightSubtreeRoot == null || leftSubtreeRoot.data != rightSubtreeRoot.data;
+ return leftSubtreeRoot == null || rightSubtreeRoot == null
+ || leftSubtreeRoot.data != rightSubtreeRoot.data;
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java
index 99b1fb4efe97..5c08a0021450 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java
@@ -1,7 +1,6 @@
package com.thealgorithms.datastructures.trees;
import com.thealgorithms.datastructures.trees.BinaryTree.Node;
-
import java.util.HashMap;
import java.util.Map;
@@ -37,13 +36,8 @@ public static Node createTreeOptimized(final Integer[] preorder, final Integer[]
return createTreeOptimized(preorder, inorderMap, 0, 0, inorder.length);
}
- private static Node createTree(
- final Integer[] preorder,
- final Integer[] inorder,
- final int preStart,
- final int inStart,
- final int size
- ) {
+ private static Node createTree(final Integer[] preorder, final Integer[] inorder,
+ final int preStart, final int inStart, final int size) {
if (size == 0) {
return null;
}
@@ -55,32 +49,15 @@ private static Node createTree(
}
int leftNodesCount = i - inStart;
int rightNodesCount = size - leftNodesCount - 1;
- root.left =
- createTree(
- preorder,
- inorder,
- preStart + 1,
- inStart,
- leftNodesCount
- );
- root.right =
- createTree(
- preorder,
- inorder,
- preStart + leftNodesCount + 1,
- i + 1,
- rightNodesCount
- );
+ root.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount);
+ root.right
+ = createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
return root;
}
- private static Node createTreeOptimized(
- final Integer[] preorder,
- final Map inorderMap,
- final int preStart,
- final int inStart,
- final int size
- ) {
+ private static Node createTreeOptimized(final Integer[] preorder,
+ final Map inorderMap, final int preStart, final int inStart,
+ final int size) {
if (size == 0) {
return null;
}
@@ -89,22 +66,10 @@ private static Node createTreeOptimized(
int i = inorderMap.get(preorder[preStart]);
int leftNodesCount = i - inStart;
int rightNodesCount = size - leftNodesCount - 1;
- root.left =
- createTreeOptimized(
- preorder,
- inorderMap,
- preStart + 1,
- inStart,
- leftNodesCount
- );
- root.right =
- createTreeOptimized(
- preorder,
- inorderMap,
- preStart + leftNodesCount + 1,
- i + 1,
- rightNodesCount
- );
+ root.left
+ = createTreeOptimized(preorder, inorderMap, preStart + 1, inStart, leftNodesCount);
+ root.right = createTreeOptimized(
+ preorder, inorderMap, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
return root;
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
index c22bdab08f2b..d4bbf0c9aad6 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
@@ -35,9 +35,7 @@ private Node create_treeG(Node node, int childindx, Scanner scn) {
if (node == null) {
System.out.println("Enter root's data");
} else {
- System.out.println(
- "Enter data of parent of index " + node.data + " " + childindx
- );
+ System.out.println("Enter data of parent of index " + node.data + " " + childindx);
}
// input
node = new Node();
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java
index cd28f93c9d56..f0f8fac8e528 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java
@@ -34,15 +34,11 @@ public class KDTree {
* @param points Array of initial points
*/
KDTree(Point[] points) {
- if (points.length == 0) throw new IllegalArgumentException(
- "Points array cannot be empty"
- );
+ if (points.length == 0) throw new IllegalArgumentException("Points array cannot be empty");
this.k = points[0].getDimension();
- for (Point point : points) if (
- point.getDimension() != k
- ) throw new IllegalArgumentException(
- "Points must have the same dimension"
- );
+ for (Point point : points)
+ if (point.getDimension() != k)
+ throw new IllegalArgumentException("Points must have the same dimension");
this.root = build(points, 0);
}
@@ -53,19 +49,13 @@ public class KDTree {
*
*/
KDTree(int[][] pointsCoordinates) {
- if (pointsCoordinates.length == 0) throw new IllegalArgumentException(
- "Points array cannot be empty"
- );
+ if (pointsCoordinates.length == 0)
+ throw new IllegalArgumentException("Points array cannot be empty");
this.k = pointsCoordinates[0].length;
- Point[] points = Arrays
- .stream(pointsCoordinates)
- .map(Point::new)
- .toArray(Point[]::new);
- for (Point point : points) if (
- point.getDimension() != k
- ) throw new IllegalArgumentException(
- "Points must have the same dimension"
- );
+ Point[] points = Arrays.stream(pointsCoordinates).map(Point::new).toArray(Point[] ::new);
+ for (Point point : points)
+ if (point.getDimension() != k)
+ throw new IllegalArgumentException("Points must have the same dimension");
this.root = build(points, 0);
}
@@ -125,11 +115,7 @@ public static int comparableDistance(Point p1, Point p2) {
*
* @return The distance between the two points
*/
- public static int comparableDistanceExceptAxis(
- Point p1,
- Point p2,
- int axis
- ) {
+ public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) {
int distance = 0;
for (int i = 0; i < p1.getDimension(); i++) {
if (i == axis) continue;
@@ -177,9 +163,10 @@ public int getAxis() {
* @return The nearest child Node
*/
public Node getNearChild(Point point) {
- if (
- point.getCoordinate(axis) < this.point.getCoordinate(axis)
- ) return left; else return right;
+ if (point.getCoordinate(axis) < this.point.getCoordinate(axis))
+ return left;
+ else
+ return right;
}
/**
@@ -190,9 +177,10 @@ public Node getNearChild(Point point) {
* @return The farthest child Node
*/
public Node getFarChild(Point point) {
- if (
- point.getCoordinate(axis) < this.point.getCoordinate(axis)
- ) return right; else return left;
+ if (point.getCoordinate(axis) < this.point.getCoordinate(axis))
+ return right;
+ else
+ return left;
}
/**
@@ -221,18 +209,11 @@ private Node build(Point[] points, int depth) {
if (points.length == 0) return null;
int axis = depth % k;
if (points.length == 1) return new Node(points[0], axis);
- Arrays.sort(
- points,
- Comparator.comparingInt(o -> o.getCoordinate(axis))
- );
+ Arrays.sort(points, Comparator.comparingInt(o -> o.getCoordinate(axis)));
int median = points.length >> 1;
Node node = new Node(points[median], axis);
node.left = build(Arrays.copyOfRange(points, 0, median), depth + 1);
- node.right =
- build(
- Arrays.copyOfRange(points, median + 1, points.length),
- depth + 1
- );
+ node.right = build(Arrays.copyOfRange(points, median + 1, points.length), depth + 1);
return node;
}
@@ -243,9 +224,8 @@ private Node build(Point[] points, int depth) {
*
*/
public void insert(Point point) {
- if (point.getDimension() != k) throw new IllegalArgumentException(
- "Point has wrong dimension"
- );
+ if (point.getDimension() != k)
+ throw new IllegalArgumentException("Point has wrong dimension");
root = insert(root, point, 0);
}
@@ -261,9 +241,10 @@ public void insert(Point point) {
private Node insert(Node root, Point point, int depth) {
int axis = depth % k;
if (root == null) return new Node(point, axis);
- if (point.getCoordinate(axis) < root.getAxisCoordinate()) root.left =
- insert(root.left, point, depth + 1); else root.right =
- insert(root.right, point, depth + 1);
+ if (point.getCoordinate(axis) < root.getAxisCoordinate())
+ root.left = insert(root.left, point, depth + 1);
+ else
+ root.right = insert(root.right, point, depth + 1);
return root;
}
@@ -276,9 +257,8 @@ private Node insert(Node root, Point point, int depth) {
* @return The Node corresponding to the specified point
*/
public Optional search(Point point) {
- if (point.getDimension() != k) throw new IllegalArgumentException(
- "Point has wrong dimension"
- );
+ if (point.getDimension() != k)
+ throw new IllegalArgumentException("Point has wrong dimension");
return search(root, point);
}
@@ -323,9 +303,8 @@ public Node findMin(Node root, int axis) {
} else {
Node left = findMin(root.left, axis);
Node right = findMin(root.right, axis);
- Node[] candidates = { left, root, right };
- return Arrays
- .stream(candidates)
+ Node[] candidates = {left, root, right};
+ return Arrays.stream(candidates)
.filter(Objects::nonNull)
.min(Comparator.comparingInt(a -> a.point.getCoordinate(axis)))
.orElse(null);
@@ -359,9 +338,8 @@ public Node findMax(Node root, int axis) {
} else {
Node left = findMax(root.left, axis);
Node right = findMax(root.right, axis);
- Node[] candidates = { left, root, right };
- return Arrays
- .stream(candidates)
+ Node[] candidates = {left, root, right};
+ return Arrays.stream(candidates)
.filter(Objects::nonNull)
.max(Comparator.comparingInt(a -> a.point.getCoordinate(axis)))
.orElse(null);
@@ -374,8 +352,8 @@ public Node findMax(Node root, int axis) {
* @param point the point to delete
* */
public void delete(Point point) {
- Node node = search(point)
- .orElseThrow(() -> new IllegalArgumentException("Point not found"));
+ Node node
+ = search(point).orElseThrow(() -> new IllegalArgumentException("Point not found"));
root = delete(root, node);
}
@@ -398,12 +376,13 @@ private Node delete(Node root, Node node) {
Node min = findMin(root.left, root.getAxis());
root.point = min.point;
root.left = delete(root.left, min);
- } else return null;
+ } else
+ return null;
}
- if (
- root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())
- ) root.left = delete(root.left, node); else root.right =
- delete(root.right, node);
+ if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis()))
+ root.left = delete(root.left, node);
+ else
+ root.right = delete(root.right, node);
return root;
}
@@ -427,17 +406,12 @@ private Node findNearest(Node root, Point point, Node nearest) {
if (root == null) return nearest;
if (root.point.equals(point)) return root;
int distance = Point.comparableDistance(root.point, point);
- int distanceExceptAxis = Point.comparableDistanceExceptAxis(
- root.point,
- point,
- root.getAxis()
- );
- if (distance < Point.comparableDistance(nearest.point, point)) nearest =
- root;
+ int distanceExceptAxis
+ = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis());
+ if (distance < Point.comparableDistance(nearest.point, point)) nearest = root;
nearest = findNearest(root.getNearChild(point), point, nearest);
- if (
- distanceExceptAxis < Point.comparableDistance(nearest.point, point)
- ) nearest = findNearest(root.getFarChild(point), point, nearest);
+ if (distanceExceptAxis < Point.comparableDistance(nearest.point, point))
+ nearest = findNearest(root.getFarChild(point), point, nearest);
return nearest;
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LCA.java b/src/main/java/com/thealgorithms/datastructures/trees/LCA.java
index 1fe83e0c0de5..d7bdb0af5486 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/LCA.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/LCA.java
@@ -8,17 +8,17 @@ public class LCA {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
- //The adjacency list representation of a tree:
+ // The adjacency list representation of a tree:
ArrayList> adj = new ArrayList<>();
- //v is the number of vertices and e is the number of edges
+ // v is the number of vertices and e is the number of edges
int v = scanner.nextInt(), e = v - 1;
for (int i = 0; i < v; i++) {
adj.add(new ArrayList());
}
- //Storing the given tree as an adjacency list
+ // Storing the given tree as an adjacency list
int to, from;
for (int i = 0; i < e; i++) {
to = scanner.nextInt();
@@ -28,19 +28,19 @@ public static void main(String[] args) {
adj.get(from).add(to);
}
- //parent[v1] gives parent of a vertex v1
+ // parent[v1] gives parent of a vertex v1
int[] parent = new int[v];
- //depth[v1] gives depth of vertex v1 with respect to the root
+ // depth[v1] gives depth of vertex v1 with respect to the root
int[] depth = new int[v];
- //Assuming the tree to be rooted at 0, hence calculating parent and depth of every vertex
+ // Assuming the tree to be rooted at 0, hence calculating parent and depth of every vertex
dfs(adj, 0, -1, parent, depth);
- //Inputting the two vertices whose LCA is to be calculated
+ // Inputting the two vertices whose LCA is to be calculated
int v1 = scanner.nextInt(), v2 = scanner.nextInt();
- //Outputting the LCA
+ // Outputting the LCA
System.out.println(getLCA(v1, v2, depth, parent));
}
@@ -54,12 +54,7 @@ public static void main(String[] args) {
* @param depth An array to store depth of all vertices
*/
private static void dfs(
- ArrayList> adj,
- int s,
- int p,
- int[] parent,
- int[] depth
- ) {
+ ArrayList> adj, int s, int p, int[] parent, int[] depth) {
for (int adjacent : adj.get(s)) {
if (adjacent != p) {
parent[adjacent] = s;
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java
index a98ec9ddd86b..b5a9db9f5e11 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java
@@ -24,7 +24,8 @@ public Node(int start, int end, int value) {
this.right = null;
}
- /** Update the value of this node with the given value diff.
+ /**
+ * Update the value of this node with the given value diff.
*
* @param diff The value to add to every index of this node range.
*/
@@ -33,7 +34,8 @@ public void applyUpdate(int diff) {
this.value += (this.end - this.start) * diff;
}
- /** Shift the lazy value of this node to its children.
+ /**
+ * Shift the lazy value of this node to its children.
*/
public void shift() {
if (lazy == 0) return;
@@ -44,7 +46,8 @@ public void shift() {
this.lazy = 0;
}
- /** Create a new node that is the sum of this node and the given node.
+ /**
+ * Create a new node that is the sum of this node and the given node.
*
* @param left The left Node of merging
* @param right The right Node of merging
@@ -53,11 +56,7 @@ public void shift() {
static Node merge(Node left, Node right) {
if (left == null) return right;
if (right == null) return left;
- Node result = new Node(
- left.start,
- right.end,
- left.value + right.value
- );
+ Node result = new Node(left.start, right.end, left.value + right.value);
result.left = left;
result.right = right;
return result;
@@ -78,7 +77,8 @@ public Node getRight() {
private final Node root;
- /** Create a new LazySegmentTree with the given array.
+ /**
+ * Create a new LazySegmentTree with the given array.
*
* @param array The array to create the LazySegmentTree from.
*/
@@ -86,7 +86,8 @@ public LazySegmentTree(int[] array) {
this.root = buildTree(array, 0, array.length);
}
- /** Build a new LazySegmentTree from the given array in O(n) time.
+ /**
+ * Build a new LazySegmentTree from the given array in O(n) time.
*
* @param array The array to build the LazySegmentTree from.
* @param start The start index of the current node.
@@ -101,7 +102,8 @@ private Node buildTree(int[] array, int start, int end) {
return Node.merge(left, right);
}
- /** Update the value of given range with the given value diff in O(log n) time.
+ /**
+ * Update the value of given range with the given value diff in O(log n) time.
*
* @param left The left index of the range to update.
* @param right The right index of the range to update.
@@ -121,7 +123,8 @@ private void updateRange(int left, int right, int diff, Node curr) {
curr.value = merge.value;
}
- /** Get Node of given range in O(log n) time.
+ /**
+ * Get Node of given range in O(log n) time.
*
* @param left The left index of the range to update.
* @param right The right index of the range to update.
@@ -131,10 +134,7 @@ private Node getRange(int left, int right, Node curr) {
if (left <= curr.start && curr.end <= right) return curr;
if (left >= curr.end || right <= curr.start) return null;
curr.shift();
- return Node.merge(
- getRange(left, right, curr.left),
- getRange(left, right, curr.right)
- );
+ return Node.merge(getRange(left, right, curr.left), getRange(left, right, curr.right));
}
public int getRange(int left, int right) {
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java
index 7103a9ead2ca..fbb51701471f 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java
@@ -28,14 +28,8 @@ public void printTree(Node node) {
return;
}
printTree(node.left);
- System.out.print(
- ((node.color == R) ? " R " : " B ") +
- "Key: " +
- node.key +
- " Parent: " +
- node.p.key +
- "\n"
- );
+ System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key
+ + " Parent: " + node.p.key + "\n");
printTree(node.right);
}
@@ -43,14 +37,8 @@ public void printTreepre(Node node) {
if (node == nil) {
return;
}
- System.out.print(
- ((node.color == R) ? " R " : " B ") +
- "Key: " +
- node.key +
- " Parent: " +
- node.p.key +
- "\n"
- );
+ System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key
+ + " Parent: " + node.p.key + "\n");
printTreepre(node.left);
printTreepre(node.right);
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java
index 6a2258b5e065..aede2a23b544 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java
@@ -5,9 +5,8 @@
/**
* Given 2 binary trees.
- * This code checks whether they are the same (structurally identical and have the same values) or not.
- *
- * Example:
+ * This code checks whether they are the same (structurally identical and have the same values) or
+ * not.
Example:
* 1. Binary trees:
* 1 1
* / \ / \
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java
index e24db38da08f..d7674f4a4086 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java
@@ -26,21 +26,14 @@ public int constructTree(int[] arr, int start, int end, int index) {
}
int mid = start + (end - start) / 2;
- this.seg_t[index] =
- constructTree(arr, start, mid, index * 2 + 1) +
- constructTree(arr, mid + 1, end, index * 2 + 2);
+ this.seg_t[index] = constructTree(arr, start, mid, index * 2 + 1)
+ + constructTree(arr, mid + 1, end, index * 2 + 2);
return this.seg_t[index];
}
/* A function which will update the value at a index i. This will be called by the
update function internally*/
- private void updateTree(
- int start,
- int end,
- int index,
- int diff,
- int seg_index
- ) {
+ private void updateTree(int start, int end, int index, int diff, int seg_index) {
if (index < start || index > end) {
return;
}
@@ -64,14 +57,9 @@ public void update(int index, int value) {
updateTree(0, n - 1, index, diff, 0);
}
- /* A function to get the sum of the elements from index l to index r. This will be called internally*/
- private int getSumTree(
- int start,
- int end,
- int q_start,
- int q_end,
- int seg_index
- ) {
+ /* A function to get the sum of the elements from index l to index r. This will be called
+ * internally*/
+ private int getSumTree(int start, int end, int q_start, int q_end, int seg_index) {
if (q_start <= start && q_end >= end) {
return this.seg_t[seg_index];
}
@@ -81,10 +69,8 @@ private int getSumTree(
}
int mid = start + (end - start) / 2;
- return (
- getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) +
- getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2)
- );
+ return (getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1)
+ + getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2));
}
/* A function to query the sum of the subarray [start...end]*/
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java
index 369eaf57cc2a..d9f5a6f0ec43 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java
@@ -5,7 +5,8 @@
*/
/* PROBLEM DESCRIPTION :
- There is a Binary Search Tree given, and we are supposed to find a random node in the given binary tree.
+ There is a Binary Search Tree given, and we are supposed to find a random node in the given binary
+ tree.
*/
/* ALGORITHM :
@@ -14,9 +15,9 @@
Step 3: Now use a method inOrder() that takes a node as input parameter to traverse through the
binary tree in inorder fashion as also store the values in a ArrayList simultaneously.
Step 4: Now define a method getRandom() that takes a node as input parameter, in this first call
- the inOrder() method to store the values in the arraylist, then find the size of the binary tree and now just generate a random number between 0 to n-1.
- Step 5: After generating the number display the value of the ArrayList at the generated index
- Step 6: STOP
+ the inOrder() method to store the values in the arraylist, then find the size of the
+ binary tree and now just generate a random number between 0 to n-1. Step 5: After generating the
+ number display the value of the ArrayList at the generated index Step 6: STOP
*/
import java.util.ArrayList;
@@ -65,7 +66,7 @@ public void getRandom(Node val) {
int n = list.size();
int min = 0;
int max = n - 1;
- //Generate random int value from 0 to n-1
+ // Generate random int value from 0 to n-1
int b = (int) (Math.random() * (max - min + 1) + min);
// displaying the value at the generated index
int random = list.get(b);
@@ -74,9 +75,10 @@ public void getRandom(Node val) {
}
/* Explanation of the Approach :
(a) Form the required binary tree
- (b) Now use the inOrder() method to get the nodes in inOrder fashion and also store them in the given arraylist 'list'
- (c) Using the getRandom() method generate a random number between 0 to n-1, then get the value at the generated random number
- from the arraylist using get() method and finally display the result.
+ (b) Now use the inOrder() method to get the nodes in inOrder fashion and also store them in the
+ given arraylist 'list' (c) Using the getRandom() method generate a random number between 0 to n-1,
+ then get the value at the generated random number from the arraylist using get() method and
+ finally display the result.
*/
/* OUTPUT :
First output :
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java b/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java
index 5829f920cac8..79c66cb90f01 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java
@@ -83,57 +83,56 @@ public static boolean isValid(String word) {
public static void main(String[] args) {
TrieImp obj = new TrieImp();
String word;
- @SuppressWarnings("resource")
- Scanner scan = new Scanner(System.in);
+ @SuppressWarnings("resource") Scanner scan = new Scanner(System.in);
sop("string should contain only a-z character for all operation");
while (true) {
sop("1. Insert\n2. Search\n3. Delete\n4. Quit");
try {
int t = scan.nextInt();
switch (t) {
- case 1:
- word = scan.next();
- if (isValid(word)) {
- obj.insert(word);
- } else {
- sop("Invalid string: allowed only a-z");
- }
- break;
- case 2:
- word = scan.next();
- boolean resS = false;
- if (isValid(word)) {
- resS = obj.search(word);
- } else {
- sop("Invalid string: allowed only a-z");
- }
- if (resS) {
- sop("word found");
- } else {
- sop("word not found");
- }
- break;
- case 3:
- word = scan.next();
- boolean resD = false;
- if (isValid(word)) {
- resD = obj.delete(word);
- } else {
- sop("Invalid string: allowed only a-z");
- }
- if (resD) {
- sop("word got deleted successfully");
- } else {
- sop("word not found");
- }
- break;
- case 4:
- sop("Quit successfully");
- System.exit(1);
- break;
- default:
- sop("Input int from 1-4");
- break;
+ case 1:
+ word = scan.next();
+ if (isValid(word)) {
+ obj.insert(word);
+ } else {
+ sop("Invalid string: allowed only a-z");
+ }
+ break;
+ case 2:
+ word = scan.next();
+ boolean resS = false;
+ if (isValid(word)) {
+ resS = obj.search(word);
+ } else {
+ sop("Invalid string: allowed only a-z");
+ }
+ if (resS) {
+ sop("word found");
+ } else {
+ sop("word not found");
+ }
+ break;
+ case 3:
+ word = scan.next();
+ boolean resD = false;
+ if (isValid(word)) {
+ resD = obj.delete(word);
+ } else {
+ sop("Invalid string: allowed only a-z");
+ }
+ if (resD) {
+ sop("word got deleted successfully");
+ } else {
+ sop("word not found");
+ }
+ break;
+ case 4:
+ sop("Quit successfully");
+ System.exit(1);
+ break;
+ default:
+ sop("Input int from 1-4");
+ break;
}
} catch (Exception e) {
String badInput = scan.next();
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java
index 15fd348ea1eb..a42b4370de68 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java
@@ -23,7 +23,7 @@
public class VerticalOrderTraversal {
/*Function that receives a root Node and prints the tree
- in Vertical Order.*/
+ in Vertical Order.*/
public static ArrayList verticalTraversal(BinaryTree.Node root) {
if (root == null) {
return new ArrayList<>();
@@ -32,19 +32,19 @@ public static ArrayList verticalTraversal(BinaryTree.Node root) {
/*Queue to store the Nodes.*/
Queue queue = new LinkedList<>();
- /*Queue to store the index of particular vertical
- column of a tree , with root at 0, Nodes on left
- with negative index and Nodes on right with positive
- index. */
+ /*Queue to store the index of particular vertical
+ column of a tree , with root at 0, Nodes on left
+ with negative index and Nodes on right with positive
+ index. */
Queue index = new LinkedList<>();
- /*Map of Integer and ArrayList to store all the
- elements in a particular index in a single arrayList
- that will have a key equal to the index itself. */
+ /*Map of Integer and ArrayList to store all the
+ elements in a particular index in a single arrayList
+ that will have a key equal to the index itself. */
Map> map = new HashMap<>();
/* min and max stores leftmost and right most index to
- later print the tree in vertical fashion.*/
+ later print the tree in vertical fashion.*/
int max = 0, min = 0;
queue.offer(root);
index.offer(0);
@@ -52,38 +52,38 @@ public static ArrayList verticalTraversal(BinaryTree.Node root) {
while (!queue.isEmpty()) {
if (queue.peek().left != null) {
/*Adding the left Node if it is not null
- and its index by subtracting 1 from it's
- parent's index*/
+ and its index by subtracting 1 from it's
+ parent's index*/
queue.offer(queue.peek().left);
index.offer(index.peek() - 1);
}
if (queue.peek().right != null) {
/*Adding the right Node if it is not null
- and its index by adding 1 from it's
- parent's index*/
+ and its index by adding 1 from it's
+ parent's index*/
queue.offer(queue.peek().right);
index.offer(index.peek() + 1);
}
/*If the map does not contains the index a new
- ArrayList is created with the index as key.*/
+ ArrayList is created with the index as key.*/
if (!map.containsKey(index.peek())) {
ArrayList a = new ArrayList<>();
map.put(index.peek(), a);
}
/*For a index, corresponding Node data is added
- to the respective ArrayList present at that
- index. */
+ to the respective ArrayList present at that
+ index. */
map.get(index.peek()).add(queue.peek().data);
max = Math.max(max, index.peek());
min = Math.min(min, index.peek());
/*The Node and its index are removed
- from their respective queues.*/
+ from their respective queues.*/
index.poll();
queue.poll();
}
/*Finally map data is printed here which has keys
- from min to max. Each ArrayList represents a
- vertical column that is added in ans ArrayList.*/
+ from min to max. Each ArrayList represents a
+ vertical column that is added in ans ArrayList.*/
ArrayList ans = new ArrayList<>();
for (int i = min; i <= max; i++) {
ans.addAll(map.get(i));
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java
index 7aafcdf83b3d..d5bfd68e97e4 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java
@@ -17,7 +17,8 @@
* This solution implements the breadth-first search (BFS) algorithm using a queue.
* 1. The algorithm starts with a root node. This node is added to a queue.
* 2. While the queue is not empty:
- * - each time we enter the while-loop we get queue size. Queue size refers to the number of nodes at the current level.
+ * - each time we enter the while-loop we get queue size. Queue size refers to the number of nodes
+ * at the current level.
* - we traverse all the level nodes in 2 ways: from left to right OR from right to left
* (this state is stored on `prevLevelFromLeftToRight` variable)
* - if the current node has children we add them to a queue
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java
index 773d30743ab2..f0626c1dae47 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java
@@ -27,7 +27,7 @@ public static NRKTree BuildTree() {
}
public static int nearestRightKey(NRKTree root, int x0) {
- //Check whether tree is empty
+ // Check whether tree is empty
if (root == null) {
return 0;
} else {
diff --git a/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java b/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java
index 873e46367841..388fb3fd9056 100644
--- a/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java
+++ b/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java
@@ -25,7 +25,6 @@ public int getBurstTime() {
return burstTime;
}
-
public int getWaitingTime() {
return waitingTime;
}
diff --git a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
index 7a60741d5d96..bfd30f9f3f24 100644
--- a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
+++ b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
@@ -54,10 +54,7 @@ public LargeTreeNode(E data, LargeTreeNode parentNode) {
* @see TreeNode#TreeNode(Object, Node)
*/
public LargeTreeNode(
- E data,
- LargeTreeNode parentNode,
- Collection> childNodes
- ) {
+ E data, LargeTreeNode parentNode, Collection> childNodes) {
super(data, parentNode);
this.childNodes = childNodes;
}
diff --git a/src/main/java/com/thealgorithms/devutils/nodes/Node.java b/src/main/java/com/thealgorithms/devutils/nodes/Node.java
index e6be58f5f616..a10817830962 100644
--- a/src/main/java/com/thealgorithms/devutils/nodes/Node.java
+++ b/src/main/java/com/thealgorithms/devutils/nodes/Node.java
@@ -20,7 +20,8 @@ public abstract class Node {
/**
* Empty constructor.
*/
- public Node() {}
+ public Node() {
+ }
/**
* Initializes the Nodes' data.
diff --git a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java
index 7230db73fb87..61f430bda3f3 100644
--- a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java
+++ b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java
@@ -57,12 +57,8 @@ public SimpleTreeNode(E data, SimpleTreeNode parentNode) {
* @param rightNode Value to which the nodes' right child reference will be
* set.
*/
- public SimpleTreeNode(
- E data,
- SimpleTreeNode parentNode,
- SimpleTreeNode leftNode,
- SimpleTreeNode rightNode
- ) {
+ public SimpleTreeNode(E data, SimpleTreeNode parentNode, SimpleTreeNode leftNode,
+ SimpleTreeNode rightNode) {
super(data, parentNode);
this.leftNode = leftNode;
this.rightNode = rightNode;
diff --git a/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java b/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java
index 365eb48cb245..da45d5b90cae 100644
--- a/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java
+++ b/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java
@@ -5,7 +5,7 @@
/*
* Binary Exponentiation is a method to calculate a to the power of b.
* It is used to calculate a^n in O(log n) time.
- *
+ *
* Reference:
* https://iq.opengenus.org/binary-exponentiation/
*/
diff --git a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java
index ad0c6867e5a2..aa453539ac94 100644
--- a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java
+++ b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java
@@ -135,11 +135,7 @@ public int yPartition(final Location[] a, final int first, final int last) {
* @param first (IN Parameter) first point
* @param last (IN Parameter) last point
*/
- public void xQuickSort(
- final Location[] a,
- final int first,
- final int last
- ) {
+ public void xQuickSort(final Location[] a, final int first, final int last) {
if (first < last) {
int q = xPartition(a, first, last); // pivot
xQuickSort(a, first, q - 1); // Left
@@ -154,11 +150,7 @@ public void xQuickSort(
* @param first (IN Parameter) first point
* @param last (IN Parameter) last point
*/
- public void yQuickSort(
- final Location[] a,
- final int first,
- final int last
- ) {
+ public void yQuickSort(final Location[] a, final int first, final int last) {
if (first < last) {
int q = yPartition(a, first, last); // pivot
yQuickSort(a, first, q - 1); // Left
@@ -186,13 +178,7 @@ public double closestPair(final Location[] a, final int indexNum) {
// divide-left array
System.arraycopy(divideArray, 0, leftArray, 0, divideX);
// divide-right array
- System.arraycopy(
- divideArray,
- divideX,
- rightArray,
- 0,
- indexNum - divideX
- );
+ System.arraycopy(divideArray, divideX, rightArray, 0, indexNum - divideX);
double minLeftArea; // Minimum length of left array
double minRightArea; // Minimum length of right array
diff --git a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java
index f7ba384c6fbe..610b1b78a36a 100644
--- a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java
+++ b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java
@@ -92,16 +92,10 @@ public ArrayList produceSubSkyLines(ArrayList list) {
* @param right the skyline of the right part of points
* @return left the final skyline
*/
- public ArrayList produceFinalSkyLine(
- ArrayList left,
- ArrayList right
- ) {
+ public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right) {
// dominated points of ArrayList left are removed
for (int i = 0; i < left.size() - 1; i++) {
- if (
- left.get(i).x == left.get(i + 1).x &&
- left.get(i).y > left.get(i + 1).y
- ) {
+ if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) {
left.remove(i);
i--;
}
@@ -172,10 +166,7 @@ public int getY() {
*/
public boolean dominates(Point p1) {
// checks if p1 is dominated
- return (
- (this.x < p1.x && this.y <= p1.y) ||
- (this.x <= p1.x && this.y < p1.y)
- );
+ return ((this.x < p1.x && this.y <= p1.y) || (this.x <= p1.x && this.y < p1.y));
}
}
diff --git a/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java b/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java
index 7fe4fe186062..4c25066a3553 100644
--- a/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java
+++ b/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java
@@ -4,12 +4,12 @@
/*
* Uses the divide and conquer approach to multiply two matrices.
- * Time Complexity: O(n^2.8074) better than the O(n^3) of the standard matrix multiplication algorithm.
- * Space Complexity: O(n^2)
- *
- * This Matrix multiplication can be performed only on square matrices
+ * Time Complexity: O(n^2.8074) better than the O(n^3) of the standard matrix multiplication
+ * algorithm. Space Complexity: O(n^2)
+ *
+ * This Matrix multiplication can be performed only on square matrices
* where n is a power of 2. Order of both of the matrices are n × n.
- *
+ *
* Reference:
* https://www.tutorialspoint.com/design_and_analysis_of_algorithms/design_and_analysis_of_algorithms_strassens_matrix_multiplication.htm#:~:text=Strassen's%20Matrix%20multiplication%20can%20be,matrices%20are%20n%20%C3%97%20n.
* https://www.geeksforgeeks.org/strassens-matrix-multiplication/
@@ -139,5 +139,4 @@ public void join(int[][] C, int[][] P, int iB, int jB) {
}
}
}
-
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java
index 0f2a14282240..7deb81448b55 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java
@@ -11,16 +11,16 @@
here target is 10
int n=10;
- startAlgo();
- System.out.println(bpR(0,n));
- System.out.println(endAlgo()+"ms");
- int[] strg=new int [n+1];
- startAlgo();
- System.out.println(bpRS(0,n,strg));
- System.out.println(endAlgo()+"ms");
- startAlgo();
- System.out.println(bpIS(0,n,strg));
- System.out.println(endAlgo()+"ms");
+ startAlgo();
+ System.out.println(bpR(0,n));
+ System.out.println(endAlgo()+"ms");
+ int[] strg=new int [n+1];
+ startAlgo();
+ System.out.println(bpRS(0,n,strg));
+ System.out.println(endAlgo()+"ms");
+ startAlgo();
+ System.out.println(bpIS(0,n,strg));
+ System.out.println(endAlgo()+"ms");
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java
index 514f9e4ccac8..d09d2d9b1b1f 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java
@@ -13,11 +13,7 @@ public class BoundaryFill {
* @param x_co_ordinate The x co-ordinate of which color is to be obtained
* @param y_co_ordinate The y co-ordinate of which color is to be obtained
*/
- public static int getPixel(
- int[][] image,
- int x_co_ordinate,
- int y_co_ordinate
- ) {
+ public static int getPixel(int[][] image, int x_co_ordinate, int y_co_ordinate) {
return image[x_co_ordinate][y_co_ordinate];
}
@@ -29,11 +25,7 @@ public static int getPixel(
* @param y_co_ordinate The y co-ordinate at which color is to be filled
*/
public static void putPixel(
- int[][] image,
- int x_co_ordinate,
- int y_co_ordinate,
- int new_color
- ) {
+ int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color) {
image[x_co_ordinate][y_co_ordinate] = new_color;
}
@@ -47,75 +39,19 @@ public static void putPixel(
* @param boundary_color The old color which is to be replaced in the image
*/
public static void boundaryFill(
- int[][] image,
- int x_co_ordinate,
- int y_co_ordinate,
- int new_color,
- int boundary_color
- ) {
- if (
- x_co_ordinate >= 0 &&
- y_co_ordinate >= 0 &&
- getPixel(image, x_co_ordinate, y_co_ordinate) != new_color &&
- getPixel(image, x_co_ordinate, y_co_ordinate) != boundary_color
- ) {
+ int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color, int boundary_color) {
+ if (x_co_ordinate >= 0 && y_co_ordinate >= 0
+ && getPixel(image, x_co_ordinate, y_co_ordinate) != new_color
+ && getPixel(image, x_co_ordinate, y_co_ordinate) != boundary_color) {
putPixel(image, x_co_ordinate, y_co_ordinate, new_color);
- boundaryFill(
- image,
- x_co_ordinate + 1,
- y_co_ordinate,
- new_color,
- boundary_color
- );
- boundaryFill(
- image,
- x_co_ordinate - 1,
- y_co_ordinate,
- new_color,
- boundary_color
- );
- boundaryFill(
- image,
- x_co_ordinate,
- y_co_ordinate + 1,
- new_color,
- boundary_color
- );
- boundaryFill(
- image,
- x_co_ordinate,
- y_co_ordinate - 1,
- new_color,
- boundary_color
- );
- boundaryFill(
- image,
- x_co_ordinate + 1,
- y_co_ordinate - 1,
- new_color,
- boundary_color
- );
- boundaryFill(
- image,
- x_co_ordinate - 1,
- y_co_ordinate + 1,
- new_color,
- boundary_color
- );
- boundaryFill(
- image,
- x_co_ordinate + 1,
- y_co_ordinate + 1,
- new_color,
- boundary_color
- );
- boundaryFill(
- image,
- x_co_ordinate - 1,
- y_co_ordinate - 1,
- new_color,
- boundary_color
- );
+ boundaryFill(image, x_co_ordinate + 1, y_co_ordinate, new_color, boundary_color);
+ boundaryFill(image, x_co_ordinate - 1, y_co_ordinate, new_color, boundary_color);
+ boundaryFill(image, x_co_ordinate, y_co_ordinate + 1, new_color, boundary_color);
+ boundaryFill(image, x_co_ordinate, y_co_ordinate - 1, new_color, boundary_color);
+ boundaryFill(image, x_co_ordinate + 1, y_co_ordinate - 1, new_color, boundary_color);
+ boundaryFill(image, x_co_ordinate - 1, y_co_ordinate + 1, new_color, boundary_color);
+ boundaryFill(image, x_co_ordinate + 1, y_co_ordinate + 1, new_color, boundary_color);
+ boundaryFill(image, x_co_ordinate - 1, y_co_ordinate - 1, new_color, boundary_color);
}
}
@@ -136,30 +72,30 @@ public static void printImageArray(int[][] image) {
// Driver Program
public static void main(String[] args) {
- //Input 2D image matrix
+ // Input 2D image matrix
int[][] image = {
- { 0, 0, 0, 0, 0, 0, 0 },
- { 0, 3, 3, 3, 3, 0, 0 },
- { 0, 3, 0, 0, 3, 0, 0 },
- { 0, 3, 0, 0, 3, 3, 3 },
- { 0, 3, 3, 3, 0, 0, 3 },
- { 0, 0, 0, 3, 0, 0, 3 },
- { 0, 0, 0, 3, 3, 3, 3 },
+ {0, 0, 0, 0, 0, 0, 0},
+ {0, 3, 3, 3, 3, 0, 0},
+ {0, 3, 0, 0, 3, 0, 0},
+ {0, 3, 0, 0, 3, 3, 3},
+ {0, 3, 3, 3, 0, 0, 3},
+ {0, 0, 0, 3, 0, 0, 3},
+ {0, 0, 0, 3, 3, 3, 3},
};
boundaryFill(image, 2, 2, 5, 3);
/* Output ==>
- * 0 0 0 0 0 0 0
- 0 3 3 3 3 0 0
- 0 3 5 5 3 0 0
- 0 3 5 5 3 3 3
- 0 3 3 3 5 5 3
- 0 0 0 3 5 5 3
+ * 0 0 0 0 0 0 0
+ 0 3 3 3 3 0 0
+ 0 3 5 5 3 0 0
+ 0 3 5 5 3 3 3
+ 0 3 3 3 5 5 3
+ 0 0 0 3 5 5 3
0 0 0 3 3 3 3
- * */
+ * */
- //print 2D image matrix
+ // print 2D image matrix
printImageArray(image);
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
index c6f555609a24..5b17a10105f4 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
@@ -22,16 +22,15 @@ static int knapSack(int W, int[] wt, int[] val, int n) {
// (1) nth item included
// (2) not included
else {
- return Math.max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),
- knapSack(W, wt, val, n - 1)
- );
+ return Math.max(
+ val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1));
}
}
// Driver code
public static void main(String[] args) {
- int[] val = new int[] { 60, 100, 120 };
- int[] wt = new int[] { 10, 20, 30 };
+ int[] val = new int[] {60, 100, 120};
+ int[] wt = new int[] {10, 20, 30};
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
index 9744f3c03c7e..5db7d39f1d99 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
@@ -47,9 +47,7 @@ static long findNthCatalan(int n) {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
- System.out.println(
- "Enter the number n to find nth Catalan number (n <= 50)"
- );
+ System.out.println("Enter the number n to find nth Catalan number (n <= 50)");
int n = sc.nextInt();
System.out.println(n + "th Catalan number is " + findNthCatalan(n));
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java b/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java
index 376a6532c102..58ba1351109c 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java
@@ -9,7 +9,7 @@ public class ClimbingStairs {
public static int numberOfWays(int n) {
- if(n == 1 || n == 0){
+ if (n == 1 || n == 0) {
return n;
}
int prev = 1;
@@ -17,14 +17,13 @@ public static int numberOfWays(int n) {
int next;
- for(int i = 2; i <= n; i++){
- next = curr+prev;
+ for (int i = 2; i <= n; i++) {
+ next = curr + prev;
prev = curr;
curr = next;
}
return curr;
-
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
index d7bd476f5071..7d74e2a8a5e5 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
@@ -8,20 +8,12 @@ public class CoinChange {
// Driver Program
public static void main(String[] args) {
int amount = 12;
- int[] coins = { 2, 4, 5 };
+ int[] coins = {2, 4, 5};
- System.out.println(
- "Number of combinations of getting change for " +
- amount +
- " is: " +
- change(coins, amount)
- );
- System.out.println(
- "Minimum number of coins required for amount :" +
- amount +
- " is: " +
- minimumCoins(coins, amount)
- );
+ System.out.println("Number of combinations of getting change for " + amount
+ + " is: " + change(coins, amount));
+ System.out.println("Minimum number of coins required for amount :" + amount
+ + " is: " + minimumCoins(coins, amount));
}
/**
@@ -67,10 +59,7 @@ public static int minimumCoins(int[] coins, int amount) {
for (int coin : coins) {
if (coin <= i) {
int sub_res = minimumCoins[i - coin];
- if (
- sub_res != Integer.MAX_VALUE &&
- sub_res + 1 < minimumCoins[i]
- ) {
+ if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i]) {
minimumCoins[i] = sub_res + 1;
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
index 75189b61d53f..e18725405394 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
@@ -1,8 +1,10 @@
-/** Author : Siddhant Swarup Mallick
+/**
+ * Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
/**
- * In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal to number of times n appears in the sequence.
+ * In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal
+ * to number of times n appears in the sequence.
*/
/**
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java b/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java
index 5744e4f84217..84f9cf6a83d8 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java
@@ -15,11 +15,12 @@ And it can be done using Dynamic Programming(DP).
// dice where every dice has 'm' faces
class DP {
- /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m faces. */
+ /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m
+ * faces. */
public static long findWays(int m, int n, int x) {
- /* Create a table to store the results of subproblems.
- One extra row and column are used for simplicity
- (Number of dice is directly used as row index and sum is directly used as column index).
+ /* Create a table to store the results of subproblems.
+ One extra row and column are used for simplicity
+ (Number of dice is directly used as row index and sum is directly used as column index).
The entries in 0th row and 0th column are never used. */
long[][] table = new long[n + 1][x + 1];
@@ -28,7 +29,7 @@ public static long findWays(int m, int n, int x) {
table[1][j] = 1;
}
- /* Fill rest of the entries in table using recursive relation
+ /* Fill rest of the entries in table using recursive relation
i: number of dice, j: sum */
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= x; j++) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java
index 3b501f669ade..042dff375acd 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java
@@ -27,8 +27,8 @@ static int knapSack(int W, int[] wt, int[] val, int n) {
// Driver code
public static void main(String[] args) {
- int[] val = new int[] { 60, 100, 120 };
- int[] wt = new int[] { 10, 20, 30 };
+ int[] val = new int[] {60, 100, 120};
+ int[] wt = new int[] {10, 20, 30};
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
index 5141e12db2a5..bba637294643 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
@@ -77,13 +77,7 @@ public static void main(String[] args) {
// ans stores the final Edit Distance between the two strings
int ans = minDistance(s1, s2);
System.out.println(
- "The minimum Edit Distance between \"" +
- s1 +
- "\" and \"" +
- s2 +
- "\" is " +
- ans
- );
+ "The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans);
input.close();
}
@@ -108,8 +102,7 @@ public static int editDistance(String s1, String s2, int[][] storage) {
return storage[m][n];
}
if (s1.charAt(0) == s2.charAt(0)) {
- storage[m][n] =
- editDistance(s1.substring(1), s2.substring(1), storage);
+ storage[m][n] = editDistance(s1.substring(1), s2.substring(1), storage);
} else {
int op1 = editDistance(s1, s2.substring(1), storage);
int op2 = editDistance(s1.substring(1), s2, storage);
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java b/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java
index eee6ab7878e4..ef1ff49465f3 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java
@@ -25,9 +25,7 @@ public static int minTrials(int n, int m) {
for (int j = 2; j <= m; j++) {
eggFloor[i][j] = Integer.MAX_VALUE;
for (x = 1; x <= j; x++) {
- result =
- 1 +
- Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);
+ result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]);
// choose min of all values for particular x
if (result < eggFloor[i][j]) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java
index 521bb2a9d1ba..5d250cd54e3f 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java
@@ -91,21 +91,22 @@ public static int fibOptimized(int n) {
res = next;
}
return res;
-}
-
+ }
+
/**
- * We have only defined the nth Fibonacci number in terms of the two before it. Now, we will look at Binet's formula to calculate the nth Fibonacci number in constant time.
- * The Fibonacci terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced ‘phi'.
- * First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2 = 1.6180339887...
- * Now, let's look at Binet's formula: Sn = Φⁿ–(– Φ⁻ⁿ)/√5
- * We first calculate the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get the required term.
- * Time Complexity will be O(1)
- */
-
+ * We have only defined the nth Fibonacci number in terms of the two before it. Now, we will
+ * look at Binet's formula to calculate the nth Fibonacci number in constant time. The Fibonacci
+ * terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced
+ * ‘phi'. First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2
+ * = 1.6180339887... Now, let's look at Binet's formula: Sn = Φⁿ–(– Φ⁻ⁿ)/√5 We first calculate
+ * the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get
+ * the required term. Time Complexity will be O(1)
+ */
+
public static int fibBinet(int n) {
double squareRootOf5 = Math.sqrt(5);
- double phi = (1 + squareRootOf5)/2;
- int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n))/squareRootOf5);
+ double phi = (1 + squareRootOf5) / 2;
+ int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n)) / squareRootOf5);
return nthTerm;
}
}
\ No newline at end of file
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java b/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java
index 1b9f1deea884..63ec477c4590 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java
@@ -26,9 +26,7 @@ public static void main(String[] args) {
capacity[3][4] = 15;
capacity[4][5] = 17;
- System.out.println(
- "Max capacity in networkFlow : " + networkFlow(0, 5)
- );
+ System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5));
}
private static int networkFlow(int source, int sink) {
@@ -46,10 +44,7 @@ private static int networkFlow(int source, int sink) {
int here = q.peek();
q.poll();
for (int there = 0; there < V; ++there) {
- if (
- capacity[here][there] - flow[here][there] > 0 &&
- parent.get(there) == -1
- ) {
+ if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) {
q.add(there);
parent.set(there, here);
}
@@ -63,11 +58,7 @@ private static int networkFlow(int source, int sink) {
String printer = "path : ";
StringBuilder sb = new StringBuilder();
for (int p = sink; p != source; p = parent.get(p)) {
- amount =
- Math.min(
- capacity[parent.get(p)][p] - flow[parent.get(p)][p],
- amount
- );
+ amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount);
sb.append(p + "-");
}
sb.append(source);
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
index 0c15e2febeb6..51cd6e50ea43 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
@@ -1,4 +1,5 @@
-/** Author : Siddhant Swarup Mallick
+/**
+ * Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
index 13296b8456a2..712a028ee960 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
@@ -5,8 +5,7 @@
*/
public class Knapsack {
- private static int knapSack(int W, int[] wt, int[] val, int n)
- throws IllegalArgumentException {
+ private static int knapSack(int W, int[] wt, int[] val, int n) throws IllegalArgumentException {
if (wt == null || val == null) {
throw new IllegalArgumentException();
}
@@ -19,11 +18,7 @@ private static int knapSack(int W, int[] wt, int[] val, int n)
if (i == 0 || w == 0) {
rv[i][w] = 0;
} else if (wt[i - 1] <= w) {
- rv[i][w] =
- Math.max(
- val[i - 1] + rv[i - 1][w - wt[i - 1]],
- rv[i - 1][w]
- );
+ rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]);
} else {
rv[i][w] = rv[i - 1][w];
}
@@ -35,8 +30,8 @@ private static int knapSack(int W, int[] wt, int[] val, int n)
// Driver program to test above function
public static void main(String[] args) {
- int[] val = new int[] { 50, 100, 130 };
- int[] wt = new int[] { 10, 20, 40 };
+ int[] val = new int[] {50, 100, 130};
+ int[] wt = new int[] {10, 20, 40};
int W = 50;
System.out.println(knapSack(W, wt, val, val.length));
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
index bcf1909d49d6..161a910bfe99 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
@@ -25,9 +25,8 @@ int knapSack(int capacity, int[] weights, int[] profits, int numOfItems) {
}
// Returns the value of maximum profit using recursive approach
- int solveKnapsackRecursive(int capacity, int[] weights,
- int[] profits, int numOfItems,
- int[][] dpTable) {
+ int solveKnapsackRecursive(
+ int capacity, int[] weights, int[] profits, int numOfItems, int[][] dpTable) {
// Base condition
if (numOfItems == 0 || capacity == 0) {
return 0;
@@ -39,11 +38,15 @@ int solveKnapsackRecursive(int capacity, int[] weights,
if (weights[numOfItems - 1] > capacity) {
// Store the value of function call stack in table
- dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
+ dpTable[numOfItems][capacity]
+ = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
return dpTable[numOfItems][capacity];
} else {
// Return value of table after storing
- return dpTable[numOfItems][capacity] = Math.max((profits[numOfItems - 1] + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, profits, numOfItems - 1, dpTable)),
+ return dpTable[numOfItems][capacity]
+ = Math.max((profits[numOfItems - 1]
+ + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights,
+ profits, numOfItems - 1, dpTable)),
solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable));
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
index f2a96187bc91..23222becff8f 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
@@ -32,12 +32,9 @@ public static int calculateLevenshteinDistance(String str1, String str2) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
distanceMat[i][j] = distanceMat[i - 1][j - 1];
} else {
- distanceMat[i][j] =
- 1 + minimum(
- distanceMat[i - 1][j],
- distanceMat[i - 1][j - 1],
- distanceMat[i][j - 1]
- );
+ distanceMat[i][j] = 1
+ + minimum(distanceMat[i - 1][j], distanceMat[i - 1][j - 1],
+ distanceMat[i][j - 1]);
}
}
}
@@ -48,9 +45,7 @@ public static void main(String[] args) {
String str1 = ""; // enter your string here
String str2 = ""; // enter your string here
- System.out.print(
- "Levenshtein distance between " + str1 + " and " + str2 + " is: "
- );
+ System.out.print("Levenshtein distance between " + str1 + " and " + str2 + " is: ");
System.out.println(calculateLevenshteinDistance(str1, str2));
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java
index bfa75a908441..5b508e036ae3 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java
@@ -2,12 +2,13 @@
/*
- * Problem Statement: -
+ * Problem Statement: -
* Find Longest Alternating Subsequence
- * A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following relations :
+ * A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following
+ relations :
- x1 < x2 > x3 < x4 > x5 < …. xn or
+ x1 < x2 > x3 < x4 > x5 < …. xn or
x1 > x2 < x3 > x4 < x5 > …. xn
*/
public class LongestAlternatingSubsequence {
@@ -16,16 +17,16 @@ public class LongestAlternatingSubsequence {
static int AlternatingLength(int[] arr, int n) {
/*
- las[i][0] = Length of the longest
- alternating subsequence ending at
- index i and last element is
- greater than its previous element
+ las[i][0] = Length of the longest
+ alternating subsequence ending at
+ index i and last element is
+ greater than its previous element
- las[i][1] = Length of the longest
- alternating subsequence ending at
- index i and last element is
- smaller than its previous
- element
+ las[i][1] = Length of the longest
+ alternating subsequence ending at
+ index i and last element is
+ smaller than its previous
+ element
*/
int[][] las = new int[n][2]; // las = LongestAlternatingSubsequence
@@ -61,12 +62,9 @@ static int AlternatingLength(int[] arr, int n) {
}
public static void main(String[] args) {
- int[] arr = { 10, 22, 9, 33, 49, 50, 31, 60 };
+ int[] arr = {10, 22, 9, 33, 49, 50, 31, 60};
int n = arr.length;
- System.out.println(
- "Length of Longest " +
- "alternating subsequence is " +
- AlternatingLength(arr, n)
- );
+ System.out.println("Length of Longest "
+ + "alternating subsequence is " + AlternatingLength(arr, n));
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
index a2711a810cf8..72fbc89397c0 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
@@ -37,11 +37,7 @@ public static String getLCS(String str1, String str2) {
return lcsString(str1, str2, lcsMatrix);
}
- public static String lcsString(
- String str1,
- String str2,
- int[][] lcsMatrix
- ) {
+ public static String lcsString(String str1, String str2, int[][] lcsMatrix) {
StringBuilder lcs = new StringBuilder();
int i = str1.length(), j = str2.length();
while (i > 0 && j > 0) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
index 373077e88e4c..e7a54f213ac1 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
@@ -56,8 +56,8 @@ else if (array[i] > tail[length - 1]) {
} // array[i] will become end candidate of an existing subsequence or
// Throw away larger elements in all LIS, to make room for upcoming grater elements than
// array[i]
- // (and also, array[i] would have already appeared in one of LIS, identify the location and
- // replace it)
+ // (and also, array[i] would have already appeared in one of LIS, identify the location
+ // and replace it)
else {
tail[upperBound(tail, -1, length - 1, array[i])] = array[i];
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java
index d3d7c36b2ef1..68fd6edbaeb5 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java
@@ -31,32 +31,21 @@ private static String recursiveLPS(String original, String reverse) {
bestResult = "";
} else {
// if the last chars match, then remove it from both strings and recur
- if (
- original.charAt(original.length() - 1) ==
- reverse.charAt(reverse.length() - 1)
- ) {
- String bestSubResult = recursiveLPS(
- original.substring(0, original.length() - 1),
- reverse.substring(0, reverse.length() - 1)
- );
+ if (original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) {
+ String bestSubResult = recursiveLPS(original.substring(0, original.length() - 1),
+ reverse.substring(0, reverse.length() - 1));
- bestResult =
- reverse.charAt(reverse.length() - 1) + bestSubResult;
+ bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult;
} else {
- // otherwise (1) ignore the last character of reverse, and recur on original and updated
- // reverse again
- // (2) ignore the last character of original and recur on the updated original and reverse
- // again
- // then select the best result from these two subproblems.
-
- String bestSubResult1 = recursiveLPS(
- original,
- reverse.substring(0, reverse.length() - 1)
- );
- String bestSubResult2 = recursiveLPS(
- original.substring(0, original.length() - 1),
- reverse
- );
+ // otherwise (1) ignore the last character of reverse, and recur on original and
+ // updated reverse again (2) ignore the last character of original and recur on the
+ // updated original and reverse again then select the best result from these two
+ // subproblems.
+
+ String bestSubResult1
+ = recursiveLPS(original, reverse.substring(0, reverse.length() - 1));
+ String bestSubResult2
+ = recursiveLPS(original.substring(0, original.length() - 1), reverse);
if (bestSubResult1.length() > bestSubResult2.length()) {
bestResult = bestSubResult1;
} else {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java
index a2a5427e55c9..f8de2d848294 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java
@@ -31,10 +31,7 @@ public static int getLongestValidParentheses(String s) {
int index = i - res[i - 1] - 1;
if (index >= 0 && chars[index] == '(') {
// ()(())
- res[i] =
- res[i - 1] +
- 2 +
- (index - 1 >= 0 ? res[index - 1] : 0);
+ res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0);
}
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java
index 7a3213558ef2..6dec5b418c50 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java
@@ -16,9 +16,7 @@ public class MatrixChainMultiplication {
public static void main(String[] args) {
int count = 1;
while (true) {
- String[] mSize = input(
- "input size of matrix A(" + count + ") ( ex. 10 20 ) : "
- );
+ String[] mSize = input("input size of matrix A(" + count + ") ( ex. 10 20 ) : ");
int col = Integer.parseInt(mSize[0]);
if (col == 0) {
break;
@@ -30,12 +28,7 @@ public static void main(String[] args) {
count++;
}
for (Matrix m : mArray) {
- System.out.format(
- "A(%d) = %2d x %2d%n",
- m.count(),
- m.col(),
- m.row()
- );
+ System.out.format("A(%d) = %2d x %2d%n", m.count(), m.col(), m.row());
}
size = mArray.size();
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java
index 0bcff7678bd4..b1bf31520d74 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java
@@ -28,10 +28,8 @@ static int Lookup_Chain(int[][] m, int[] p, int i, int j) {
return m[i][j];
} else {
for (int k = i; k < j; k++) {
- int q =
- Lookup_Chain(m, p, i, k) +
- Lookup_Chain(m, p, k + 1, j) +
- (p[i - 1] * p[k] * p[j]);
+ int q = Lookup_Chain(m, p, i, k) + Lookup_Chain(m, p, k + 1, j)
+ + (p[i - 1] * p[k] * p[j]);
if (q < m[i][j]) {
m[i][j] = q;
}
@@ -40,12 +38,10 @@ static int Lookup_Chain(int[][] m, int[] p, int i, int j) {
return m[i][j];
}
- // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 respectively
- // output should be Minimum number of multiplications is 38
+ // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5
+ // respectively output should be Minimum number of multiplications is 38
public static void main(String[] args) {
- int[] arr = { 1, 2, 3, 4, 5 };
- System.out.println(
- "Minimum number of multiplications is " + Memoized_Matrix_Chain(arr)
- );
+ int[] arr = {1, 2, 3, 4, 5};
+ System.out.println("Minimum number of multiplications is " + Memoized_Matrix_Chain(arr));
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java
index 22e77c047754..cd1f25a46664 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java
@@ -28,22 +28,22 @@ The Space Complexity of your algorithm should be smaller than or equal to O(mn).
public class MinimumPathSum {
public void testRegular() {
- int[][] grid = { { 1, 3, 1 }, { 1, 5, 1 }, { 4, 2, 1 } };
+ int[][] grid = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
System.out.println(minimumPathSum(grid));
}
public void testLessColumns() {
- int[][] grid = { { 1, 2 }, { 5, 6 }, { 1, 1 } };
+ int[][] grid = {{1, 2}, {5, 6}, {1, 1}};
System.out.println(minimumPathSum(grid));
}
public void testLessRows() {
- int[][] grid = { { 2, 3, 3 }, { 7, 2, 1 } };
+ int[][] grid = {{2, 3, 3}, {7, 2, 1}};
System.out.println(minimumPathSum(grid));
}
public void testOneRowOneColumn() {
- int[][] grid = { { 2 } };
+ int[][] grid = {{2}};
System.out.println(minimumPathSum(grid));
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java
index 78676c0085b4..c15c0186fc62 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java
@@ -82,8 +82,8 @@ public static int getMin(int[] arr, int sum) {
* Driver Code
*/
public static void main(String[] args) {
- assert subSet(new int[] { 1, 6, 11, 5 }) == 1;
- assert subSet(new int[] { 36, 7, 46, 40 }) == 23;
- assert subSet(new int[] { 1, 2, 3, 9 }) == 3;
+ assert subSet(new int[] {1, 6, 11, 5}) == 1;
+ assert subSet(new int[] {36, 7, 46, 40}) == 23;
+ assert subSet(new int[] {1, 2, 3, 9}) == 3;
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
index d41135b1f118..5aa0bf027c02 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
@@ -1,4 +1,5 @@
-/** Author : Siddhant Swarup Mallick
+/**
+ * Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
index 071880af5d9d..52ffaf191bae 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
@@ -22,9 +22,11 @@ public class OptimalJobScheduling {
* @param numberProcesses ,refers to the number of precedent processes(N)
* @param numberMachines ,refers to the number of different machines in our disposal(M)
* @param Run , N*M matrix refers to the cost of running each process to each machine
- * @param Transfer ,M*M symmetric matrix refers to the transportation delay for each pair of machines
+ * @param Transfer ,M*M symmetric matrix refers to the transportation delay for each pair of
+ * machines
*/
- public OptimalJobScheduling(int numberProcesses, int numberMachines, int[][] Run, int[][] Transfer) {
+ public OptimalJobScheduling(
+ int numberProcesses, int numberMachines, int[][] Run, int[][] Transfer) {
this.numberProcesses = numberProcesses;
this.numberMachines = numberMachines;
this.Run = Run;
@@ -35,7 +37,7 @@ public OptimalJobScheduling(int numberProcesses, int numberMachines, int[][] Run
/**
* Function which computes the cost of process scheduling to a number of VMs.
*/
- public void execute(){
+ public void execute() {
this.calculateCost();
this.showResults();
}
@@ -43,11 +45,11 @@ public void execute(){
/**
* Function which computes the cost of running each Process to each and every Machine
*/
- private void calculateCost(){
+ private void calculateCost() {
- for (int i=0; i < numberProcesses; i++){ //for each Process
+ for (int i = 0; i < numberProcesses; i++) { // for each Process
- for (int j=0; j < numberMachines; j++) { //for each Machine
+ for (int j = 0; j < numberMachines; j++) { // for each Machine
Cost[i][j] = runningCost(i, j);
}
@@ -55,10 +57,12 @@ private void calculateCost(){
}
/**
- * Function which returns the minimum cost of running a certain Process to a certain Machine.In order for the Machine to execute the Process ,he requires the output
- * of the previously executed Process, which may have been executed to the same Machine or some other.If the previous Process has been executed to another Machine,we
- * have to transfer her result, which means extra cost for transferring the data from one Machine to another(if the previous Process has been executed to the same
- * Machine, there is no transport cost).
+ * Function which returns the minimum cost of running a certain Process to a certain Machine.In
+ * order for the Machine to execute the Process ,he requires the output of the previously
+ * executed Process, which may have been executed to the same Machine or some other.If the
+ * previous Process has been executed to another Machine,we have to transfer her result, which
+ * means extra cost for transferring the data from one Machine to another(if the previous
+ * Process has been executed to the same Machine, there is no transport cost).
*
* @param process ,refers to the Process
* @param machine ,refers to the Machine
@@ -66,32 +70,38 @@ private void calculateCost(){
*/
private int runningCost(int process, int machine) {
- if (process==0) //refers to the first process,which does not require for a previous one to have been executed
+ if (process == 0) // refers to the first process,which does not require for a previous one
+ // to have been executed
return Run[process][machine];
else {
- int[] runningCosts = new int[numberMachines]; //stores the costs of executing our Process depending on the Machine the previous one was executed
+ int[] runningCosts
+ = new int[numberMachines]; // stores the costs of executing our Process depending on
+ // the Machine the previous one was executed
- for (int k=0; k < numberMachines; k++) //computes the cost of executing the previous process to each and every Machine
- runningCosts[k] = Cost[process-1][k] + Transfer[k][machine] + Run[process][machine]; //transferring the result to our Machine and executing the Process to our Machine
+ for (int k = 0; k < numberMachines; k++) // computes the cost of executing the previous
+ // process to each and every Machine
+ runningCosts[k] = Cost[process - 1][k] + Transfer[k][machine]
+ + Run[process][machine]; // transferring the result to our Machine and executing
+ // the Process to our Machine
- return findMin(runningCosts); //returns the minimum running cost
+ return findMin(runningCosts); // returns the minimum running cost
}
}
/**
* Function used in order to return the minimum Cost.
- * @param cost ,an Array of size M which refers to the costs of executing a Process to each Machine
+ * @param cost ,an Array of size M which refers to the costs of executing a Process to each
+ * Machine
* @return the minimum cost
*/
private int findMin(int[] cost) {
- int min=0;
+ int min = 0;
- for (int i=1;i {
* @param x x-coordinate
* @param y y-coordinate
*/
- public Point { }
-
- /**
- * @return the x-coordinate
- */
- @Override
- public int x() {
- return x;
- }
+ public Point {
+ }
- /**
- * @return the y-coordinate
- */
- @Override
- public int y() { return y; }
-
- /**
- * Finds the orientation of ordered triplet.
- *
- * @param a Co-ordinates of point a
- * @param b Co-ordinates of point a
- * @param c Co-ordinates of point a
- * @return { -1, 0, +1 } if a -→ b -→ c is a { clockwise, collinear; counterclockwise } turn.
- */
- public static int orientation(Point a, Point b, Point c) {
- int val = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
- if (val == 0) {
- return 0;
- }
- return (val > 0) ? +1 : -1;
- }
+ /**
+ * @return the x-coordinate
+ */
+ @Override
+ public int x() {
+ return x;
+ }
- /**
- * @param p2 Co-ordinate of point to compare to.
- * This function will compare the points and will return a positive integer it the
- * point is greater than the argument point and a negative integer if the point is
- * less than the argument point.
- */
- public int compareTo(Point p2) {
- if (this.y < p2.y) return -1;
- if (this.y > p2.y) return +1;
- if (this.x < p2.x) return -1;
- if (this.x > p2.x) return +1;
+ /**
+ * @return the y-coordinate
+ */
+ @Override
+ public int y() {
+ return y;
+ }
+
+ /**
+ * Finds the orientation of ordered triplet.
+ *
+ * @param a Co-ordinates of point a
+ * @param b Co-ordinates of point a
+ * @param c Co-ordinates of point a
+ * @return { -1, 0, +1 } if a -→ b -→ c is a { clockwise, collinear; counterclockwise }
+ * turn.
+ */
+ public static int orientation(Point a, Point b, Point c) {
+ int val = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
+ if (val == 0) {
return 0;
}
+ return (val > 0) ? +1 : -1;
+ }
- /**
- * A helper function that will let us sort points by their polar order
- * This function will compare the angle between 2 polar Co-ordinates
- *
- * @return the comparator
- */
- public Comparator polarOrder() {
- return new PolarOrder();
- }
+ /**
+ * @param p2 Co-ordinate of point to compare to.
+ * This function will compare the points and will return a positive integer it the
+ * point is greater than the argument point and a negative integer if the point is
+ * less than the argument point.
+ */
+ public int compareTo(Point p2) {
+ if (this.y < p2.y) return -1;
+ if (this.y > p2.y) return +1;
+ if (this.x < p2.x) return -1;
+ if (this.x > p2.x) return +1;
+ return 0;
+ }
- private class PolarOrder implements Comparator {
- public int compare(Point p1, Point p2) {
- int dx1 = p1.x - x;
- int dy1 = p1.y - y;
- int dx2 = p2.x - x;
- int dy2 = p2.y - y;
-
- if (dy1 >= 0 && dy2 < 0) return -1; // q1 above; q2 below
- else if (dy2 >= 0 && dy1 < 0) return +1; // q1 below; q2 above
- else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal
- if (dx1 >= 0 && dx2 < 0) return -1;
- else if (dx2 >= 0 && dx1 < 0) return +1;
- else return 0;
- } else return -orientation(Point.this, p1, p2); // both above or below
- }
- }
+ /**
+ * A helper function that will let us sort points by their polar order
+ * This function will compare the angle between 2 polar Co-ordinates
+ *
+ * @return the comparator
+ */
+ public Comparator polarOrder() {
+ return new PolarOrder();
+ }
- /**
- * Override of the toString method, necessary to compute the difference
- * between the expected result and the derived result
- *
- * @return a string representation of any given 2D point in the format (x, y)
- */
- @Override
- public String toString() {
- return "(" + x + ", " + y + ")";
+ private class PolarOrder implements Comparator {
+ public int compare(Point p1, Point p2) {
+ int dx1 = p1.x - x;
+ int dy1 = p1.y - y;
+ int dx2 = p2.x - x;
+ int dy2 = p2.y - y;
+
+ if (dy1 >= 0 && dy2 < 0)
+ return -1; // q1 above; q2 below
+ else if (dy2 >= 0 && dy1 < 0)
+ return +1; // q1 below; q2 above
+ else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal
+ if (dx1 >= 0 && dx2 < 0)
+ return -1;
+ else if (dx2 >= 0 && dx1 < 0)
+ return +1;
+ else
+ return 0;
+ } else
+ return -orientation(Point.this, p1, p2); // both above or below
}
}
+
+ /**
+ * Override of the toString method, necessary to compute the difference
+ * between the expected result and the derived result
+ *
+ * @return a string representation of any given 2D point in the format (x, y)
+ */
+ @Override
+ public String toString() {
+ return "(" + x + ", " + y + ")";
+ }
+ }
}
diff --git a/src/main/java/com/thealgorithms/io/BufferedReader.java b/src/main/java/com/thealgorithms/io/BufferedReader.java
index 1012ce79690f..8bd96cc9d132 100644
--- a/src/main/java/com/thealgorithms/io/BufferedReader.java
+++ b/src/main/java/com/thealgorithms/io/BufferedReader.java
@@ -13,181 +13,175 @@
*/
public class BufferedReader {
- private static final int DEFAULT_BUFFER_SIZE = 5;
-
- /**
- * Maximum number of bytes the buffer can hold.
- * Value is changed when encountered Eof to not
- * cause overflow read of 0 bytes
- */
-
- private int bufferSize;
- private final byte[] buffer;
-
- /**
- * posRead -> indicates the next byte to read
- */
- private int posRead = 0, bufferPos = 0;
-
- private boolean foundEof = false;
-
- private InputStream input;
-
- public BufferedReader(byte[] input) throws IOException {
- this(new ByteArrayInputStream(input));
- }
-
- public BufferedReader(InputStream input) throws IOException {
- this(input, DEFAULT_BUFFER_SIZE);
- }
-
- public BufferedReader(InputStream input, int bufferSize) throws IOException {
- this.input = input;
- if (input.available() == -1)
- throw new IOException("Empty or already closed stream provided");
-
- this.bufferSize = bufferSize;
- buffer = new byte[bufferSize];
- }
-
- /**
- * Reads a single byte from the stream
- */
- public int read() throws IOException {
- if (needsRefill()) {
- if (foundEof)
- return -1;
- // the buffer is empty, or the buffer has
- // been completely read and needs to be refilled
- refill();
+ private static final int DEFAULT_BUFFER_SIZE = 5;
+
+ /**
+ * Maximum number of bytes the buffer can hold.
+ * Value is changed when encountered Eof to not
+ * cause overflow read of 0 bytes
+ */
+
+ private int bufferSize;
+ private final byte[] buffer;
+
+ /**
+ * posRead -> indicates the next byte to read
+ */
+ private int posRead = 0, bufferPos = 0;
+
+ private boolean foundEof = false;
+
+ private InputStream input;
+
+ public BufferedReader(byte[] input) throws IOException {
+ this(new ByteArrayInputStream(input));
+ }
+
+ public BufferedReader(InputStream input) throws IOException {
+ this(input, DEFAULT_BUFFER_SIZE);
+ }
+
+ public BufferedReader(InputStream input, int bufferSize) throws IOException {
+ this.input = input;
+ if (input.available() == -1)
+ throw new IOException("Empty or already closed stream provided");
+
+ this.bufferSize = bufferSize;
+ buffer = new byte[bufferSize];
}
- return buffer[posRead++] & 0xff; // read and un-sign it
- }
-
- /**
- * Number of bytes not yet been read
- */
-
- public int available() throws IOException {
- int available = input.available();
- if (needsRefill())
- // since the block is already empty,
- // we have no responsibility yet
- return available;
- return bufferPos - posRead + available;
- }
-
- /**
- * Returns the next character
- */
-
- public int peek() throws IOException {
- return peek(1);
- }
-
- /**
- * Peeks and returns a value located at next {n}
- */
-
- public int peek(int n) throws IOException {
- int available = available();
- if (n >= available)
- throw new IOException("Out of range, available %d, but trying with %d"
- .formatted(available, n));
- pushRefreshData();
-
- if (n >= bufferSize)
- throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)"
- .formatted(n, bufferSize));
- return buffer[n];
- }
-
- /**
- * Removes the already read bytes from the buffer
- * in-order to make space for new bytes to be filled up.
- *
- * This may also do the job to read first time data (whole buffer is empty)
- */
-
- private void pushRefreshData() throws IOException {
- for (int i = posRead, j = 0; i < bufferSize; i++, j++)
- buffer[j] = buffer[i];
-
- bufferPos -= posRead;
- posRead = 0;
-
- // fill out the spaces that we've
- // emptied
- justRefill();
- }
-
- /**
- * Reads one complete block of size {bufferSize}
- * if found eof, the total length of array will
- * be that of what's available
- *
- * @return a completed block
- */
- public byte[] readBlock() throws IOException {
- pushRefreshData();
-
- byte[] cloned = new byte[bufferSize];
- // arraycopy() function is better than clone()
- if (bufferPos >= 0)
- System.arraycopy(buffer,
- 0,
- cloned,
- 0,
- // important to note that, bufferSize does not stay constant
- // once the class is defined. See justRefill() function
- bufferSize);
- // we assume that already a chunk
- // has been read
- refill();
- return cloned;
- }
-
- private boolean needsRefill() {
- return bufferPos == 0 || posRead == bufferSize;
- }
-
- private void refill() throws IOException {
- posRead = 0;
- bufferPos = 0;
- justRefill();
- }
-
- private void justRefill() throws IOException {
- assertStreamOpen();
-
- // try to fill in the maximum we can until
- // we reach EOF
- while (bufferPos < bufferSize) {
- int read = input.read();
- if (read == -1) {
- // reached end-of-file, no more data left
- // to be read
- foundEof = true;
- // rewrite the BUFFER_SIZE, to know that we've reached
- // EOF when requested refill
- bufferSize = bufferPos;
- }
- buffer[bufferPos++] = (byte) read;
+
+ /**
+ * Reads a single byte from the stream
+ */
+ public int read() throws IOException {
+ if (needsRefill()) {
+ if (foundEof) return -1;
+ // the buffer is empty, or the buffer has
+ // been completely read and needs to be refilled
+ refill();
+ }
+ return buffer[posRead++] & 0xff; // read and un-sign it
+ }
+
+ /**
+ * Number of bytes not yet been read
+ */
+
+ public int available() throws IOException {
+ int available = input.available();
+ if (needsRefill())
+ // since the block is already empty,
+ // we have no responsibility yet
+ return available;
+ return bufferPos - posRead + available;
}
- }
-
- private void assertStreamOpen() {
- if (input == null)
- throw new IllegalStateException("Input Stream already closed!");
- }
-
- public void close() throws IOException {
- if (input != null) {
- try {
- input.close();
- } finally {
- input = null;
- }
+
+ /**
+ * Returns the next character
+ */
+
+ public int peek() throws IOException {
+ return peek(1);
+ }
+
+ /**
+ * Peeks and returns a value located at next {n}
+ */
+
+ public int peek(int n) throws IOException {
+ int available = available();
+ if (n >= available)
+ throw new IOException(
+ "Out of range, available %d, but trying with %d".formatted(available, n));
+ pushRefreshData();
+
+ if (n >= bufferSize)
+ throw new IllegalAccessError(
+ "Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize));
+ return buffer[n];
+ }
+
+ /**
+ * Removes the already read bytes from the buffer
+ * in-order to make space for new bytes to be filled up.
+ *
+ * This may also do the job to read first time data (whole buffer is empty)
+ */
+
+ private void pushRefreshData() throws IOException {
+ for (int i = posRead, j = 0; i < bufferSize; i++, j++) buffer[j] = buffer[i];
+
+ bufferPos -= posRead;
+ posRead = 0;
+
+ // fill out the spaces that we've
+ // emptied
+ justRefill();
+ }
+
+ /**
+ * Reads one complete block of size {bufferSize}
+ * if found eof, the total length of array will
+ * be that of what's available
+ *
+ * @return a completed block
+ */
+ public byte[] readBlock() throws IOException {
+ pushRefreshData();
+
+ byte[] cloned = new byte[bufferSize];
+ // arraycopy() function is better than clone()
+ if (bufferPos >= 0)
+ System.arraycopy(buffer, 0, cloned, 0,
+ // important to note that, bufferSize does not stay constant
+ // once the class is defined. See justRefill() function
+ bufferSize);
+ // we assume that already a chunk
+ // has been read
+ refill();
+ return cloned;
+ }
+
+ private boolean needsRefill() {
+ return bufferPos == 0 || posRead == bufferSize;
+ }
+
+ private void refill() throws IOException {
+ posRead = 0;
+ bufferPos = 0;
+ justRefill();
+ }
+
+ private void justRefill() throws IOException {
+ assertStreamOpen();
+
+ // try to fill in the maximum we can until
+ // we reach EOF
+ while (bufferPos < bufferSize) {
+ int read = input.read();
+ if (read == -1) {
+ // reached end-of-file, no more data left
+ // to be read
+ foundEof = true;
+ // rewrite the BUFFER_SIZE, to know that we've reached
+ // EOF when requested refill
+ bufferSize = bufferPos;
+ }
+ buffer[bufferPos++] = (byte) read;
+ }
+ }
+
+ private void assertStreamOpen() {
+ if (input == null) throw new IllegalStateException("Input Stream already closed!");
+ }
+
+ public void close() throws IOException {
+ if (input != null) {
+ try {
+ input.close();
+ } finally {
+ input = null;
+ }
+ }
}
- }
}
diff --git a/src/main/java/com/thealgorithms/maths/ADTFraction.java b/src/main/java/com/thealgorithms/maths/ADTFraction.java
index d0eaddfaacf5..1ffd3d67d384 100644
--- a/src/main/java/com/thealgorithms/maths/ADTFraction.java
+++ b/src/main/java/com/thealgorithms/maths/ADTFraction.java
@@ -21,11 +21,8 @@ public record ADTFraction(int numerator, int denominator) {
* @return A new {@code ADTFraction} containing the result of the operation
*/
public ADTFraction plus(ADTFraction fraction) {
- var numerator =
- this.denominator *
- fraction.numerator +
- this.numerator *
- fraction.denominator;
+ var numerator
+ = this.denominator * fraction.numerator + this.numerator * fraction.denominator;
var denominator = this.denominator * fraction.denominator;
return new ADTFraction(numerator, denominator);
}
@@ -64,7 +61,8 @@ public ADTFraction reciprocal() {
/**
* Calculates the result of the fraction.
*
- * @return The numerical result of the division between {@code numerator} and {@code denominator}
+ * @return The numerical result of the division between {@code numerator} and {@code
+ * denominator}
*/
public float value() {
return (float) this.numerator / this.denominator;
diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java
index d5b278481aee..a8796ae40324 100644
--- a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java
+++ b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java
@@ -15,12 +15,9 @@ public static int getMinValue(int... numbers) {
throw new IllegalArgumentException("Numbers array cannot be empty");
}
- var absMinWrapper = new Object() {
- int value = numbers[0];
- };
+ var absMinWrapper = new Object() { int value = numbers[0]; };
- Arrays
- .stream(numbers)
+ Arrays.stream(numbers)
.skip(1)
.filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value))
.forEach(number -> absMinWrapper.value = number);
diff --git a/src/main/java/com/thealgorithms/maths/AliquotSum.java b/src/main/java/com/thealgorithms/maths/AliquotSum.java
index 6eb18f260db9..b9c7d3819da2 100644
--- a/src/main/java/com/thealgorithms/maths/AliquotSum.java
+++ b/src/main/java/com/thealgorithms/maths/AliquotSum.java
@@ -18,28 +18,24 @@ public class AliquotSum {
* @return aliquot sum of given {@code number}
*/
public static int getAliquotValue(int number) {
- var sumWrapper = new Object() {
- int value = 0;
- };
+ var sumWrapper = new Object() { int value = 0; };
- IntStream
- .iterate(1, i -> ++i)
+ IntStream.iterate(1, i -> ++i)
.limit(number / 2)
.filter(i -> number % i == 0)
.forEach(i -> sumWrapper.value += i);
return sumWrapper.value;
}
-
- /**
+
+ /**
* Function to calculate the aliquot sum of an integer number
*
* @param n a positive integer
* @return aliquot sum of given {@code number}
*/
public static int getAliquotSum(int n) {
- if (n <= 0)
- return -1;
+ if (n <= 0) return -1;
int sum = 1;
double root = Math.sqrt(n);
/*
@@ -56,9 +52,9 @@ public static int getAliquotSum(int n) {
sum += i + n / i;
}
}
- // if n is a perfect square then its root was added twice in above loop, so subtracting root from sum
- if (root == (int) root)
- sum -= root;
+ // if n is a perfect square then its root was added twice in above loop, so subtracting root
+ // from sum
+ if (root == (int) root) sum -= root;
return sum;
}
}
diff --git a/src/main/java/com/thealgorithms/maths/AmicableNumber.java b/src/main/java/com/thealgorithms/maths/AmicableNumber.java
index 3efea0e16f4f..f52470833e65 100644
--- a/src/main/java/com/thealgorithms/maths/AmicableNumber.java
+++ b/src/main/java/com/thealgorithms/maths/AmicableNumber.java
@@ -21,9 +21,8 @@ public class AmicableNumber {
public static void main(String[] args) {
AmicableNumber.findAllInRange(1, 3000);
- /* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284) 2: = ( 1184,1210)
- 3: = ( 2620,2924) So it worked */
-
+ /* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284)
+ 2: = ( 1184,1210) 3: = ( 2620,2924) So it worked */
}
/**
@@ -32,8 +31,9 @@ public static void main(String[] args) {
* @return
*/
static void findAllInRange(int startValue, int stopValue) {
- /* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200) is the same calculation
- * also to avoid is to check the number with it self. a number with itself is always a AmicableNumber
+ /* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200)
+ * is the same calculation also to avoid is to check the number with it self. a number with
+ * itself is always a AmicableNumber
* */
StringBuilder res = new StringBuilder();
int countofRes = 0;
@@ -42,22 +42,14 @@ static void findAllInRange(int startValue, int stopValue) {
for (int j = i + 1; j <= stopValue; j++) {
if (isAmicableNumber(i, j)) {
countofRes++;
- res.append(
- "" + countofRes + ": = ( " + i + "," + j + ")" + "\t"
- );
+ res.append("" + countofRes + ": = ( " + i + "," + j + ")"
+ + "\t");
}
}
}
- res.insert(
- 0,
- "Int Range of " +
- startValue +
- " till " +
- stopValue +
- " there are " +
- countofRes +
- " Amicable_numbers.These are \n "
- );
+ res.insert(0,
+ "Int Range of " + startValue + " till " + stopValue + " there are " + countofRes
+ + " Amicable_numbers.These are \n ");
System.out.println(res);
}
@@ -69,12 +61,8 @@ static void findAllInRange(int startValue, int stopValue) {
* otherwise false
*/
static boolean isAmicableNumber(int numberOne, int numberTwo) {
- return (
- (
- recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo &&
- numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)
- )
- );
+ return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo
+ && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
}
/**
diff --git a/src/main/java/com/thealgorithms/maths/Area.java b/src/main/java/com/thealgorithms/maths/Area.java
index 262669fe8087..b4bae5ae9a13 100644
--- a/src/main/java/com/thealgorithms/maths/Area.java
+++ b/src/main/java/com/thealgorithms/maths/Area.java
@@ -135,7 +135,8 @@ public static double surfaceAreaParallelogram(final double base, final double he
* @param height height of trapezium
* @return area of given trapezium
*/
- public static double surfaceAreaTrapezium(final double base1, final double base2, final double height) {
+ public static double surfaceAreaTrapezium(
+ final double base1, final double base2, final double height) {
if (base1 <= 0) {
throw new IllegalArgumentException(POSITIVE_BASE + 1);
}
diff --git a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
index 3ea898cc4a7f..55c4864f0e00 100644
--- a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
+++ b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
@@ -20,15 +20,15 @@ public class AutomorphicNumber {
* {@code false}
*/
public static boolean isAutomorphic(long n) {
- if (n < 0)
- return false;
+ if (n < 0) return false;
long square = n * n; // Calculating square of the number
long t = n, numberOfdigits = 0;
while (t > 0) {
numberOfdigits++; // Calculating number of digits in n
t /= 10;
}
- long lastDigits = square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square
+ long lastDigits
+ = square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square
return n == lastDigits;
}
@@ -40,8 +40,7 @@ public static boolean isAutomorphic(long n) {
* {@code false}
*/
public static boolean isAutomorphic2(long n) {
- if (n < 0)
- return false;
+ if (n < 0) return false;
long square = n * n; // Calculating square of the number
return String.valueOf(square).endsWith(String.valueOf(n));
}
@@ -55,8 +54,7 @@ public static boolean isAutomorphic2(long n) {
*/
public static boolean isAutomorphic3(String s) {
BigInteger n = new BigInteger(s);
- if (n.signum() == -1)
- return false; //if number is negative, return false
+ if (n.signum() == -1) return false; // if number is negative, return false
BigInteger square = n.multiply(n); // Calculating square of the number
return String.valueOf(square).endsWith(String.valueOf(n));
}
diff --git a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java
index 18f0d12b67f8..5e7271a6137e 100644
--- a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java
+++ b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java
@@ -17,13 +17,11 @@ public class BinomialCoefficient {
*
* @param totalObjects Total number of objects
* @param numberOfObjects Number of objects to be chosen from total_objects
- * @return number of ways in which no_of_objects objects can be chosen from total_objects objects
+ * @return number of ways in which no_of_objects objects can be chosen from total_objects
+ * objects
*/
- public static int binomialCoefficient(
- int totalObjects,
- int numberOfObjects
- ) {
+ public static int binomialCoefficient(int totalObjects, int numberOfObjects) {
// Base Case
if (numberOfObjects > totalObjects) {
return 0;
@@ -35,9 +33,7 @@ public static int binomialCoefficient(
}
// Recursive Call
- return (
- binomialCoefficient(totalObjects - 1, numberOfObjects - 1) +
- binomialCoefficient(totalObjects - 1, numberOfObjects)
- );
+ return (binomialCoefficient(totalObjects - 1, numberOfObjects - 1)
+ + binomialCoefficient(totalObjects - 1, numberOfObjects));
}
}
diff --git a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java
index 693fbbe9b38a..b66499b349b7 100644
--- a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java
+++ b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java
@@ -39,14 +39,14 @@ private static void padding(ArrayList x, int newSize) {
* @return The convolved signal.
*/
public static ArrayList fftCircularConvolution(
- ArrayList a,
- ArrayList b
- ) {
- int convolvedSize = Math.max(a.size(), b.size()); // The two signals must have the same size equal to the bigger one
+ ArrayList a, ArrayList b) {
+ int convolvedSize = Math.max(
+ a.size(), b.size()); // The two signals must have the same size equal to the bigger one
padding(a, convolvedSize); // Zero padding the smaller signal
padding(b, convolvedSize);
- /* Find the FFTs of both signal. Here we use the Bluestein algorithm because we want the FFT to have the same length with the signal and not bigger */
+ /* Find the FFTs of both signal. Here we use the Bluestein algorithm because we want the FFT
+ * to have the same length with the signal and not bigger */
FFTBluestein.fftBluestein(a, false);
FFTBluestein.fftBluestein(b, false);
ArrayList convolved = new ArrayList<>();
diff --git a/src/main/java/com/thealgorithms/maths/Convolution.java b/src/main/java/com/thealgorithms/maths/Convolution.java
index 8a89d31ad3c5..cafb36f7a2b1 100644
--- a/src/main/java/com/thealgorithms/maths/Convolution.java
+++ b/src/main/java/com/thealgorithms/maths/Convolution.java
@@ -27,8 +27,9 @@ public static double[] convolution(double[] A, double[] B) {
C[i] = Σ (A[k]*B[i-k])
k=0
- It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <= B.length - 1
- From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get the conditions below.
+ It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <=
+ B.length - 1 From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get
+ the conditions below.
*/
for (int i = 0; i < convolved.length; i++) {
convolved[i] = 0;
diff --git a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java
index c5f48815de46..cacde4b886ba 100644
--- a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java
+++ b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java
@@ -43,14 +43,13 @@ private static void padding(ArrayList x, int newSize) {
* @return The convolved signal.
*/
public static ArrayList convolutionFFT(
- ArrayList a,
- ArrayList b
- ) {
+ ArrayList a, ArrayList b) {
int convolvedSize = a.size() + b.size() - 1; // The size of the convolved signal
padding(a, convolvedSize); // Zero padding both signals
padding(b, convolvedSize);
- /* Find the FFTs of both signals (Note that the size of the FFTs will be bigger than the convolvedSize because of the extra zero padding in FFT algorithm) */
+ /* Find the FFTs of both signals (Note that the size of the FFTs will be bigger than the
+ * convolvedSize because of the extra zero padding in FFT algorithm) */
FFT.fft(a, false);
FFT.fft(b, false);
ArrayList convolved = new ArrayList<>();
@@ -59,7 +58,9 @@ public static ArrayList convolutionFFT(
convolved.add(a.get(i).multiply(b.get(i))); // FFT(a)*FFT(b)
}
FFT.fft(convolved, true); // IFFT
- convolved.subList(convolvedSize, convolved.size()).clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came from
+ convolved.subList(convolvedSize, convolved.size())
+ .clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came
+ // from
// paddingPowerOfTwo() method inside the fft() method.
return convolved;
diff --git a/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java b/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java
index 388bf396975b..c1ef3fc09e1d 100644
--- a/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java
+++ b/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java
@@ -37,10 +37,10 @@ static int determinant(int[][] a, int n) {
return det;
}
- //Driver Method
+ // Driver Method
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
- //Input Matrix
+ // Input Matrix
System.out.println("Enter matrix size (Square matrix only)");
int n = in.nextInt();
System.out.println("Enter matrix");
diff --git a/src/main/java/com/thealgorithms/maths/DigitalRoot.java b/src/main/java/com/thealgorithms/maths/DigitalRoot.java
index 6a3541f3454d..78066f404739 100644
--- a/src/main/java/com/thealgorithms/maths/DigitalRoot.java
+++ b/src/main/java/com/thealgorithms/maths/DigitalRoot.java
@@ -1,7 +1,9 @@
-/** Author : Suraj Kumar Modi
+/**
+ * Author : Suraj Kumar Modi
* https://github.com/skmodi649
*/
-/** You are given a number n. You need to find the digital root of n.
+/**
+ * You are given a number n. You need to find the digital root of n.
* DigitalRoot of a number is the recursive sum of its digits until we get a single digit number.
*
* Test Case 1:
@@ -19,7 +21,8 @@
* sum of digit of 45 is 9 which is a single
* digit number.
*/
-/** Algorithm :
+/**
+ * Algorithm :
* Step 1 : Define a method digitalRoot(int n)
* Step 2 : Define another method single(int n)
* Step 3 : digitalRoot(int n) method takes output of single(int n) as input
@@ -32,14 +35,16 @@
* return n;
* else
* return (n%10) + (n/10)
- * Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and print the result
+ * Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and
+ * print the result
*/
package com.thealgorithms.maths;
class DigitalRoot {
public static int digitalRoot(int n) {
- if (single(n) <= 9) { // If n is already single digit than simply call single method and return the value
+ if (single(n) <= 9) { // If n is already single digit than simply call single method and
+ // return the value
return single(n);
} else {
return digitalRoot(single(n));
@@ -55,7 +60,6 @@ public static int single(int n) {
}
} // n / 10 is the number obtainded after removing the digit one by one
// Sum of digits is stored in the Stack memory and then finally returned
-
}
/**
* Time Complexity : O((Number of Digits)^2) Auxiliary Space Complexity :
diff --git a/src/main/java/com/thealgorithms/maths/DistanceFormula.java b/src/main/java/com/thealgorithms/maths/DistanceFormula.java
index 89f9b4298077..9a2654dbeedb 100644
--- a/src/main/java/com/thealgorithms/maths/DistanceFormula.java
+++ b/src/main/java/com/thealgorithms/maths/DistanceFormula.java
@@ -2,23 +2,13 @@
public class DistanceFormula {
- public static double euclideanDistance(
- double x1,
- double y1,
- double x2,
- double y2
- ) {
+ public static double euclideanDistance(double x1, double y1, double x2, double y2) {
double dX = Math.pow(x2 - x1, 2);
double dY = Math.pow(y2 - x1, 2);
return Math.sqrt(dX + dY);
}
- public static double manhattanDistance(
- double x1,
- double y1,
- double x2,
- double y2
- ) {
+ public static double manhattanDistance(double x1, double y1, double x2, double y2) {
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
diff --git a/src/main/java/com/thealgorithms/maths/DudeneyNumber.java b/src/main/java/com/thealgorithms/maths/DudeneyNumber.java
index ab9fb70b1cf0..72c2065e2121 100644
--- a/src/main/java/com/thealgorithms/maths/DudeneyNumber.java
+++ b/src/main/java/com/thealgorithms/maths/DudeneyNumber.java
@@ -10,7 +10,7 @@
public class DudeneyNumber {
- //returns True if the number is a Dudeney number and False if it is not a Dudeney number.
+ // returns True if the number is a Dudeney number and False if it is not a Dudeney number.
public static boolean isDudeney(int n) {
// Calculating Cube Root
int cube_root = (int) (Math.round((Math.pow(n, 1.0 / 3.0))));
@@ -19,7 +19,7 @@ public static boolean isDudeney(int n) {
return false;
}
int sum_of_digits = 0; // Stores the sums of the digit of the entered number
- int temp = n; //A temporary variable to store the entered number
+ int temp = n; // A temporary variable to store the entered number
// Loop to calculate sum of the digits.
while (temp > 0) {
// Extracting Last digit of the number
@@ -32,7 +32,7 @@ public static boolean isDudeney(int n) {
temp /= 10;
}
- //If the cube root of the number is not equal to the sum of its digits we return false.
+ // If the cube root of the number is not equal to the sum of its digits we return false.
return cube_root == sum_of_digits;
}
}
diff --git a/src/main/java/com/thealgorithms/maths/EulerMethod.java b/src/main/java/com/thealgorithms/maths/EulerMethod.java
index eca4007656be..a5c5cf8de20b 100644
--- a/src/main/java/com/thealgorithms/maths/EulerMethod.java
+++ b/src/main/java/com/thealgorithms/maths/EulerMethod.java
@@ -37,15 +37,8 @@ public static void main(String[] args) {
// example from https://www.geeksforgeeks.org/euler-method-solving-differential-equation/
System.out.println("\n\nexample 3:");
- BiFunction exampleEquation3 = (x, y) ->
- x + y + x * y;
- ArrayList points3 = eulerFull(
- 0,
- 0.1,
- 0.025,
- 1,
- exampleEquation3
- );
+ BiFunction exampleEquation3 = (x, y) -> x + y + x * y;
+ ArrayList points3 = eulerFull(0, 0.1, 0.025, 1, exampleEquation3);
assert points3.get(points3.size() - 1)[1] == 1.1116729841674804;
points3.forEach(point -> System.out.printf("x: %1$f; y: %2$f%n", point[0], point[1]));
}
@@ -60,16 +53,10 @@ public static void main(String[] args) {
* @param differentialEquation The differential equation to be solved.
* @return The next y-value.
*/
- public static double eulerStep(
- double xCurrent,
- double stepSize,
- double yCurrent,
- BiFunction differentialEquation
- ) {
+ public static double eulerStep(double xCurrent, double stepSize, double yCurrent,
+ BiFunction differentialEquation) {
if (stepSize <= 0) {
- throw new IllegalArgumentException(
- "stepSize should be greater than zero"
- );
+ throw new IllegalArgumentException("stepSize should be greater than zero");
}
return yCurrent + stepSize * differentialEquation.apply(xCurrent, yCurrent);
}
@@ -86,36 +73,26 @@ public static double eulerStep(
* @return The points constituting the solution of the differential
* equation.
*/
- public static ArrayList eulerFull(
- double xStart,
- double xEnd,
- double stepSize,
- double yStart,
- BiFunction differentialEquation
- ) {
+ public static ArrayList eulerFull(double xStart, double xEnd, double stepSize,
+ double yStart, BiFunction differentialEquation) {
if (xStart >= xEnd) {
- throw new IllegalArgumentException(
- "xEnd should be greater than xStart"
- );
+ throw new IllegalArgumentException("xEnd should be greater than xStart");
}
if (stepSize <= 0) {
- throw new IllegalArgumentException(
- "stepSize should be greater than zero"
- );
+ throw new IllegalArgumentException("stepSize should be greater than zero");
}
ArrayList points = new ArrayList();
- double[] firstPoint = { xStart, yStart };
+ double[] firstPoint = {xStart, yStart};
points.add(firstPoint);
double yCurrent = yStart;
double xCurrent = xStart;
while (xCurrent < xEnd) {
// Euler method for next step
- yCurrent =
- eulerStep(xCurrent, stepSize, yCurrent, differentialEquation);
+ yCurrent = eulerStep(xCurrent, stepSize, yCurrent, differentialEquation);
xCurrent += stepSize;
- double[] point = { xCurrent, yCurrent };
+ double[] point = {xCurrent, yCurrent};
points.add(point);
}
diff --git a/src/main/java/com/thealgorithms/maths/FFT.java b/src/main/java/com/thealgorithms/maths/FFT.java
index 998d0668f5fe..f50bec52997b 100644
--- a/src/main/java/com/thealgorithms/maths/FFT.java
+++ b/src/main/java/com/thealgorithms/maths/FFT.java
@@ -180,10 +180,7 @@ public Complex divide(double n) {
* @param inverse True if you want to find the inverse FFT.
* @return
*/
- public static ArrayList fft(
- ArrayList x,
- boolean inverse
- ) {
+ public static ArrayList fft(ArrayList x, boolean inverse) {
/* Pad the signal with zeros if necessary */
paddingPowerOfTwo(x);
int N = x.size();
@@ -220,11 +217,7 @@ public static int findLog2(int N) {
}
/* Swap the values of the signal with bit-reversal method */
- public static ArrayList fftBitReversal(
- int N,
- int log2N,
- ArrayList x
- ) {
+ public static ArrayList fftBitReversal(int N, int log2N, ArrayList x) {
int reverse;
for (int i = 0; i < N; i++) {
reverse = reverseBits(i, log2N);
@@ -236,11 +229,7 @@ public static ArrayList fftBitReversal(
}
/* Divide by N if we want the inverse FFT */
- public static ArrayList inverseFFT(
- int N,
- boolean inverse,
- ArrayList x
- ) {
+ public static ArrayList inverseFFT(int N, boolean inverse, ArrayList x) {
if (inverse) {
for (int i = 0; i < x.size(); i++) {
Complex z = x.get(i);
diff --git a/src/main/java/com/thealgorithms/maths/FFTBluestein.java b/src/main/java/com/thealgorithms/maths/FFTBluestein.java
index ffd42bd57198..cd698b62570a 100644
--- a/src/main/java/com/thealgorithms/maths/FFTBluestein.java
+++ b/src/main/java/com/thealgorithms/maths/FFTBluestein.java
@@ -30,7 +30,8 @@ public static void fftBluestein(ArrayList x, boolean inverse) {
ArrayList an = new ArrayList<>();
ArrayList bn = new ArrayList<>();
- /* Initialization of the b(n) sequence (see Wikipedia's article above for the symbols used)*/
+ /* Initialization of the b(n) sequence (see Wikipedia's article above for the symbols
+ * used)*/
for (int i = 0; i < bnSize; i++) {
bn.add(new FFT.Complex());
}
@@ -38,26 +39,16 @@ public static void fftBluestein(ArrayList x, boolean inverse) {
for (int i = 0; i < N; i++) {
double angle = (i - N + 1) * (i - N + 1) * Math.PI / N * direction;
bn.set(i, new FFT.Complex(Math.cos(angle), Math.sin(angle)));
- bn.set(
- bnSize - i - 1,
- new FFT.Complex(Math.cos(angle), Math.sin(angle))
- );
+ bn.set(bnSize - i - 1, new FFT.Complex(Math.cos(angle), Math.sin(angle)));
}
/* Initialization of the a(n) sequence */
for (int i = 0; i < N; i++) {
double angle = -i * i * Math.PI / N * direction;
- an.add(
- x
- .get(i)
- .multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle)))
- );
+ an.add(x.get(i).multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle))));
}
- ArrayList convolution = ConvolutionFFT.convolutionFFT(
- an,
- bn
- );
+ ArrayList convolution = ConvolutionFFT.convolutionFFT(an, bn);
/* The final multiplication of the convolution with the b*(k) factor */
for (int i = 0; i < N; i++) {
diff --git a/src/main/java/com/thealgorithms/maths/Factorial.java b/src/main/java/com/thealgorithms/maths/Factorial.java
index 4c31e69d78b3..90fcde543a4d 100644
--- a/src/main/java/com/thealgorithms/maths/Factorial.java
+++ b/src/main/java/com/thealgorithms/maths/Factorial.java
@@ -21,7 +21,8 @@ public static long factorial(int n) {
throw new IllegalArgumentException("number is negative");
}
long factorial = 1;
- for (int i = 1; i <= n; factorial *= i, ++i);
+ for (int i = 1; i <= n; factorial *= i, ++i)
+ ;
return factorial;
}
}
diff --git a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
index 1e30374e57f0..886337478d01 100644
--- a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
+++ b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
@@ -1,4 +1,5 @@
-/** Author : Siddhant Swarup Mallick
+/**
+ * Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
@@ -22,7 +23,8 @@ public static boolean inverseSqrt(float number) {
/**
* Returns the inverse square root of the given number upto 6 - 8 decimal places.
- * calculates the inverse square root of the given number and returns true if calculated answer matches with given answer else returns false
+ * calculates the inverse square root of the given number and returns true if calculated answer
+ * matches with given answer else returns false
*/
public static boolean inverseSqrt(double number) {
@@ -39,17 +41,16 @@ public static boolean inverseSqrt(double number) {
}
/**
* Returns the inverse square root of the given number upto 14 - 16 decimal places.
- * calculates the inverse square root of the given number and returns true if calculated answer matches with given answer else returns false
+ * calculates the inverse square root of the given number and returns true if calculated answer
+ * matches with given answer else returns false
*/
}
/**
* OUTPUT :
* Input - number = 4522
- * Output: it calculates the inverse squareroot of a number and returns true with it matches the given answer else returns false.
- * 1st approach Time Complexity : O(1)
- * Auxiliary Space Complexity : O(1)
- * Input - number = 4522
- * Output: it calculates the inverse squareroot of a number and returns true with it matches the given answer else returns false.
- * 2nd approach Time Complexity : O(1)
+ * Output: it calculates the inverse squareroot of a number and returns true with it matches the
+ * given answer else returns false. 1st approach Time Complexity : O(1) Auxiliary Space Complexity :
+ * O(1) Input - number = 4522 Output: it calculates the inverse squareroot of a number and returns
+ * true with it matches the given answer else returns false. 2nd approach Time Complexity : O(1)
* Auxiliary Space Complexity : O(1)
*/
diff --git a/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java b/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java
index b6a39adf0517..72e89f0993be 100644
--- a/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java
+++ b/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java
@@ -25,31 +25,24 @@ public static Optional