- * E.g. num = 13 = 00001101 in binary log2N = 8 Then reversed = 176 =
+ * E.g. num = 13 = 00001101 in binary log2n = 8 Then reversed = 176 =
* 10110000 in binary
*
*
@@ -255,14 +255,14 @@ public static ArrayList inverseFFT(int N, boolean inverse, ArrayList x, boolean inverse) {
- int N = x.size();
- int bnSize = 2 * N - 1;
+ int n = x.size();
+ int bnSize = 2 * n - 1;
int direction = inverse ? -1 : 1;
ArrayList an = new ArrayList<>();
ArrayList bn = new ArrayList<>();
@@ -38,32 +38,32 @@ public static void fftBluestein(ArrayList x, boolean inverse) {
bn.add(new FFT.Complex());
}
- for (int i = 0; i < N; i++) {
- double angle = (i - N + 1) * (i - N + 1) * Math.PI / N * direction;
+ 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)));
}
/* Initialization of the a(n) sequence */
- for (int i = 0; i < N; i++) {
- double angle = -i * i * Math.PI / N * direction;
+ 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))));
}
ArrayList convolution = ConvolutionFFT.convolutionFFT(an, bn);
/* The final multiplication of the convolution with the b*(k) factor */
- for (int i = 0; i < N; i++) {
- double angle = -1 * i * i * Math.PI / N * direction;
+ for (int i = 0; i < n; i++) {
+ double angle = -1 * i * i * Math.PI / n * direction;
FFT.Complex bk = new FFT.Complex(Math.cos(angle), Math.sin(angle));
- x.set(i, bk.multiply(convolution.get(i + N - 1)));
+ x.set(i, bk.multiply(convolution.get(i + n - 1)));
}
- /* Divide by N if we want the inverse FFT */
+ /* Divide by n if we want the inverse FFT */
if (inverse) {
- for (int i = 0; i < N; i++) {
+ for (int i = 0; i < n; i++) {
FFT.Complex z = x.get(i);
- x.set(i, z.divide(N));
+ x.set(i, z.divide(n));
}
}
}
diff --git a/src/main/java/com/thealgorithms/maths/KeithNumber.java b/src/main/java/com/thealgorithms/maths/KeithNumber.java
index c2d64dcad493..1756cfbae91b 100644
--- a/src/main/java/com/thealgorithms/maths/KeithNumber.java
+++ b/src/main/java/com/thealgorithms/maths/KeithNumber.java
@@ -26,24 +26,24 @@ static boolean isKeith(int x) {
}
// reverse the List
Collections.reverse(terms);
- int next_term = 0;
+ int nextTerm = 0;
int i = n;
// finds next term for the series
// loop executes until the condition returns true
- while (next_term < x) {
- next_term = 0;
+ while (nextTerm < x) {
+ nextTerm = 0;
// next term is the sum of previous n terms (it depends on number of digits the number
// has)
for (int j = 1; j <= n; j++) {
- next_term = next_term + terms.get(i - j);
+ nextTerm = nextTerm + terms.get(i - j);
}
- terms.add(next_term);
+ terms.add(nextTerm);
i++;
}
// when the control comes out of the while loop, there will be two conditions:
- // either next_term will be equal to x or greater than x
+ // either nextTerm will be equal to x or greater than x
// if equal, the given number is Keith, else not
- return (next_term == x);
+ return (nextTerm == x);
}
// driver code
diff --git a/src/main/java/com/thealgorithms/maths/LongDivision.java b/src/main/java/com/thealgorithms/maths/LongDivision.java
index 2191bf840a9b..45e97b1c14c3 100644
--- a/src/main/java/com/thealgorithms/maths/LongDivision.java
+++ b/src/main/java/com/thealgorithms/maths/LongDivision.java
@@ -12,59 +12,59 @@ public final class LongDivision {
private LongDivision() {
}
public static int divide(int dividend, int divisor) {
- long new_dividend_1 = dividend;
- long new_divisor_1 = divisor;
+ long newDividend1 = dividend;
+ long newDivisor1 = divisor;
if (divisor == 0) {
return 0;
}
if (dividend < 0) {
- new_dividend_1 = new_dividend_1 * -1;
+ newDividend1 = newDividend1 * -1;
}
if (divisor < 0) {
- new_divisor_1 = new_divisor_1 * -1;
+ newDivisor1 = newDivisor1 * -1;
}
- if (dividend == 0 || new_dividend_1 < new_divisor_1) {
+ if (dividend == 0 || newDividend1 < newDivisor1) {
return 0;
}
StringBuilder answer = new StringBuilder();
- String dividend_string = "" + new_dividend_1;
- int last_index = 0;
+ String dividendString = "" + newDividend1;
+ int lastIndex = 0;
String remainder = "";
- for (int i = 0; i < dividend_string.length(); i++) {
- String part_v1 = remainder + "" + dividend_string.substring(last_index, i + 1);
- long part_1 = Long.parseLong(part_v1);
- if (part_1 > new_divisor_1) {
+ for (int i = 0; i < dividendString.length(); i++) {
+ String partV1 = remainder + "" + dividendString.substring(lastIndex, i + 1);
+ long part1 = Long.parseLong(partV1);
+ if (part1 > newDivisor1) {
int quotient = 0;
- while (part_1 >= new_divisor_1) {
- part_1 = part_1 - new_divisor_1;
+ while (part1 >= newDivisor1) {
+ part1 = part1 - newDivisor1;
quotient++;
}
answer.append(quotient);
- } else if (part_1 == new_divisor_1) {
+ } else if (part1 == newDivisor1) {
int quotient = 0;
- while (part_1 >= new_divisor_1) {
- part_1 = part_1 - new_divisor_1;
+ while (part1 >= newDivisor1) {
+ part1 = part1 - newDivisor1;
quotient++;
}
answer.append(quotient);
- } else if (part_1 == 0) {
+ } else if (part1 == 0) {
answer.append(0);
- } else if (part_1 < new_divisor_1) {
+ } else if (part1 < newDivisor1) {
answer.append(0);
}
- if (!(part_1 == 0)) {
- remainder = String.valueOf(part_1);
+ if (!(part1 == 0)) {
+ remainder = String.valueOf(part1);
} else {
remainder = "";
}
- last_index++;
+ lastIndex++;
}
if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) {
diff --git a/src/main/java/com/thealgorithms/maths/MagicSquare.java b/src/main/java/com/thealgorithms/maths/MagicSquare.java
index 7e0ff4da6da7..de0afc148982 100644
--- a/src/main/java/com/thealgorithms/maths/MagicSquare.java
+++ b/src/main/java/com/thealgorithms/maths/MagicSquare.java
@@ -18,32 +18,32 @@ public static void main(String[] args) {
System.exit(0);
}
- int[][] magic_square = new int[num][num];
+ int[][] magicSquare = new int[num][num];
- int row_num = num / 2;
- int col_num = num - 1;
- magic_square[row_num][col_num] = 1;
+ int rowNum = num / 2;
+ int colNum = num - 1;
+ magicSquare[rowNum][colNum] = 1;
for (int i = 2; i <= num * num; i++) {
- if (magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == 0) {
- row_num = (row_num - 1 + num) % num;
- col_num = (col_num + 1) % num;
+ if (magicSquare[(rowNum - 1 + num) % num][(colNum + 1) % num] == 0) {
+ rowNum = (rowNum - 1 + num) % num;
+ colNum = (colNum + 1) % num;
} else {
- col_num = (col_num - 1 + num) % num;
+ colNum = (colNum - 1 + num) % num;
}
- magic_square[row_num][col_num] = i;
+ magicSquare[rowNum][colNum] = i;
}
// print the square
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
- if (magic_square[i][j] < 10) {
+ if (magicSquare[i][j] < 10) {
System.out.print(" ");
}
- if (magic_square[i][j] < 100) {
+ if (magicSquare[i][j] < 100) {
System.out.print(" ");
}
- System.out.print(magic_square[i][j] + " ");
+ System.out.print(magicSquare[i][j] + " ");
}
System.out.println();
}
diff --git a/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java b/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java
index ef02c5759c03..79bc112902c4 100644
--- a/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java
+++ b/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java
@@ -19,19 +19,19 @@ public static void main(String[] args) {
SimpsonIntegration integration = new SimpsonIntegration();
// Give random data for the example purposes
- int N = 16;
+ int n = 16;
double a = 1;
double b = 3;
- // Check so that N is even
- if (N % 2 != 0) {
- System.out.println("N must be even number for Simpsons method. Aborted");
+ // Check so that n is even
+ if (n % 2 != 0) {
+ System.out.println("n must be even number for Simpsons method. Aborted");
System.exit(1);
}
// Calculate step h and evaluate the integral
- double h = (b - a) / (double) N;
- double integralEvaluation = integration.simpsonsMethod(N, h, a);
+ double h = (b - a) / (double) n;
+ double integralEvaluation = integration.simpsonsMethod(n, h, a);
System.out.println("The integral is equal to: " + integralEvaluation);
}
@@ -45,13 +45,13 @@ public static void main(String[] args) {
*
* @return result of the integral evaluation
*/
- public double simpsonsMethod(int N, double h, double a) {
+ public double simpsonsMethod(int n, double h, double a) {
TreeMap data = new TreeMap<>(); // Key: i, Value: f(xi)
double temp;
double xi = a; // Initialize the variable xi = x0 + 0*h
// Create the table of xi and yi points
- for (int i = 0; i <= N; i++) {
+ for (int i = 0; i <= n; i++) {
temp = f(xi); // Get the value of the function at that point
data.put(i, temp);
xi += h; // Increase the xi to the next point
diff --git a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java
index 8a1bb1488eab..8b93702b9514 100644
--- a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java
+++ b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java
@@ -111,15 +111,15 @@ public static void main(String[] args) {
static void test() {
// Create two vectors
- VectorCrossProduct A = new VectorCrossProduct(1, -2, 3);
- VectorCrossProduct B = new VectorCrossProduct(2, 0, 3);
+ VectorCrossProduct a = new VectorCrossProduct(1, -2, 3);
+ VectorCrossProduct b = new VectorCrossProduct(2, 0, 3);
// Determine cross product
- VectorCrossProduct crossProd = A.crossProduct(B);
+ VectorCrossProduct crossProd = a.crossProduct(b);
crossProd.displayVector();
// Determine dot product
- int dotProd = A.dotProduct(B);
- System.out.println("Dot Product of A and B: " + dotProd);
+ int dotProd = a.dotProduct(b);
+ System.out.println("Dot Product of a and b: " + dotProd);
}
}
diff --git a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java
index a78bbbf34278..15093549871b 100644
--- a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java
+++ b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java
@@ -21,27 +21,27 @@ public static void main(String[] args) {
// To insert a new element(we are creating a new array)
System.out.println("Enter the index at which the element should be inserted");
- int insert_pos = s.nextInt();
+ int insertPos = s.nextInt();
System.out.println("Enter the element to be inserted");
int ins = s.nextInt();
int size2 = size + 1;
int[] b = new int[size2];
for (i = 0; i < size2; i++) {
- if (i <= insert_pos) {
+ if (i <= insertPos) {
b[i] = a[i];
} else {
b[i] = a[i - 1];
}
}
- b[insert_pos] = ins;
+ b[insertPos] = ins;
for (i = 0; i < size2; i++) {
System.out.println(b[i]);
}
// To delete an element given the index
System.out.println("Enter the index at which element is to be deleted");
- int del_pos = s.nextInt();
- for (i = del_pos; i < size2 - 1; i++) {
+ int delPos = s.nextInt();
+ for (i = delPos; i < size2 - 1; i++) {
b[i] = b[i + 1];
}
for (i = 0; i < size2 - 1; i++) {
diff --git a/src/main/java/com/thealgorithms/others/PageRank.java b/src/main/java/com/thealgorithms/others/PageRank.java
index 960034fdb701..c7be7a9882bc 100644
--- a/src/main/java/com/thealgorithms/others/PageRank.java
+++ b/src/main/java/com/thealgorithms/others/PageRank.java
@@ -28,20 +28,20 @@ public static void main(String[] args) {
public double[] pagerank = new double[10];
public void calc(double totalNodes) {
- double InitialPageRank;
- double OutgoingLinks = 0;
- double DampingFactor = 0.85;
- double[] TempPageRank = new double[10];
- int ExternalNodeNumber;
- int InternalNodeNumber;
+ double initialPageRank;
+ double outgoingLinks = 0;
+ double dampingFactor = 0.85;
+ double[] tempPageRank = new double[10];
+ int externalNodeNumber;
+ int internalNodeNumber;
int k = 1; // For Traversing
- int ITERATION_STEP = 1;
- InitialPageRank = 1 / totalNodes;
- System.out.printf(" Total Number of Nodes :" + totalNodes + "\t Initial PageRank of All Nodes :" + InitialPageRank + "\n");
+ int iterationStep = 1;
+ initialPageRank = 1 / totalNodes;
+ System.out.printf(" Total Number of Nodes :" + totalNodes + "\t Initial PageRank of All Nodes :" + initialPageRank + "\n");
// 0th ITERATION _ OR _ INITIALIZATION PHASE //
for (k = 1; k <= totalNodes; k++) {
- this.pagerank[k] = InitialPageRank;
+ this.pagerank[k] = initialPageRank;
}
System.out.print("\n Initial PageRank Values , 0th Step \n");
@@ -49,40 +49,40 @@ public void calc(double totalNodes) {
System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n");
}
- while (ITERATION_STEP <= 2) { // Iterations
+ while (iterationStep <= 2) { // Iterations
// Store the PageRank for All Nodes in Temporary Array
for (k = 1; k <= totalNodes; k++) {
- TempPageRank[k] = this.pagerank[k];
+ tempPageRank[k] = this.pagerank[k];
this.pagerank[k] = 0;
}
- for (InternalNodeNumber = 1; InternalNodeNumber <= totalNodes; InternalNodeNumber++) {
- for (ExternalNodeNumber = 1; ExternalNodeNumber <= totalNodes; ExternalNodeNumber++) {
- if (this.path[ExternalNodeNumber][InternalNodeNumber] == 1) {
+ for (internalNodeNumber = 1; internalNodeNumber <= totalNodes; internalNodeNumber++) {
+ for (externalNodeNumber = 1; externalNodeNumber <= totalNodes; externalNodeNumber++) {
+ if (this.path[externalNodeNumber][internalNodeNumber] == 1) {
k = 1;
- OutgoingLinks = 0; // Count the Number of Outgoing Links for each ExternalNodeNumber
+ outgoingLinks = 0; // Count the Number of Outgoing Links for each externalNodeNumber
while (k <= totalNodes) {
- if (this.path[ExternalNodeNumber][k] == 1) {
- OutgoingLinks = OutgoingLinks + 1; // Counter for Outgoing Links
+ if (this.path[externalNodeNumber][k] == 1) {
+ outgoingLinks = outgoingLinks + 1; // Counter for Outgoing Links
}
k = k + 1;
}
// Calculate PageRank
- this.pagerank[InternalNodeNumber] += TempPageRank[ExternalNodeNumber] * (1 / OutgoingLinks);
+ this.pagerank[internalNodeNumber] += tempPageRank[externalNodeNumber] * (1 / outgoingLinks);
}
}
- System.out.printf("\n After " + ITERATION_STEP + "th Step \n");
+ System.out.printf("\n After " + iterationStep + "th Step \n");
for (k = 1; k <= totalNodes; k++) {
System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n");
}
- ITERATION_STEP = ITERATION_STEP + 1;
+ iterationStep = iterationStep + 1;
}
// Add the Damping Factor to PageRank
for (k = 1; k <= totalNodes; k++) {
- this.pagerank[k] = (1 - DampingFactor) + DampingFactor * this.pagerank[k];
+ this.pagerank[k] = (1 - dampingFactor) + dampingFactor * this.pagerank[k];
}
// Display PageRank
diff --git a/src/main/java/com/thealgorithms/others/ReturnSubsequence.java b/src/main/java/com/thealgorithms/others/ReturnSubsequence.java
index cf2f091a102f..81bd051ca365 100644
--- a/src/main/java/com/thealgorithms/others/ReturnSubsequence.java
+++ b/src/main/java/com/thealgorithms/others/ReturnSubsequence.java
@@ -30,18 +30,18 @@ private static String[] returnSubsequence(String givenString) {
ans[0] = "";
return ans;
}
- String[] SmallAns = returnSubsequence(givenString.substring(1)); // recursive call to get subsequences of substring starting from index
+ String[] smallAns = returnSubsequence(givenString.substring(1)); // recursive call to get subsequences of substring starting from index
// position=1
- String[] ans = new String[2 * SmallAns.length]; // Our answer will be an array off string of size=2*SmallAns
+ String[] ans = new String[2 * smallAns.length]; // Our answer will be an array off string of size=2*smallAns
int i = 0;
- for (; i < SmallAns.length; i++) {
- ans[i] = SmallAns[i]; // Copying all the strings present in SmallAns to ans string array
+ for (; i < smallAns.length; i++) {
+ ans[i] = smallAns[i]; // Copying all the strings present in smallAns to ans string array
}
- for (int k = 0; k < SmallAns.length; k++) {
- ans[k + SmallAns.length] = givenString.charAt(0) + SmallAns[k]; // Insert character at index=0 of the given
+ for (int k = 0; k < smallAns.length; k++) {
+ ans[k + smallAns.length] = givenString.charAt(0) + smallAns[k]; // Insert character at index=0 of the given
// substring in front of every string
- // in SmallAns
+ // in smallAns
}
return ans;
}
diff --git a/src/main/java/com/thealgorithms/others/RootPrecision.java b/src/main/java/com/thealgorithms/others/RootPrecision.java
index a804f8f69db4..bc195ffca5ae 100644
--- a/src/main/java/com/thealgorithms/others/RootPrecision.java
+++ b/src/main/java/com/thealgorithms/others/RootPrecision.java
@@ -10,27 +10,27 @@ public static void main(String[] args) {
// take input
Scanner scn = new Scanner(System.in);
- // N is the input number
- int N = scn.nextInt();
+ // n is the input number
+ int n = scn.nextInt();
- // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870.
- int P = scn.nextInt();
- System.out.println(squareRoot(N, P));
+ // p is precision value for eg - p is 3 in 2.564 and 5 in 3.80870.
+ int p = scn.nextInt();
+ System.out.println(squareRoot(n, p));
scn.close();
}
- public static double squareRoot(int N, int P) {
+ public static double squareRoot(int n, int p) {
// rv means return value
double rv;
- double root = Math.pow(N, 0.5);
+ double root = Math.pow(n, 0.5);
// calculate precision to power of 10 and then multiply it with root value.
- int precision = (int) Math.pow(10, P);
+ int precision = (int) Math.pow(10, p);
root = root * precision;
/*typecast it into integer then divide by precision and again typecast into double
- so as to have decimal points upto P precision */
+ so as to have decimal points upto p precision */
rv = (int) root;
return rv / precision;
diff --git a/src/main/java/com/thealgorithms/others/Sudoku.java b/src/main/java/com/thealgorithms/others/Sudoku.java
index d27a1648b743..0839a376c5de 100644
--- a/src/main/java/com/thealgorithms/others/Sudoku.java
+++ b/src/main/java/com/thealgorithms/others/Sudoku.java
@@ -86,16 +86,16 @@ public static boolean solveSudoku(int[][] board, int n) {
return false;
}
- public static void print(int[][] board, int N) {
+ public static void print(int[][] board, int n) {
// We got the answer, just print it
- for (int r = 0; r < N; r++) {
- for (int d = 0; d < N; d++) {
+ for (int r = 0; r < n; r++) {
+ for (int d = 0; d < n; d++) {
System.out.print(board[r][d]);
System.out.print(" ");
}
System.out.print("\n");
- if ((r + 1) % (int) Math.sqrt(N) == 0) {
+ if ((r + 1) % (int) Math.sqrt(n) == 0) {
System.out.print("");
}
}
@@ -114,11 +114,11 @@ public static void main(String[] args) {
{0, 0, 0, 0, 0, 0, 0, 7, 4},
{0, 0, 5, 2, 0, 6, 3, 0, 0},
};
- int N = board.length;
+ int n = board.length;
- if (solveSudoku(board, N)) {
+ if (solveSudoku(board, n)) {
// print solution
- print(board, N);
+ print(board, n);
} else {
System.out.println("No solution");
}
diff --git a/src/main/java/com/thealgorithms/searches/KMPSearch.java b/src/main/java/com/thealgorithms/searches/KMPSearch.java
index 38a4c74dee31..3648a4b08b86 100644
--- a/src/main/java/com/thealgorithms/searches/KMPSearch.java
+++ b/src/main/java/com/thealgorithms/searches/KMPSearch.java
@@ -3,25 +3,25 @@
class KMPSearch {
int kmpSearch(String pat, String txt) {
- int M = pat.length();
- int N = txt.length();
+ int m = pat.length();
+ int n = txt.length();
// create lps[] that will hold the longest
// prefix suffix values for pattern
- int[] lps = new int[M];
+ int[] lps = new int[m];
int j = 0; // index for pat[]
// Preprocess the pattern (calculate lps[]
// array)
- computeLPSArray(pat, M, lps);
+ computeLPSArray(pat, m, lps);
int i = 0; // index for txt[]
- while ((N - i) >= (M - j)) {
+ while ((n - i) >= (m - j)) {
if (pat.charAt(j) == txt.charAt(i)) {
j++;
i++;
}
- if (j == M) {
+ if (j == m) {
System.out.println("Found pattern "
+ "at index " + (i - j));
int index = (i - j);
@@ -29,7 +29,7 @@ int kmpSearch(String pat, String txt) {
return index;
}
// mismatch after j matches
- else if (i < N && pat.charAt(j) != txt.charAt(i)) {
+ else if (i < n && pat.charAt(j) != txt.charAt(i)) {
// Do not match lps[0..lps[j-1]] characters,
// they will match anyway
if (j != 0)
@@ -42,14 +42,14 @@ else if (i < N && pat.charAt(j) != txt.charAt(i)) {
return -1;
}
- void computeLPSArray(String pat, int M, int[] lps) {
+ void computeLPSArray(String pat, int m, int[] lps) {
// length of the previous longest prefix suffix
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0
- // the loop calculates lps[i] for i = 1 to M-1
- while (i < M) {
+ // the loop calculates lps[i] for i = 1 to m-1
+ while (i < m) {
if (pat.charAt(i) == pat.charAt(len)) {
len++;
lps[i] = len;
diff --git a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
index 8fb3f4f68986..cdd256150871 100644
--- a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
@@ -18,7 +18,7 @@ private OrderAgnosticBinarySearch() {
static int binSearchAlgo(int[] arr, int start, int end, int target) {
// Checking whether the given array is ascending order
- boolean AscOrd = arr[start] < arr[end];
+ boolean ascOrd = arr[start] < arr[end];
while (start <= end) {
int middle = start + (end - start) / 2;
@@ -27,7 +27,7 @@ static int binSearchAlgo(int[] arr, int start, int end, int target) {
if (arr[middle] == target) return middle; // returns the index of the middle element
// Ascending order
- if (AscOrd) {
+ if (ascOrd) {
if (arr[middle] < target)
start = middle + 1;
else
diff --git a/src/main/java/com/thealgorithms/sorts/DNFSort.java b/src/main/java/com/thealgorithms/sorts/DNFSort.java
index 6e89bb65ad32..50ba8c89715b 100644
--- a/src/main/java/com/thealgorithms/sorts/DNFSort.java
+++ b/src/main/java/com/thealgorithms/sorts/DNFSort.java
@@ -6,9 +6,9 @@ private DNFSort() {
// Sort the input array, the array is assumed to
// have values in {0, 1, 2}
- static void sort012(int[] a, int arr_size) {
+ static void sort012(int[] a, int arrSize) {
int low = 0;
- int high = arr_size - 1;
+ int high = arrSize - 1;
int mid = 0;
int temp;
while (mid <= high) {
@@ -38,8 +38,8 @@ static void sort012(int[] a, int arr_size) {
}
/* Utility function to print array arr[] */
- static void printArray(int[] arr, int arr_size) {
- for (int i = 0; i < arr_size; i++) {
+ static void printArray(int[] arr, int arrSize) {
+ for (int i = 0; i < arrSize; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
@@ -48,9 +48,9 @@ static void printArray(int[] arr, int arr_size) {
/*Driver function to check for above functions*/
public static void main(String[] args) {
int[] arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
- int arr_size = arr.length;
- sort012(arr, arr_size);
+ int arrSize = arr.length;
+ sort012(arr, arrSize);
System.out.println("Array after seggregation ");
- printArray(arr, arr_size);
+ printArray(arr, arrSize);
}
}
diff --git a/src/main/java/com/thealgorithms/sorts/SwapSort.java b/src/main/java/com/thealgorithms/sorts/SwapSort.java
index b10728b6a5c3..08ce988578f3 100644
--- a/src/main/java/com/thealgorithms/sorts/SwapSort.java
+++ b/src/main/java/com/thealgorithms/sorts/SwapSort.java
@@ -11,10 +11,10 @@ public class SwapSort implements SortAlgorithm {
@Override
public > T[] sort(T[] array) {
- int LENGTH = array.length;
+ int len = array.length;
int index = 0;
- while (index < LENGTH - 1) {
+ while (index < len - 1) {
int amountSmallerElements = this.getSmallerElementCount(array, index);
if (amountSmallerElements > 0 && index != amountSmallerElements) {
diff --git a/src/main/java/com/thealgorithms/strings/MyAtoi.java b/src/main/java/com/thealgorithms/strings/MyAtoi.java
index 119d75e4d828..0aed13f936a7 100644
--- a/src/main/java/com/thealgorithms/strings/MyAtoi.java
+++ b/src/main/java/com/thealgorithms/strings/MyAtoi.java
@@ -8,13 +8,13 @@ private MyAtoi() {
}
public static int myAtoi(String s) {
s = s.trim();
- char[] char_1 = s.toCharArray();
+ char[] char1 = s.toCharArray();
String number = "";
boolean negative = false;
boolean zero = false;
boolean isDigit = false;
- for (char ch : char_1) {
+ for (char ch : char1) {
if (Character.isDigit(ch)) {
if (number.length() > 1 && !isDigit) {
number = "0";
diff --git a/src/main/java/com/thealgorithms/strings/WordLadder.java b/src/main/java/com/thealgorithms/strings/WordLadder.java
index 025c43b15466..16d4e0a02452 100644
--- a/src/main/java/com/thealgorithms/strings/WordLadder.java
+++ b/src/main/java/com/thealgorithms/strings/WordLadder.java
@@ -67,24 +67,24 @@ public static int ladderLength(String beginWord, String endWord, List wo
int size = queue.size();
for (int i = 0; i < size; i++) {
String curr = queue.poll();
- char[] words_chars = curr.toCharArray();
- for (int j = 0; j < words_chars.length; j++) {
- char original_chars = words_chars[j];
+ char[] wordsChars = curr.toCharArray();
+ for (int j = 0; j < wordsChars.length; j++) {
+ char originalChars = wordsChars[j];
for (char c = 'a'; c <= 'z'; c++) {
- if (words_chars[j] == c) {
+ if (wordsChars[j] == c) {
continue;
}
- words_chars[j] = c;
- String new_word = String.valueOf(words_chars);
- if (new_word.equals(endWord)) {
+ wordsChars[j] = c;
+ String newWord = String.valueOf(wordsChars);
+ if (newWord.equals(endWord)) {
return level + 1;
}
- if (set.contains(new_word)) {
- set.remove(new_word);
- queue.offer(new_word);
+ if (set.contains(newWord)) {
+ set.remove(newWord);
+ queue.offer(newWord);
}
}
- words_chars[j] = original_chars;
+ wordsChars[j] = originalChars;
}
}
level++;
diff --git a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java
index 1af529f89459..2dfcf3909b8f 100644
--- a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java
+++ b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java
@@ -13,20 +13,20 @@ public static String encode(String s, int numRows) {
char[] zigZagedArray = new char[s.length()];
while (depth != 0) {
int pointer = start;
- int height_space = 2 + ((height - 2) * 2);
- int depth_space = 2 + ((depth - 2) * 2);
+ int heightSpace = 2 + ((height - 2) * 2);
+ int depthSpace = 2 + ((depth - 2) * 2);
boolean bool = true;
while (pointer < s.length()) {
zigZagedArray[index++] = s.charAt(pointer);
- if (height_space == 0)
- pointer += depth_space;
- else if (depth_space == 0)
- pointer += height_space;
+ if (heightSpace == 0)
+ pointer += depthSpace;
+ else if (depthSpace == 0)
+ pointer += heightSpace;
else if (bool) {
- pointer += depth_space;
+ pointer += depthSpace;
bool = false;
} else {
- pointer += height_space;
+ pointer += heightSpace;
bool = true;
}
}
diff --git a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java
index ada3c23f4c65..17a1d2374d66 100644
--- a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java
+++ b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java
@@ -13,28 +13,29 @@ class StrassenMatrixMultiplicationTest {
@Test
public void strassenMatrixMultiplicationTest2x2() {
- int[][] A = {{1, 2}, {3, 4}};
- int[][] B = {{5, 6}, {7, 8}};
+ int[][] a = {{1, 2}, {3, 4}};
+ int[][] b = {{5, 6}, {7, 8}};
int[][] expResult = {{19, 22}, {43, 50}};
- int[][] actResult = SMM.multiply(A, B);
+ int[][] actResult = SMM.multiply(a, b);
assertArrayEquals(expResult, actResult);
}
@Test
void strassenMatrixMultiplicationTest4x4() {
- int[][] A = {{1, 2, 5, 4}, {9, 3, 0, 6}, {4, 6, 3, 1}, {0, 2, 0, 6}};
- int[][] B = {{1, 0, 4, 1}, {1, 2, 0, 2}, {0, 3, 1, 3}, {1, 8, 1, 2}};
+ int[][] a = {{1, 2, 5, 4}, {9, 3, 0, 6}, {4, 6, 3, 1}, {0, 2, 0, 6}};
+ int[][] b = {{1, 0, 4, 1}, {1, 2, 0, 2}, {0, 3, 1, 3}, {1, 8, 1, 2}};
int[][] expResult = {{7, 51, 13, 28}, {18, 54, 42, 27}, {11, 29, 20, 27}, {8, 52, 6, 16}};
- int[][] actResult = SMM.multiply(A, B);
+ int[][] actResult = SMM.multiply(a, b);
assertArrayEquals(expResult, actResult);
}
@Test
- void strassenMatrixMultiplicationTestNegativeNumber4x4() {
- int[][] A = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
- int[][] B = {{1, -2, -3, 4}, {4, -3, -2, 1}, {5, -6, -7, 8}, {8, -7, -6, -5}};
+
+ void strassenMatrixMultiplicationTestNegetiveNumber4x4() {
+ int[][] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
+ int[][] b = {{1, -2, -3, 4}, {4, -3, -2, 1}, {5, -6, -7, 8}, {8, -7, -6, -5}};
int[][] expResult = {{56, -54, -52, 10}, {128, -126, -124, 42}, {200, -198, -196, 74}, {272, -270, -268, 106}};
- int[][] actResult = SMM.multiply(A, B);
+ int[][] actResult = SMM.multiply(a, b);
assertArrayEquals(expResult, actResult);
}
}
diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java
index 72e1d660028c..173ed00488d0 100644
--- a/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java
+++ b/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java
@@ -15,11 +15,11 @@ public void testOptimalJobScheduling1() {
int numberProcesses = 5;
int numberMachines = 4;
- int[][] Run = {{5, 1, 3, 2}, {4, 2, 1, 3}, {1, 5, 2, 1}, {2, 3, 4, 2}, {1, 1, 3, 1}};
+ int[][] run = {{5, 1, 3, 2}, {4, 2, 1, 3}, {1, 5, 2, 1}, {2, 3, 4, 2}, {1, 1, 3, 1}};
- int[][] Transfer = {{0, 1, 2, 4}, {1, 0, 2, 3}, {2, 2, 0, 1}, {4, 3, 1, 0}};
+ int[][] transfer = {{0, 1, 2, 4}, {1, 0, 2, 3}, {2, 2, 0, 1}, {4, 3, 1, 0}};
- OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer);
+ OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, run, transfer);
opt.execute();
@@ -40,11 +40,11 @@ public void testOptimalJobScheduling2() {
int numberProcesses = 3;
int numberMachines = 3;
- int[][] Run = {{5, 1, 3}, {4, 2, 1}, {1, 5, 2}};
+ int[][] run = {{5, 1, 3}, {4, 2, 1}, {1, 5, 2}};
- int[][] Transfer = {{0, 1, 2}, {1, 0, 2}, {2, 2, 0}};
+ int[][] transfer = {{0, 1, 2}, {1, 0, 2}, {2, 2, 0}};
- OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer);
+ OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, run, transfer);
opt.execute();
@@ -65,7 +65,7 @@ public void testOptimalJobScheduling3() {
int numberProcesses = 6;
int numberMachines = 4;
- int[][] Run = {
+ int[][] run = {
{5, 1, 3, 2},
{4, 2, 1, 1},
{1, 5, 2, 6},
@@ -74,14 +74,14 @@ public void testOptimalJobScheduling3() {
{3, 2, 2, 3},
};
- int[][] Transfer = {
+ int[][] transfer = {
{0, 1, 2, 1},
{1, 0, 2, 3},
{2, 2, 0, 2},
{1, 3, 2, 0},
};
- OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer);
+ OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, run, transfer);
opt.execute();
From 1a98ebe36bac61c8edc5223533d320ac03f3bec9 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Tue, 28 May 2024 20:57:32 +0200
Subject: [PATCH 0055/1023] style: enable `MissingSwitchDefault` in CheckStyle
(#5188)
---
checkstyle.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/checkstyle.xml b/checkstyle.xml
index 6357bcb4ddbd..8b659d986af8 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -166,7 +166,7 @@
-
+
From 2cda9446434dc6ec7c65d7aad66a2e72e0258cb5 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Tue, 28 May 2024 21:03:52 +0200
Subject: [PATCH 0056/1023] style: include `ENMI_EQUALS_ON_ENUM` (#5189)
---
spotbugs-exclude.xml | 3 ---
.../com/thealgorithms/datastructures/crdt/LWWElementSet.java | 4 ++--
2 files changed, 2 insertions(+), 5 deletions(-)
diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml
index 99a24bbff9d5..45ea8ed05d07 100644
--- a/spotbugs-exclude.xml
+++ b/spotbugs-exclude.xml
@@ -222,9 +222,6 @@
-
-
-
diff --git a/src/main/java/com/thealgorithms/datastructures/crdt/LWWElementSet.java b/src/main/java/com/thealgorithms/datastructures/crdt/LWWElementSet.java
index b8b296359844..2c6ce8a427d1 100644
--- a/src/main/java/com/thealgorithms/datastructures/crdt/LWWElementSet.java
+++ b/src/main/java/com/thealgorithms/datastructures/crdt/LWWElementSet.java
@@ -124,14 +124,14 @@ public void merge(LWWElementSet other) {
* @return True if the first element's timestamp is greater or the bias is ADDS and timestamps are equal.
*/
public boolean compareTimestamps(Element e, Element other) {
- if (!e.bias.equals(other.bias)) {
+ if (e.bias != other.bias) {
throw new IllegalArgumentException("Invalid bias value");
}
Bias bias = e.bias;
int timestampComparison = Integer.compare(e.timestamp, other.timestamp);
if (timestampComparison == 0) {
- return !bias.equals(Bias.ADDS);
+ return bias != Bias.ADDS;
}
return timestampComparison < 0;
}
From d2bfb100b22a1b8ad86d99dfcc75a5f65db6e874 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Tue, 28 May 2024 21:06:47 +0200
Subject: [PATCH 0057/1023] style: include `LII_LIST_INDEXED_ITERATING` (#5190)
---
spotbugs-exclude.xml | 3 ---
.../java/com/thealgorithms/scheduling/FCFSScheduling.java | 4 ++--
src/main/java/com/thealgorithms/scheduling/RRScheduling.java | 4 +++-
3 files changed, 5 insertions(+), 6 deletions(-)
diff --git a/spotbugs-exclude.xml b/spotbugs-exclude.xml
index 45ea8ed05d07..02e03725c429 100644
--- a/spotbugs-exclude.xml
+++ b/spotbugs-exclude.xml
@@ -141,9 +141,6 @@
-
-
-
diff --git a/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java b/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java
index e73937f60b48..b22e81fe560e 100644
--- a/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java
+++ b/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java
@@ -40,8 +40,8 @@ private void evaluateWaitingTime() {
}
private void evaluateTurnAroundTime() {
- for (int i = 0; i < processes.size(); i++) {
- processes.get(i).setTurnAroundTimeTime(processes.get(i).getBurstTime() + processes.get(i).getWaitingTime());
+ for (final var process : processes) {
+ process.setTurnAroundTimeTime(process.getBurstTime() + process.getWaitingTime());
}
}
}
diff --git a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java
index 9968f172b482..991c9a4f6148 100644
--- a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java
+++ b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java
@@ -95,6 +95,8 @@ private void evaluateTurnAroundTime() {
}
private void evaluateWaitingTime() {
- for (int i = 0; i < processes.size(); i++) processes.get(i).setWaitingTime(processes.get(i).getTurnAroundTimeTime() - processes.get(i).getBurstTime());
+ for (final var process : processes) {
+ process.setWaitingTime(process.getTurnAroundTimeTime() - process.getBurstTime());
+ }
}
}
From a6e873deefade4d302d12f4bc63a51ec10daf67c Mon Sep 17 00:00:00 2001
From: "S. Utkarsh" <69796213+cpu-pixel@users.noreply.github.com>
Date: Thu, 30 May 2024 02:14:14 +0530
Subject: [PATCH 0058/1023] style: enable `MemberName` in checkstyle (#5193)
* style: enable MemberName in checkstyle
* style: simply uncomment `MemberName`
---------
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
---
checkstyle.xml | 2 +-
.../com/thealgorithms/ciphers/Blowfish.java | 20 ++--
.../conversions/HexaDecimalToBinary.java | 4 +-
.../datastructures/crdt/GCounter.java | 14 +--
.../datastructures/crdt/PNCounter.java | 26 +++---
.../datastructures/graphs/FloydWarshall.java | 12 +--
.../graphs/HamiltonianCycle.java | 12 +--
.../datastructures/graphs/MatrixGraphs.java | 36 ++++----
.../graphs/TarjansAlgorithm.java | 14 +--
.../hashmap/hashing/HashMapCuckooHashing.java | 20 ++--
.../queues/GenericArrayListQueue.java | 10 +-
.../datastructures/trees/FenwickTree.java | 8 +-
.../datastructures/trees/RedBlackBST.java | 92 +++++++++----------
.../datastructures/trees/SegmentTree.java | 14 +--
.../OptimalJobScheduling.java | 38 ++++----
.../StrassenMatrixMultiplicationTest.java | 8 +-
.../sorts/BinaryInsertionSortTest.java | 6 +-
17 files changed, 168 insertions(+), 168 deletions(-)
diff --git a/checkstyle.xml b/checkstyle.xml
index 8b659d986af8..de7c70266bfb 100644
--- a/checkstyle.xml
+++ b/checkstyle.xml
@@ -111,7 +111,7 @@
-
+
diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
index d0e947206e5f..a8fa6fc56088 100644
--- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java
+++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
@@ -11,7 +11,7 @@
public class Blowfish {
// Initializing substitution boxes
- String[][] S = {
+ String[][] sBox = {
{
"d1310ba6",
"98dfb5ac",
@@ -1047,7 +1047,7 @@ public class Blowfish {
};
// Initializing subkeys with digits of pi
- String[] P = {
+ String[] subKeys = {
"243f6a88",
"85a308d3",
"13198a2e",
@@ -1154,7 +1154,7 @@ private String f(String plainText) {
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);
- a[i / 2] = S[i / 2][(int) col];
+ a[i / 2] = sBox[i / 2][(int) col];
}
ans = addBin(a[0], a[1]);
ans = xor(ans, a[2]);
@@ -1165,9 +1165,9 @@ private String f(String plainText) {
// generate subkeys
private void keyGenerate(String key) {
int j = 0;
- for (int i = 0; i < P.length; i++) {
+ for (int i = 0; i < subKeys.length; i++) {
// XOR-ing 32-bit parts of the key with initial subkeys
- P[i] = xor(P[i], key.substring(j, j + 8));
+ subKeys[i] = xor(subKeys[i], key.substring(j, j + 8));
j = (j + 8) % key.length();
}
@@ -1179,7 +1179,7 @@ private String round(int time, String plainText) {
String right;
left = plainText.substring(0, 8);
right = plainText.substring(8, 16);
- left = xor(left, P[time]);
+ left = xor(left, subKeys[time]);
// output from F function
String fOut = f(left);
@@ -1207,8 +1207,8 @@ String encrypt(String plainText, String key) {
// postprocessing
String right = plainText.substring(0, 8);
String left = plainText.substring(8, 16);
- right = xor(right, P[16]);
- left = xor(left, P[17]);
+ right = xor(right, subKeys[16]);
+ left = xor(left, subKeys[17]);
return left + right;
}
@@ -1229,8 +1229,8 @@ String decrypt(String cipherText, String key) {
// postprocessing
String right = cipherText.substring(0, 8);
String left = cipherText.substring(8, 16);
- right = xor(right, P[1]);
- left = xor(left, P[0]);
+ right = xor(right, subKeys[1]);
+ left = xor(left, subKeys[0]);
return left + right;
}
}
diff --git a/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java b/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java
index 5372c95f23d4..c766b83f1c7b 100644
--- a/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java
+++ b/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java
@@ -3,7 +3,7 @@
// Hex [0-9],[A-F] -> Binary [0,1]
public class HexaDecimalToBinary {
- private final int LONG_BITS = 8;
+ private final int longBits = 8;
public String convert(String numHex) {
// String a HexaDecimal:
@@ -15,7 +15,7 @@ public String convert(String numHex) {
}
public String completeDigits(String binNum) {
- for (int i = binNum.length(); i < LONG_BITS; i++) {
+ for (int i = binNum.length(); i < longBits; i++) {
binNum = "0" + binNum;
}
return binNum;
diff --git a/src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java b/src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java
index ced55d87a3cf..25b01bce19f3 100644
--- a/src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java
+++ b/src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java
@@ -17,7 +17,7 @@
*/
class GCounter {
- private final Map P;
+ private final Map counterMap;
private final int myId;
private final int n;
@@ -29,10 +29,10 @@ class GCounter {
GCounter(int myId, int n) {
this.myId = myId;
this.n = n;
- this.P = new HashMap<>();
+ this.counterMap = new HashMap<>();
for (int i = 0; i < n; i++) {
- P.put(i, 0);
+ counterMap.put(i, 0);
}
}
@@ -40,7 +40,7 @@ class GCounter {
* Increments the counter for the current node.
*/
public void increment() {
- P.put(myId, P.get(myId) + 1);
+ counterMap.put(myId, counterMap.get(myId) + 1);
}
/**
@@ -50,7 +50,7 @@ public void increment() {
*/
public int value() {
int sum = 0;
- for (int v : P.values()) {
+ for (int v : counterMap.values()) {
sum += v;
}
return sum;
@@ -64,7 +64,7 @@ public int value() {
*/
public boolean compare(GCounter other) {
for (int i = 0; i < n; i++) {
- if (this.P.get(i) > other.P.get(i)) {
+ if (this.counterMap.get(i) > other.counterMap.get(i)) {
return false;
}
}
@@ -78,7 +78,7 @@ public boolean compare(GCounter other) {
*/
public void merge(GCounter other) {
for (int i = 0; i < n; i++) {
- this.P.put(i, Math.max(this.P.get(i), other.P.get(i)));
+ this.counterMap.put(i, Math.max(this.counterMap.get(i), other.counterMap.get(i)));
}
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java b/src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java
index 04b846758f37..53c21dcbd108 100644
--- a/src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java
+++ b/src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java
@@ -17,8 +17,8 @@
*/
class PNCounter {
- private final Map P;
- private final Map N;
+ private final Map pCounter;
+ private final Map nCounter;
private final int myId;
private final int n;
@@ -31,12 +31,12 @@ class PNCounter {
PNCounter(int myId, int n) {
this.myId = myId;
this.n = n;
- this.P = new HashMap<>();
- this.N = new HashMap<>();
+ this.pCounter = new HashMap<>();
+ this.nCounter = new HashMap<>();
for (int i = 0; i < n; i++) {
- P.put(i, 0);
- N.put(i, 0);
+ pCounter.put(i, 0);
+ nCounter.put(i, 0);
}
}
@@ -44,14 +44,14 @@ class PNCounter {
* Increments the increment counter for the current node.
*/
public void increment() {
- P.put(myId, P.get(myId) + 1);
+ pCounter.put(myId, pCounter.get(myId) + 1);
}
/**
* Increments the decrement counter for the current node.
*/
public void decrement() {
- N.put(myId, N.get(myId) + 1);
+ nCounter.put(myId, nCounter.get(myId) + 1);
}
/**
@@ -60,8 +60,8 @@ public void decrement() {
* @return The total value of the counter.
*/
public int value() {
- int sumP = P.values().stream().mapToInt(Integer::intValue).sum();
- int sumN = N.values().stream().mapToInt(Integer::intValue).sum();
+ int sumP = pCounter.values().stream().mapToInt(Integer::intValue).sum();
+ int sumN = nCounter.values().stream().mapToInt(Integer::intValue).sum();
return sumP - sumN;
}
@@ -76,7 +76,7 @@ public boolean compare(PNCounter other) {
throw new IllegalArgumentException("Cannot compare PN-Counters with different number of nodes");
}
for (int i = 0; i < n; i++) {
- if (this.P.get(i) > other.P.get(i) && this.N.get(i) > other.N.get(i)) {
+ if (this.pCounter.get(i) > other.pCounter.get(i) && this.nCounter.get(i) > other.nCounter.get(i)) {
return false;
}
}
@@ -93,8 +93,8 @@ public void merge(PNCounter other) {
throw new IllegalArgumentException("Cannot merge PN-Counters with different number of nodes");
}
for (int i = 0; i < n; i++) {
- this.P.put(i, Math.max(this.P.get(i), other.P.get(i)));
- this.N.put(i, Math.max(this.N.get(i), other.N.get(i)));
+ this.pCounter.put(i, Math.max(this.pCounter.get(i), other.pCounter.get(i)));
+ this.nCounter.put(i, Math.max(this.nCounter.get(i), other.nCounter.get(i)));
}
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
index b295fb08c1dc..a574b40daec6 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
@@ -4,12 +4,12 @@
public class FloydWarshall {
- private int[][] DistanceMatrix;
+ private int[][] distanceMatrix;
private int numberofvertices; // number of vertices in the graph
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;
@@ -18,17 +18,17 @@ public FloydWarshall(int numberofvertices) {
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];
+ distanceMatrix[source][destination] = AdjacencyMatrix[source][destination];
}
}
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
+ 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];
+ distanceMatrix[source][destination] = distanceMatrix[source][intermediate] + distanceMatrix[intermediate][destination];
}
}
}
@@ -40,7 +40,7 @@ public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the dista
for (int source = 1; source <= numberofvertices; source++) {
System.out.print(source + "\t");
for (int destination = 1; destination <= numberofvertices; destination++) {
- System.out.print(DistanceMatrix[source][destination] + "\t");
+ System.out.print(distanceMatrix[source][destination] + "\t");
}
System.out.println();
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
index d12f631db6f1..65483eeeb65c 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
@@ -8,7 +8,7 @@
*/
public class HamiltonianCycle {
- private int V;
+ private int vertex;
private int pathCount;
private int[] cycle;
private int[][] graph;
@@ -22,8 +22,8 @@ public class HamiltonianCycle {
* else returns 1D array with value -1.
*/
public int[] findHamiltonianCycle(int[][] graph) {
- this.V = graph.length;
- this.cycle = new int[this.V + 1];
+ this.vertex = graph.length;
+ this.cycle = new int[this.vertex + 1];
// Initialize path array with -1 value
for (int i = 0; i < this.cycle.length; i++) {
@@ -53,17 +53,17 @@ public int[] findHamiltonianCycle(int[][] graph) {
* @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.vertex;
if (isLastVertexConnectedToStart) {
return true;
}
/** all vertices selected but last vertex not linked to 0 **/
- if (this.pathCount == this.V) {
+ if (this.pathCount == this.vertex) {
return false;
}
- for (int v = 0; v < this.V; v++) {
+ for (int v = 0; v < this.vertex; v++) {
/** if connected **/
if (this.graph[vertex][v] == 1) {
/** add to path **/
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
index c578053477d7..902553f9a54c 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
@@ -48,17 +48,17 @@ class AdjacencyMatrixGraph {
/**
* The number of vertices in the graph
*/
- private int _numberOfVertices;
+ private int vertexCount;
/**
* The number of edges in the graph
*/
- private int _numberOfEdges;
+ private int edgeCount;
/**
* The adjacency matrix for the graph
*/
- private int[][] _adjacency;
+ private int[][] adjMatrix;
/**
* Static variables to define whether or not an edge exists in the adjacency
@@ -87,16 +87,16 @@ class AdjacencyMatrixGraph {
* @param newNumberOfVertices the new number of vertices
*/
private void setNumberOfVertices(int newNumberOfVertices) {
- this._numberOfVertices = newNumberOfVertices;
+ this.vertexCount = newNumberOfVertices;
}
/**
- * Getter for `this._numberOfVertices`
+ * Getter for `this.vertexCount`
*
* @return the number of vertices in the graph
*/
public int numberOfVertices() {
- return this._numberOfVertices;
+ return this.vertexCount;
}
/**
@@ -106,16 +106,16 @@ public int numberOfVertices() {
*
*/
private void setNumberOfEdges(int newNumberOfEdges) {
- this._numberOfEdges = newNumberOfEdges;
+ this.edgeCount = newNumberOfEdges;
}
/**
- * Getter for `this._numberOfEdges`
+ * Getter for `this.edgeCount`
*
* @return the number of edges
*/
public int numberOfEdges() {
- return this._numberOfEdges;
+ return this.edgeCount;
}
/**
@@ -124,7 +124,7 @@ public int numberOfEdges() {
* @param newAdjacency the new adjaceny matrix
*/
private void setAdjacency(int[][] newAdjacency) {
- this._adjacency = newAdjacency;
+ this.adjMatrix = newAdjacency;
}
/**
@@ -133,7 +133,7 @@ private void setAdjacency(int[][] newAdjacency) {
* @return the adjacency matrix
*/
private int[][] adjacency() {
- return this._adjacency;
+ return this.adjMatrix;
}
/**
@@ -222,12 +222,12 @@ public boolean removeEdge(int from, int to) {
*/
public List depthFirstOrder(int startVertex) {
// If the startVertex is invalid, return an empty list
- if (startVertex >= _numberOfVertices || startVertex < 0) {
+ if (startVertex >= vertexCount || startVertex < 0) {
return new ArrayList();
}
// Create an array to track the visited vertices
- boolean[] visited = new boolean[_numberOfVertices];
+ boolean[] visited = new boolean[vertexCount];
// Create a list to keep track of the order of our traversal
ArrayList orderList = new ArrayList();
@@ -259,7 +259,7 @@ private void depthFirstOrder(int currentVertex, boolean[] visited, List
orderList.add(currentVertex);
// Get the adjacency array for this vertex
- int[] adjacent = _adjacency[currentVertex];
+ int[] adjacent = adjMatrix[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
if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) {
@@ -277,12 +277,12 @@ private void depthFirstOrder(int currentVertex, boolean[] visited, List
*/
public List breadthFirstOrder(int startVertex) {
// If the specified startVertex is invalid, return an empty list
- if (startVertex >= _numberOfVertices || startVertex < 0) {
+ if (startVertex >= vertexCount || startVertex < 0) {
return new ArrayList();
}
// Create an array to keep track of the visited vertices
- boolean[] visited = new boolean[_numberOfVertices];
+ boolean[] visited = new boolean[vertexCount];
// Create a list to keep track of the ordered vertices
ArrayList orderList = new ArrayList();
@@ -309,7 +309,7 @@ public List breadthFirstOrder(int startVertex) {
// Get the adjacency array for the currentVertex and
// check each node
- int[] adjacent = _adjacency[currentVertex];
+ int[] adjacent = adjMatrix[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
if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) {
@@ -336,7 +336,7 @@ public String toString() {
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + i + " : ";
for (int j = 0; j < this.numberOfVertices(); j++) {
- s = s + this._adjacency[i][j] + " ";
+ s = s + this.adjMatrix[i][j] + " ";
}
s = s + "\n";
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
index 293ea5837823..251c169d11ac 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
@@ -56,9 +56,9 @@
public class TarjansAlgorithm {
// Timer for tracking lowtime and insertion time
- private int Time;
+ private int time;
- private List> SCClist = new ArrayList>();
+ private List> sccList = new ArrayList>();
public List> stronglyConnectedComponents(int V, List> graph) {
@@ -85,15 +85,15 @@ public List> stronglyConnectedComponents(int V, List
if (insertionTime[i] == -1) stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
}
- return SCClist;
+ return sccList;
}
private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, boolean[] isInStack, Stack st, List> graph) {
// Initialize insertion time and lowTime value of current node
- insertionTime[u] = Time;
- lowTime[u] = Time;
- Time += 1;
+ insertionTime[u] = time;
+ lowTime[u] = time;
+ time += 1;
// Push current node into stack
isInStack[u] = true;
@@ -123,7 +123,7 @@ private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, bo
scc.add(w);
isInStack[w] = false;
}
- SCClist.add(scc);
+ 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 6f382766b3b1..b48502b51d08 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java
@@ -12,21 +12,21 @@ public class HashMapCuckooHashing {
private int tableSize; // size of the hash table
private Integer[] buckets; // array representing the table
- private final Integer AVAILABLE;
+ private final Integer emptySlot;
private int size; // number of elements in the hash table
private int thresh; // threshold for infinite loop checking
/**
* Constructor initializes buckets array, hsize, and creates dummy object
- * for AVAILABLE
+ * for emptySlot
*
* @param tableSize the desired size of the hash map
*/
public HashMapCuckooHashing(int tableSize) {
this.buckets = new Integer[tableSize];
this.tableSize = tableSize;
- this.AVAILABLE = Integer.MIN_VALUE;
+ this.emptySlot = Integer.MIN_VALUE;
this.size = 0;
this.thresh = (int) (Math.log(tableSize) / Math.log(2)) + 2;
}
@@ -84,7 +84,7 @@ public void insertKey2HashTable(int key) {
loopCounter++;
hash = hashFunction1(key);
- if ((buckets[hash] == null) || Objects.equals(buckets[hash], AVAILABLE)) {
+ if ((buckets[hash] == null) || Objects.equals(buckets[hash], emptySlot)) {
buckets[hash] = wrappedInt;
size++;
checkLoadFactor();
@@ -95,7 +95,7 @@ public void insertKey2HashTable(int key) {
buckets[hash] = wrappedInt;
wrappedInt = temp;
hash = hashFunction2(temp);
- if (Objects.equals(buckets[hash], AVAILABLE)) {
+ if (Objects.equals(buckets[hash], emptySlot)) {
buckets[hash] = wrappedInt;
size++;
checkLoadFactor();
@@ -124,7 +124,7 @@ public void insertKey2HashTable(int key) {
public void reHashTableIncreasesTableSize() {
HashMapCuckooHashing newT = new HashMapCuckooHashing(tableSize * 2);
for (int i = 0; i < tableSize; i++) {
- if (buckets[i] != null && !Objects.equals(buckets[i], AVAILABLE)) {
+ if (buckets[i] != null && !Objects.equals(buckets[i], emptySlot)) {
newT.insertKey2HashTable(this.buckets[i]);
}
}
@@ -146,14 +146,14 @@ public void deleteKeyFromHashTable(int key) {
}
if (Objects.equals(buckets[hash], wrappedInt)) {
- buckets[hash] = AVAILABLE;
+ buckets[hash] = emptySlot;
size--;
return;
}
hash = hashFunction2(key);
if (Objects.equals(buckets[hash], wrappedInt)) {
- buckets[hash] = AVAILABLE;
+ buckets[hash] = emptySlot;
size--;
return;
}
@@ -165,7 +165,7 @@ public void deleteKeyFromHashTable(int key) {
*/
public void displayHashtable() {
for (int i = 0; i < tableSize; i++) {
- if ((buckets[i] == null) || Objects.equals(buckets[i], AVAILABLE)) {
+ if ((buckets[i] == null) || Objects.equals(buckets[i], emptySlot)) {
System.out.println("Bucket " + i + ": Empty");
} else {
System.out.println("Bucket " + i + ": " + buckets[i].toString());
@@ -229,7 +229,7 @@ public double checkLoadFactor() {
public boolean isFull() {
boolean response = true;
for (int i = 0; i < tableSize; i++) {
- if (buckets[i] == null || Objects.equals(buckets[i], AVAILABLE)) {
+ if (buckets[i] == null || Objects.equals(buckets[i], emptySlot)) {
return false;
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/GenericArrayListQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/GenericArrayListQueue.java
index b9331569e131..ec1e15e415b8 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/GenericArrayListQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/GenericArrayListQueue.java
@@ -15,7 +15,7 @@ public class GenericArrayListQueue {
/**
* The generic ArrayList for the queue T is the generic element
*/
- ArrayList _queue = new ArrayList<>();
+ ArrayList elementList = new ArrayList<>();
/**
* Checks if the queue has elements (not empty).
@@ -23,7 +23,7 @@ public class GenericArrayListQueue {
* @return True if the queue has elements. False otherwise.
*/
private boolean hasElements() {
- return !_queue.isEmpty();
+ return !elementList.isEmpty();
}
/**
@@ -35,7 +35,7 @@ private boolean hasElements() {
public T peek() {
T result = null;
if (this.hasElements()) {
- result = _queue.get(0);
+ result = elementList.get(0);
}
return result;
}
@@ -47,7 +47,7 @@ public T peek() {
* @return True if the element was added successfully
*/
public boolean add(T element) {
- return _queue.add(element);
+ return elementList.add(element);
}
/**
@@ -58,7 +58,7 @@ public boolean add(T element) {
public T pull() {
T result = null;
if (this.hasElements()) {
- result = _queue.remove(0);
+ result = elementList.remove(0);
}
return result;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java b/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java
index 5cd28202229e..5378a01f6642 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java
@@ -3,12 +3,12 @@
public class FenwickTree {
private int n;
- private int[] fen_t;
+ private int[] fenTree;
/* Constructor which takes the size of the array as a parameter */
public FenwickTree(int n) {
this.n = n;
- this.fen_t = new int[n + 1];
+ this.fenTree = new int[n + 1];
}
/* A function which will add the element val at index i*/
@@ -16,7 +16,7 @@ public void update(int i, int val) {
// As index starts from 0, increment the index by 1
i += 1;
while (i <= n) {
- fen_t[i] += val;
+ fenTree[i] += val;
i += i & (-i);
}
}
@@ -27,7 +27,7 @@ public int query(int i) {
i += 1;
int cumSum = 0;
while (i > 0) {
- cumSum += fen_t[i];
+ cumSum += fenTree[i];
i -= i & (-i);
}
return cumSum;
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java
index c7cb108d6b77..2961282efe75 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java
@@ -7,13 +7,13 @@
*/
public class RedBlackBST {
- private final int R = 0;
- private final int B = 1;
+ private final int red = 0;
+ private final int black = 1;
private class Node {
int key = -1;
- int color = B;
+ int color = black;
Node left = nil;
Node right = nil;
Node p = nil;
@@ -31,7 +31,7 @@ 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 == red) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
printTree(node.right);
}
@@ -39,7 +39,7 @@ 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 == red) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
printTreepre(node.left);
printTreepre(node.right);
}
@@ -66,10 +66,10 @@ private void insert(Node node) {
Node temp = root;
if (root == nil) {
root = node;
- node.color = B;
+ node.color = black;
node.p = nil;
} else {
- node.color = R;
+ node.color = red;
while (true) {
if (node.key < temp.key) {
if (temp.left == nil) {
@@ -94,15 +94,15 @@ private void insert(Node node) {
}
private void fixTree(Node node) {
- while (node.p.color == R) {
+ while (node.p.color == red) {
Node y = nil;
if (node.p == node.p.p.left) {
y = node.p.p.right;
- if (y != nil && y.color == R) {
- node.p.color = B;
- y.color = B;
- node.p.p.color = R;
+ if (y != nil && y.color == red) {
+ node.p.color = black;
+ y.color = black;
+ node.p.p.color = red;
node = node.p.p;
continue;
}
@@ -110,15 +110,15 @@ private void fixTree(Node node) {
node = node.p;
rotateLeft(node);
}
- node.p.color = B;
- node.p.p.color = R;
+ node.p.color = black;
+ node.p.p.color = red;
rotateRight(node.p.p);
} else {
y = node.p.p.left;
- if (y != nil && y.color == R) {
- node.p.color = B;
- y.color = B;
- node.p.p.color = R;
+ if (y != nil && y.color == red) {
+ node.p.color = black;
+ y.color = black;
+ node.p.p.color = red;
node = node.p.p;
continue;
}
@@ -126,12 +126,12 @@ private void fixTree(Node node) {
node = node.p;
rotateRight(node);
}
- node.p.color = B;
- node.p.p.color = R;
+ node.p.color = black;
+ node.p.p.color = red;
rotateLeft(node.p.p);
}
}
- root.color = B;
+ root.color = black;
}
void rotateLeft(Node node) {
@@ -234,67 +234,67 @@ boolean delete(Node z) {
y.left.p = y;
y.color = z.color;
}
- if (yorigcolor == B) {
+ if (yorigcolor == black) {
deleteFixup(x);
}
return true;
}
void deleteFixup(Node x) {
- while (x != root && x.color == B) {
+ while (x != root && x.color == black) {
if (x == x.p.left) {
Node w = x.p.right;
- if (w.color == R) {
- w.color = B;
- x.p.color = R;
+ if (w.color == red) {
+ w.color = black;
+ x.p.color = red;
rotateLeft(x.p);
w = x.p.right;
}
- if (w.left.color == B && w.right.color == B) {
- w.color = R;
+ if (w.left.color == black && w.right.color == black) {
+ w.color = red;
x = x.p;
continue;
- } else if (w.right.color == B) {
- w.left.color = B;
- w.color = R;
+ } else if (w.right.color == black) {
+ w.left.color = black;
+ w.color = red;
rotateRight(w);
w = x.p.right;
}
- if (w.right.color == R) {
+ if (w.right.color == red) {
w.color = x.p.color;
- x.p.color = B;
- w.right.color = B;
+ x.p.color = black;
+ w.right.color = black;
rotateLeft(x.p);
x = root;
}
} else {
Node w = x.p.left;
- if (w.color == R) {
- w.color = B;
- x.p.color = R;
+ if (w.color == red) {
+ w.color = black;
+ x.p.color = red;
rotateRight(x.p);
w = x.p.left;
}
- if (w.right.color == B && w.left.color == B) {
- w.color = R;
+ if (w.right.color == black && w.left.color == black) {
+ w.color = red;
x = x.p;
continue;
- } else if (w.left.color == B) {
- w.right.color = B;
- w.color = R;
+ } else if (w.left.color == black) {
+ w.right.color = black;
+ w.color = red;
rotateLeft(w);
w = x.p.left;
}
- if (w.left.color == R) {
+ if (w.left.color == red) {
w.color = x.p.color;
- x.p.color = B;
- w.left.color = B;
+ x.p.color = black;
+ w.left.color = black;
rotateRight(x.p);
x = root;
}
}
}
- x.color = B;
+ x.color = black;
}
public void insertDemo() {
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java
index a6954b24cf3a..a6a76f8f094f 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java
@@ -2,7 +2,7 @@
public class SegmentTree {
- private int[] seg_t;
+ private int[] segTree;
private int n;
private int[] arr;
@@ -12,7 +12,7 @@ public SegmentTree(int n, int[] arr) {
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
int segSize = 2 * (int) Math.pow(2, x) - 1;
- this.seg_t = new int[segSize];
+ this.segTree = new int[segSize];
this.arr = arr;
this.n = n;
constructTree(arr, 0, n - 1, 0);
@@ -21,13 +21,13 @@ public SegmentTree(int n, int[] arr) {
/* A function which will create the segment tree*/
public final int constructTree(int[] arr, int start, int end, int index) {
if (start == end) {
- this.seg_t[index] = arr[start];
+ this.segTree[index] = arr[start];
return arr[start];
}
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);
- return this.seg_t[index];
+ this.segTree[index] = constructTree(arr, start, mid, index * 2 + 1) + constructTree(arr, mid + 1, end, index * 2 + 2);
+ return this.segTree[index];
}
/* A function which will update the value at a index i. This will be called by the
@@ -37,7 +37,7 @@ private void updateTree(int start, int end, int index, int diff, int seg_index)
return;
}
- this.seg_t[seg_index] += diff;
+ this.segTree[seg_index] += diff;
if (start != end) {
int mid = start + (end - start) / 2;
updateTree(start, mid, index, diff, seg_index * 2 + 1);
@@ -60,7 +60,7 @@ public void update(int index, int value) {
* 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];
+ return this.segTree[seg_index];
}
if (q_start > end || q_end < start) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
index 5ee3327553d7..0840e08c531c 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
@@ -13,24 +13,24 @@ public class OptimalJobScheduling {
private final int numberProcesses;
private final int numberMachines;
- private final int[][] Run;
- private final int[][] Transfer;
- private final int[][] Cost;
+ private final int[][] run;
+ private final int[][] transfer;
+ private final int[][] cost;
/**
* Constructor of the class.
* @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
+ * @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
*/
- 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;
- this.Transfer = Transfer;
- this.Cost = new int[numberProcesses][numberMachines];
+ this.run = run;
+ this.transfer = transfer;
+ this.cost = new int[numberProcesses][numberMachines];
}
/**
@@ -50,7 +50,7 @@ private void calculateCost() {
for (int j = 0; j < numberMachines; j++) { // for each Machine
- Cost[i][j] = runningCost(i, j);
+ cost[i][j] = runningCost(i, j);
}
}
}
@@ -71,7 +71,7 @@ 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
- return Run[process][machine];
+ return run[process][machine];
else {
int[] runningCosts = new int[numberMachines]; // stores the costs of executing our Process depending on
@@ -79,7 +79,7 @@ private int runningCost(int process, int 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
+ 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
@@ -88,19 +88,19 @@ private int runningCost(int process, int machine) {
/**
* 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
+ * @param costArr ,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) {
+ private int findMin(int[] costArr) {
int min = 0;
- for (int i = 1; i < cost.length; i++) {
+ for (int i = 1; i < costArr.length; i++) {
- if (cost[i] < cost[min]) min = i;
+ if (costArr[i] < costArr[min]) min = i;
}
- return cost[min];
+ return costArr[min];
}
/**
@@ -111,7 +111,7 @@ private void showResults() {
for (int i = 0; i < numberProcesses; i++) {
for (int j = 0; j < numberMachines; j++) {
- System.out.print(Cost[i][j]);
+ System.out.print(cost[i][j]);
System.out.print(" ");
}
@@ -124,6 +124,6 @@ private void showResults() {
* Getter for the running Cost of i process on j machine.
*/
public int getCost(int process, int machine) {
- return Cost[process][machine];
+ return cost[process][machine];
}
}
diff --git a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java
index 17a1d2374d66..1ec45a863e1a 100644
--- a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java
+++ b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java
@@ -6,7 +6,7 @@
class StrassenMatrixMultiplicationTest {
- StrassenMatrixMultiplication SMM = new StrassenMatrixMultiplication();
+ StrassenMatrixMultiplication smm = new StrassenMatrixMultiplication();
// Strassen Matrix Multiplication can only be allplied to matrices of size 2^n
// and has to be a Square Matrix
@@ -16,7 +16,7 @@ public void strassenMatrixMultiplicationTest2x2() {
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] expResult = {{19, 22}, {43, 50}};
- int[][] actResult = SMM.multiply(a, b);
+ int[][] actResult = smm.multiply(a, b);
assertArrayEquals(expResult, actResult);
}
@@ -25,7 +25,7 @@ void strassenMatrixMultiplicationTest4x4() {
int[][] a = {{1, 2, 5, 4}, {9, 3, 0, 6}, {4, 6, 3, 1}, {0, 2, 0, 6}};
int[][] b = {{1, 0, 4, 1}, {1, 2, 0, 2}, {0, 3, 1, 3}, {1, 8, 1, 2}};
int[][] expResult = {{7, 51, 13, 28}, {18, 54, 42, 27}, {11, 29, 20, 27}, {8, 52, 6, 16}};
- int[][] actResult = SMM.multiply(a, b);
+ int[][] actResult = smm.multiply(a, b);
assertArrayEquals(expResult, actResult);
}
@@ -35,7 +35,7 @@ void strassenMatrixMultiplicationTestNegetiveNumber4x4() {
int[][] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int[][] b = {{1, -2, -3, 4}, {4, -3, -2, 1}, {5, -6, -7, 8}, {8, -7, -6, -5}};
int[][] expResult = {{56, -54, -52, 10}, {128, -126, -124, 42}, {200, -198, -196, 74}, {272, -270, -268, 106}};
- int[][] actResult = SMM.multiply(a, b);
+ int[][] actResult = smm.multiply(a, b);
assertArrayEquals(expResult, actResult);
}
}
diff --git a/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java b/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java
index 2c355cee01b8..bdd0702942a2 100644
--- a/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java
+++ b/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java
@@ -6,14 +6,14 @@
class BinaryInsertionSortTest {
- BinaryInsertionSort BIS = new BinaryInsertionSort();
+ BinaryInsertionSort bis = new BinaryInsertionSort();
@Test
// valid test case
public void binaryInsertionSortTestNonDuplicate() {
int[] array = {1, 0, 2, 5, 3, 4, 9, 8, 10, 6, 7};
int[] expResult = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- int[] actResult = BIS.binaryInsertSort(array);
+ int[] actResult = bis.binaryInsertSort(array);
assertArrayEquals(expResult, actResult);
}
@@ -21,7 +21,7 @@ public void binaryInsertionSortTestNonDuplicate() {
public void binaryInsertionSortTestDuplicate() {
int[] array = {1, 1, 1, 5, 9, 8, 7, 2, 6};
int[] expResult = {1, 1, 1, 2, 5, 6, 7, 8, 9};
- int[] actResult = BIS.binaryInsertSort(array);
+ int[] actResult = bis.binaryInsertSort(array);
assertArrayEquals(expResult, actResult);
}
}
From 2568b96784e50ce517aa223e29302fc10ef3caac Mon Sep 17 00:00:00 2001
From: Alex K
Date: Thu, 30 May 2024 21:43:15 +0300
Subject: [PATCH 0059/1023] Adding class for generating all subsequences from a
given List (#5194)
* Adding class for generating all subsequences from a given List
* Fix test data format
* Fix braces wrong placement
* Fix "Utility classes should not have a public or default constructor."
* Fix checkstyle " Class Subsequence should be declared as final."
* Renaming class Subsequence to SubsequenceFinder. Refactored test to Parametrized test. Fixed input parameter as final.
* Fix formatting
* Fix formatting
* Fix formatting
* Fix import ordering
* Renaming method generate all.
Renaming test method.
Adding duplication test.
Renaming TestData to TestCase.
* Fix formatting
* style: add assertion to avoid potential infinite loop
---------
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
---
.../backtracking/SubsequenceFinder.java | 54 +++++++++++++++++++
.../backtracking/SubsequenceFinderTest.java | 28 ++++++++++
2 files changed, 82 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java
create mode 100644 src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java
diff --git a/src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java b/src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java
new file mode 100644
index 000000000000..4a159dbfe0b1
--- /dev/null
+++ b/src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java
@@ -0,0 +1,54 @@
+package com.thealgorithms.backtracking;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Class generates all subsequences for a given list of elements using backtracking
+ */
+public final class SubsequenceFinder {
+ private SubsequenceFinder() {
+ }
+
+ /**
+ * Find all subsequences of given list using backtracking
+ *
+ * @param sequence a list of items on the basis of which we need to generate all subsequences
+ * @param the type of elements in the array
+ * @return a list of all subsequences
+ */
+ public static List> generateAll(List sequence) {
+ List> allSubSequences = new ArrayList<>();
+ if (sequence.isEmpty()) {
+ allSubSequences.add(new ArrayList<>());
+ return allSubSequences;
+ }
+ List currentSubsequence = new ArrayList<>();
+ backtrack(sequence, currentSubsequence, 0, allSubSequences);
+ return allSubSequences;
+ }
+
+ /**
+ * Iterate through each branch of states
+ * We know that each state has exactly two branching
+ * It terminates when it reaches the end of the given sequence
+ *
+ * @param sequence all elements
+ * @param currentSubsequence current subsequence
+ * @param index current index
+ * @param allSubSequences contains all sequences
+ * @param the type of elements which we generate
+ */
+ private static void backtrack(List sequence, List currentSubsequence, final int index, List> allSubSequences) {
+ assert index <= sequence.size();
+ if (index == sequence.size()) {
+ allSubSequences.add(new ArrayList<>(currentSubsequence));
+ return;
+ }
+
+ backtrack(sequence, currentSubsequence, index + 1, allSubSequences);
+ currentSubsequence.add(sequence.get(index));
+ backtrack(sequence, currentSubsequence, index + 1, allSubSequences);
+ currentSubsequence.removeLast();
+ }
+}
diff --git a/src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java b/src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java
new file mode 100644
index 000000000000..dac2e2675674
--- /dev/null
+++ b/src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java
@@ -0,0 +1,28 @@
+package com.thealgorithms.backtracking;
+
+import static org.junit.jupiter.api.Assertions.assertIterableEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class SubsequenceFinderTest {
+
+ @ParameterizedTest
+ @MethodSource("getTestCases")
+ void testGenerateAll(TestCase testData) {
+ final var actual = SubsequenceFinder.generateAll(testData.input());
+ assertIterableEquals(testData.expected(), actual);
+ }
+
+ static Stream getTestCases() {
+ return Stream.of(new TestCase(new ArrayList<>(), List.of(List.of())), new TestCase(List.of(1, 2), List.of(List.of(), List.of(2), List.of(1), List.of(1, 2))),
+ new TestCase(List.of("A", "B", "C"), List.of(List.of(), List.of("C"), List.of("B"), List.of("B", "C"), List.of("A"), List.of("A", "C"), List.of("A", "B"), List.of("A", "B", "C"))),
+ new TestCase(List.of(1, 2, 3), List.of(List.of(), List.of(3), List.of(2), List.of(2, 3), List.of(1), List.of(1, 3), List.of(1, 2), List.of(1, 2, 3))), new TestCase(List.of(2, 2), List.of(List.of(), List.of(2), List.of(2), List.of(2, 2))));
+ }
+
+ record TestCase(List