style: enable LocalVariableName in CheckStyle (#5191)

* style: enable LocalVariableName in checkstyle

* Removed minor bug

* Resolved Method Name Bug

* Changed names according to suggestions
This commit is contained in:
S. Utkarsh
2024-05-28 23:59:28 +05:30
committed by GitHub
parent 81cb09b1f8
commit 25d711c5d8
45 changed files with 418 additions and 417 deletions

View File

@ -110,7 +110,7 @@
<!-- See https://checkstyle.org/checks/naming/index.html -->
<module name="ConstantName"/>
<module name="LocalFinalVariableName"/>
<!-- TODO <module name="LocalVariableName"/> -->
<module name="LocalVariableName"/>
<!-- TODO <module name="MemberName"/> -->
<module name="MethodName"/>
<module name="PackageName"/>

View File

@ -27,7 +27,7 @@ final class AffineCipher {
static String decryptCipher(String cipher) {
String msg = "";
int a_inv = 0;
int aInv = 0;
int flag = 0;
// Find a^-1 (the multiplicative inverse of a
@ -38,7 +38,7 @@ final class AffineCipher {
// Check if (a*i)%26 == 1,
// then i will be the multiplicative inverse of a
if (flag == 1) {
a_inv = i;
aInv = i;
}
}
for (int i = 0; i < cipher.length(); i++) {
@ -46,7 +46,7 @@ final class AffineCipher {
{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');
msg = msg + (char) (((aInv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
} else { // else simply append space character
msg += cipher.charAt(i);
}

View File

@ -81,16 +81,16 @@ public class DES {
}
String[] subKeys = new String[16];
String initialPermutedKey = permutedKey.toString();
String C0 = initialPermutedKey.substring(0, 28);
String D0 = initialPermutedKey.substring(28);
String c0 = initialPermutedKey.substring(0, 28);
String d0 = initialPermutedKey.substring(28);
// 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
D0 = Dn;
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
d0 = dN;
}
// Let us shrink the keys to 48 bits (well, characters here) using pc2
@ -169,18 +169,18 @@ public class DES {
for (i = 0; i < 64; i++) {
permutedMessage.append(message.charAt(IP[i] - 1));
}
String L0 = permutedMessage.substring(0, 32);
String R0 = permutedMessage.substring(32);
String e0 = permutedMessage.substring(0, 32);
String f0 = permutedMessage.substring(32);
// Iterate 16 times
for (i = 0; i < 16; i++) {
String Ln = R0; // Previous Right block
String Rn = xOR(L0, feistel(R0, keys[i]));
L0 = Ln;
R0 = Rn;
String eN = f0; // Previous Right block
String fN = xOR(e0, feistel(f0, keys[i]));
e0 = eN;
f0 = fN;
}
String combinedBlock = R0 + L0; // Reverse the 16th block
String combinedBlock = f0 + e0; // Reverse the 16th block
permutedMessage.setLength(0);
for (i = 0; i < 64; i++) {
permutedMessage.append(combinedBlock.charAt(IP_INVERSE[i] - 1));

View File

@ -35,7 +35,7 @@ public final class HillCipher {
validateDeterminant(keyMatrix, matrixSize);
int[][] messageVector = new int[matrixSize][1];
String CipherText = "";
String cipherText = "";
int[][] cipherMatrix = new int[matrixSize][1];
int j = 0;
while (j < message.length()) {
@ -60,10 +60,10 @@ public final class HillCipher {
cipherMatrix[i][0] = cipherMatrix[i][0] % 26;
}
for (i = 0; i < matrixSize; i++) {
CipherText += (char) (cipherMatrix[i][0] + 65);
cipherText += (char) (cipherMatrix[i][0] + 65);
}
}
System.out.println("Ciphertext: " + CipherText);
System.out.println("Ciphertext: " + cipherText);
}
// Following function decrypts a message
@ -84,7 +84,7 @@ public final class HillCipher {
// solving for the required plaintext message
int[][] messageVector = new int[n][1];
String PlainText = "";
String plainText = "";
int[][] plainMatrix = new int[n][1];
int j = 0;
while (j < message.length()) {
@ -109,10 +109,10 @@ public final class HillCipher {
plainMatrix[i][0] = plainMatrix[i][0] % 26;
}
for (i = 0; i < n; i++) {
PlainText += (char) (plainMatrix[i][0] + 65);
plainText += (char) (plainMatrix[i][0] + 65);
}
}
System.out.println("Plaintext: " + PlainText);
System.out.println("Plaintext: " + plainText);
}
// Determinant calculator

View File

@ -20,20 +20,20 @@ public final class HexaDecimalToDecimal {
// Main method gets the hexadecimal input from user and converts it into Decimal output.
public static void main(String[] args) {
String hexa_Input;
int dec_output;
String hexaInput;
int decOutput;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Hexadecimal Number : ");
hexa_Input = scan.nextLine();
hexaInput = scan.nextLine();
// convert hexadecimal to decimal
dec_output = getHexaToDec(hexa_Input);
decOutput = getHexaToDec(hexaInput);
/*
Pass the string to the getHexaToDec function
and it returns the decimal form in the variable dec_output.
and it returns the decimal form in the variable decOutput.
*/
System.out.println("Number in Decimal: " + dec_output);
System.out.println("Number in Decimal: " + decOutput);
scan.close();
}
}

View File

@ -54,23 +54,23 @@ public final class BipartiteGrapfDFS {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine().trim());
while (t-- > 0) {
String[] S = read.readLine().trim().split(" ");
int V = Integer.parseInt(S[0]);
int E = Integer.parseInt(S[1]);
String[] str1 = read.readLine().trim().split(" ");
int numVertices = Integer.parseInt(str1[0]);
int numEdges = Integer.parseInt(str1[1]);
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < V; i++) {
for (int i = 0; i < numVertices; i++) {
adj.add(new ArrayList<>());
}
for (int i = 0; i < E; i++) {
String[] s = read.readLine().trim().split(" ");
int u = Integer.parseInt(s[0]);
int v = Integer.parseInt(s[1]);
adj.get(u).add(v);
adj.get(v).add(u);
for (int i = 0; i < numEdges; i++) {
String[] str2 = read.readLine().trim().split(" ");
int vertexU = Integer.parseInt(str2[0]);
int vertexV = Integer.parseInt(str2[1]);
adj.get(vertexU).add(vertexV);
adj.get(vertexV).add(vertexU);
}
boolean ans = isBipartite(V, adj);
boolean ans = isBipartite(numVertices, adj);
if (ans) {
System.out.println("YES");
} else {

View File

@ -8,18 +8,18 @@ class dijkstras {
int k = 9;
int minDist(int[] dist, Boolean[] Set) {
int minDist(int[] dist, Boolean[] set) {
int min = Integer.MAX_VALUE;
int min_index = -1;
int minIndex = -1;
for (int r = 0; r < k; r++) {
if (!Set[r] && dist[r] <= min) {
if (!set[r] && dist[r] <= min) {
min = dist[r];
min_index = r;
minIndex = r;
}
}
return min_index;
return minIndex;
}
void print(int[] dist) {
@ -31,22 +31,22 @@ class dijkstras {
void dijkstra(int[][] graph, int src) {
int[] dist = new int[k];
Boolean[] Set = new Boolean[k];
Boolean[] set = new Boolean[k];
for (int i = 0; i < k; i++) {
dist[i] = Integer.MAX_VALUE;
Set[i] = Boolean.FALSE;
set[i] = Boolean.FALSE;
}
dist[src] = 0;
for (int c = 0; c < k - 1; c++) {
int u = minDist(dist, Set);
int u = minDist(dist, set);
Set[u] = Boolean.TRUE;
set[u] = Boolean.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];
}
}

View File

@ -15,16 +15,16 @@ class PrimMST {
int minKey(int[] key, Boolean[] mstSet) {
// Initialize min value
int min = Integer.MAX_VALUE;
int min_index = -1;
int minIndex = -1;
for (int v = 0; v < V; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
min_index = v;
minIndex = v;
}
}
return min_index;
return minIndex;
}
// A utility function to print the constructed MST stored in

View File

@ -11,7 +11,7 @@ public final class Main {
int key;
HashMap h = new HashMap(7);
Scanner In = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter your Choice :");
@ -20,18 +20,18 @@ public final class Main {
System.out.println("3. Print Table");
System.out.println("4. Exit");
choice = In.nextInt();
choice = scan.nextInt();
switch (choice) {
case 1: {
System.out.println("Enter the Key: ");
key = In.nextInt();
key = scan.nextInt();
h.insertHash(key);
break;
}
case 2: {
System.out.println("Enter the Key delete: ");
key = In.nextInt();
key = scan.nextInt();
h.deleteHash(key);
break;
}
@ -41,7 +41,7 @@ public final class Main {
break;
}
case 4: {
In.close();
scan.close();
return;
}
default: {

View File

@ -11,7 +11,7 @@ public final class MainCuckooHashing {
int key;
HashMapCuckooHashing h = new HashMapCuckooHashing(7);
Scanner In = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("_________________________");
@ -24,18 +24,18 @@ public final class MainCuckooHashing {
System.out.println("6. Check load factor");
System.out.println("7. Rehash Current Table");
choice = In.nextInt();
choice = scan.nextInt();
switch (choice) {
case 1: {
System.out.println("Enter the Key: ");
key = In.nextInt();
key = scan.nextInt();
h.insertKey2HashTable(key);
break;
}
case 2: {
System.out.println("Enter the Key delete: ");
key = In.nextInt();
key = scan.nextInt();
h.deleteKeyFromHashTable(key);
break;
}
@ -45,12 +45,12 @@ public final class MainCuckooHashing {
break;
}
case 4: {
In.close();
scan.close();
return;
}
case 5: {
System.out.println("Enter the Key to find and print: ");
key = In.nextInt();
key = scan.nextInt();
System.out.println("Key: " + key + " is at index: " + h.findKeyInTable(key) + "\n");
break;
}

View File

@ -108,25 +108,25 @@ public class CursorLinkedList<T> {
Objects.requireNonNull(element);
// case element is in the head
T temp_element = cursorSpace[head].element;
int temp_next = cursorSpace[head].next;
if (temp_element.equals(element)) {
T tempElement = cursorSpace[head].element;
int tempNext = cursorSpace[head].next;
if (tempElement.equals(element)) {
free(head);
head = temp_next;
head = tempNext;
} else { // otherwise cases
int prev_index = head;
int current_index = cursorSpace[prev_index].next;
int prevIndex = head;
int currentIndex = cursorSpace[prevIndex].next;
while (current_index != -1) {
T current_element = cursorSpace[current_index].element;
if (current_element.equals(element)) {
cursorSpace[prev_index].next = cursorSpace[current_index].next;
free(current_index);
while (currentIndex != -1) {
T currentElement = cursorSpace[currentIndex].element;
if (currentElement.equals(element)) {
cursorSpace[prevIndex].next = cursorSpace[currentIndex].next;
free(currentIndex);
break;
}
prev_index = current_index;
current_index = cursorSpace[prev_index].next;
prevIndex = currentIndex;
currentIndex = cursorSpace[prevIndex].next;
}
}
@ -134,11 +134,11 @@ public class CursorLinkedList<T> {
}
private void free(int index) {
Node<T> os_node = cursorSpace[os];
int os_next = os_node.next;
Node<T> osNode = cursorSpace[os];
int osNext = osNode.next;
cursorSpace[os].next = index;
cursorSpace[index].element = null;
cursorSpace[index].next = os_next;
cursorSpace[index].next = osNext;
}
public void append(T element) {

View File

@ -23,17 +23,17 @@ public class ReverseKGroup {
Node prev = null;
int count1 = 0;
Node curr = head;
Node Next = null;
Node next = null;
while (curr != null && count1 < k) {
Next = curr.next;
next = curr.next;
curr.next = prev;
prev = curr;
curr = Next;
curr = next;
count1++;
}
if (Next != null) {
head.next = reverse(Next, count - k, k);
if (next != null) {
head.next = reverse(next, count - k, k);
}
return prev;
}

View File

@ -11,20 +11,20 @@ public class NodeStack<Item> {
* Entry point for the program.
*/
public static void main(String[] args) {
NodeStack<Integer> Stack = new NodeStack<Integer>();
NodeStack<Integer> stack = new NodeStack<Integer>();
Stack.push(3);
Stack.push(4);
Stack.push(5);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println("Testing :");
Stack.print(); // prints : 5 4 3
stack.print(); // prints : 5 4 3
Integer x = Stack.pop(); // x = 5
Stack.push(1);
Stack.push(8);
Integer y = Stack.peek(); // y = 8
Integer x = stack.pop(); // x = 5
stack.push(1);
stack.push(8);
Integer y = stack.peek(); // y = 8
System.out.println("Testing :");
Stack.print(); // prints : 8 1 4 3
stack.print(); // prints : 8 1 4 3
System.out.println("Testing :");
System.out.println("x : " + x);

View File

@ -112,10 +112,10 @@ public class AVLSimple {
private Node rightRotate(Node c) {
Node b = c.left;
Node T3 = b.right;
Node t3 = b.right;
b.right = c;
c.left = T3;
c.left = t3;
c.height = Math.max(height(c.left), height(c.right)) + 1;
b.height = Math.max(height(b.left), height(b.right)) + 1;
return b;
@ -123,10 +123,10 @@ public class AVLSimple {
private Node leftRotate(Node c) {
Node b = c.right;
Node T3 = b.left;
Node t3 = b.left;
b.left = c;
c.right = T3;
c.right = t3;
c.height = Math.max(height(c.left), height(c.right)) + 1;
b.height = Math.max(height(b.left), height(b.right)) + 1;
return b;

View File

@ -60,13 +60,13 @@ class Tree {
HashSet<Integer> set = new HashSet<>();
// Create a queue and add root to it
Queue<QItem> Q = new LinkedList<QItem>();
Q.add(new QItem(root, 0)); // Horizontal distance of root is 0
Queue<QItem> queue = new LinkedList<QItem>();
queue.add(new QItem(root, 0)); // Horizontal distance of root is 0
// Standard BFS or level order traversal loop
while (!Q.isEmpty()) {
while (!queue.isEmpty()) {
// Remove the front item and get its details
QItem qi = Q.remove();
QItem qi = queue.remove();
int hd = qi.hd;
TreeNode n = qi.node;
@ -79,10 +79,10 @@ class Tree {
// Enqueue left and right children of current node
if (n.left != null) {
Q.add(new QItem(n.left, hd - 1));
queue.add(new QItem(n.left, hd - 1));
}
if (n.right != null) {
Q.add(new QItem(n.right, hd + 1));
queue.add(new QItem(n.right, hd + 1));
}
}
}

View File

@ -10,9 +10,9 @@ public class SegmentTree {
public SegmentTree(int n, int[] arr) {
this.n = n;
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
int seg_size = 2 * (int) Math.pow(2, x) - 1;
int segSize = 2 * (int) Math.pow(2, x) - 1;
this.seg_t = new int[seg_size];
this.seg_t = new int[segSize];
this.arr = arr;
this.n = n;
constructTree(arr, 0, n - 1, 0);

View File

@ -18,124 +18,124 @@ package com.thealgorithms.divideandconquer;
public class StrassenMatrixMultiplication {
// Function to multiply matrices
public int[][] multiply(int[][] A, int[][] B) {
int n = A.length;
public int[][] multiply(int[][] a, int[][] b) {
int n = a.length;
int[][] R = new int[n][n];
int[][] mat = new int[n][n];
if (n == 1) {
R[0][0] = A[0][0] * B[0][0];
mat[0][0] = a[0][0] * b[0][0];
} else {
// Dividing Matrix into parts
// by storing sub-parts to variables
int[][] A11 = new int[n / 2][n / 2];
int[][] A12 = new int[n / 2][n / 2];
int[][] A21 = new int[n / 2][n / 2];
int[][] A22 = new int[n / 2][n / 2];
int[][] B11 = new int[n / 2][n / 2];
int[][] B12 = new int[n / 2][n / 2];
int[][] B21 = new int[n / 2][n / 2];
int[][] B22 = new int[n / 2][n / 2];
int[][] a11 = new int[n / 2][n / 2];
int[][] a12 = new int[n / 2][n / 2];
int[][] a21 = new int[n / 2][n / 2];
int[][] a22 = new int[n / 2][n / 2];
int[][] b11 = new int[n / 2][n / 2];
int[][] b12 = new int[n / 2][n / 2];
int[][] b21 = new int[n / 2][n / 2];
int[][] b22 = new int[n / 2][n / 2];
// Dividing matrix A into 4 parts
split(A, A11, 0, 0);
split(A, A12, 0, n / 2);
split(A, A21, n / 2, 0);
split(A, A22, n / 2, n / 2);
split(a, a11, 0, 0);
split(a, a12, 0, n / 2);
split(a, a21, n / 2, 0);
split(a, a22, n / 2, n / 2);
// Dividing matrix B into 4 parts
split(B, B11, 0, 0);
split(B, B12, 0, n / 2);
split(B, B21, n / 2, 0);
split(B, B22, n / 2, n / 2);
split(b, b11, 0, 0);
split(b, b12, 0, n / 2);
split(b, b21, n / 2, 0);
split(b, b22, n / 2, n / 2);
// Using Formulas as described in algorithm
// M1:=(A1+A3)×(B1+B2)
int[][] M1 = multiply(add(A11, A22), add(B11, B22));
// m1:=(A1+A3)×(B1+B2)
int[][] m1 = multiply(add(a11, a22), add(b11, b22));
// M2:=(A2+A4)×(B3+B4)
int[][] M2 = multiply(add(A21, A22), B11);
// m2:=(A2+A4)×(B3+B4)
int[][] m2 = multiply(add(a21, a22), b11);
// M3:=(A1A4)×(B1+A4)
int[][] M3 = multiply(A11, sub(B12, B22));
// m3:=(A1A4)×(B1+A4)
int[][] m3 = multiply(a11, sub(b12, b22));
// M4:=A1×(B2B4)
int[][] M4 = multiply(A22, sub(B21, B11));
// m4:=A1×(B2B4)
int[][] m4 = multiply(a22, sub(b21, b11));
// M5:=(A3+A4)×(B1)
int[][] M5 = multiply(add(A11, A12), B22);
// m5:=(A3+A4)×(B1)
int[][] m5 = multiply(add(a11, a12), b22);
// M6:=(A1+A2)×(B4)
int[][] M6 = multiply(sub(A21, A11), add(B11, B12));
// m6:=(A1+A2)×(B4)
int[][] m6 = multiply(sub(a21, a11), add(b11, b12));
// M7:=A4×(B3B1)
int[][] M7 = multiply(sub(A12, A22), add(B21, B22));
// m7:=A4×(B3B1)
int[][] m7 = multiply(sub(a12, a22), add(b21, b22));
// P:=M2+M3M6M7
int[][] C11 = add(sub(add(M1, M4), M5), M7);
// P:=m2+m3m6m7
int[][] c11 = add(sub(add(m1, m4), m5), m7);
// Q:=M4+M6
int[][] C12 = add(M3, M5);
// Q:=m4+m6
int[][] c12 = add(m3, m5);
// R:=M5+M7
int[][] C21 = add(M2, M4);
// mat:=m5+m7
int[][] c21 = add(m2, m4);
// S:=M1M3M4M5
int[][] C22 = add(sub(add(M1, M3), M2), M6);
// S:=m1m3m4m5
int[][] c22 = add(sub(add(m1, m3), m2), m6);
join(C11, R, 0, 0);
join(C12, R, 0, n / 2);
join(C21, R, n / 2, 0);
join(C22, R, n / 2, n / 2);
join(c11, mat, 0, 0);
join(c12, mat, 0, n / 2);
join(c21, mat, n / 2, 0);
join(c22, mat, n / 2, n / 2);
}
return R;
return mat;
}
// Function to subtract two matrices
public int[][] sub(int[][] A, int[][] B) {
int n = A.length;
public int[][] sub(int[][] a, int[][] b) {
int n = a.length;
int[][] C = new int[n][n];
int[][] c = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j] - B[i][j];
c[i][j] = a[i][j] - b[i][j];
}
}
return C;
return c;
}
// Function to add two matrices
public int[][] add(int[][] A, int[][] B) {
int n = A.length;
public int[][] add(int[][] a, int[][] b) {
int n = a.length;
int[][] C = new int[n][n];
int[][] c = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j] + B[i][j];
c[i][j] = a[i][j] + b[i][j];
}
}
return C;
return c;
}
// Function to split parent matrix into child matrices
public void split(int[][] P, int[][] C, int iB, int jB) {
for (int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++) {
for (int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++) {
C[i1][j1] = P[i2][j2];
public void split(int[][] p, int[][] c, int iB, int jB) {
for (int i1 = 0, i2 = iB; i1 < c.length; i1++, i2++) {
for (int j1 = 0, j2 = jB; j1 < c.length; j1++, j2++) {
c[i1][j1] = p[i2][j2];
}
}
}
// Function to join child matrices into (to) parent matrix
public void join(int[][] C, int[][] P, int iB, int jB) {
for (int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++) {
for (int j1 = 0, j2 = jB; j1 < C.length; j1++, j2++) {
P[i2][j2] = C[i1][j1];
public void join(int[][] c, int[][] p, int iB, int jB) {
for (int i1 = 0, i2 = iB; i1 < c.length; i1++, i2++) {
for (int j1 = 0, j2 = jB; j1 < c.length; j1++, j2++) {
p[i2][j2] = c[i1][j1];
}
}
}

View File

@ -32,8 +32,8 @@ public final class BruteForceKnapsack {
public static void main(String[] args) {
int[] val = new int[] {60, 100, 120};
int[] wt = new int[] {10, 20, 30};
int W = 50;
int w = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
System.out.println(knapSack(w, wt, val, n));
}
}

View File

@ -58,9 +58,9 @@ public final class CoinChange {
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (coin <= i) {
int sub_res = minimumCoins[i - coin];
if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i]) {
minimumCoins[i] = sub_res + 1;
int subRes = minimumCoins[i - coin];
if (subRes != Integer.MAX_VALUE && subRes + 1 < minimumCoins[i]) {
minimumCoins[i] = subRes + 1;
}
}
}

View File

@ -12,13 +12,13 @@ public final class KadaneAlgorithm {
public static boolean maxSum(int[] a, int predicted_answer) {
int sum = a[0];
int running_sum = 0;
int runningSum = 0;
for (int k : a) {
running_sum = running_sum + k;
runningSum = runningSum + k;
// running sum of all the indexs are stored
sum = Math.max(sum, running_sum);
sum = Math.max(sum, runningSum);
// the max is stored inorder to the get the maximum sum
if (running_sum < 0) running_sum = 0;
if (runningSum < 0) runningSum = 0;
// if running sum is negative then it is initialized to zero
}
// for-each loop is used to iterate over the array and find the maximum subarray sum

View File

@ -21,18 +21,18 @@ public final class LongestIncreasingSubsequence {
}
public static int lis(int[] array) {
int N = array.length;
if (N == 0) {
int len = array.length;
if (len == 0) {
return 0;
}
int[] tail = new int[N];
int[] tail = new int[len];
// always points empty slot in tail
int length = 1;
tail[0] = array[0];
for (int i = 1; i < N; i++) {
for (int i = 1; i < len; i++) {
// new smallest value
if (array[i] < tail[0]) {
tail[0] = array[i];

View File

@ -33,24 +33,24 @@ public final class PalindromicPartitioning {
int i;
int j;
int L; // different looping variables
int subLen; // different looping variables
// Every substring of length 1 is a palindrome
for (i = 0; i < len; i++) {
isPalindrome[i][i] = true;
}
/* L is substring length. Build the solution in bottom up manner by considering all
/* subLen is substring length. Build the solution in bottom up manner by considering all
* substrings of length starting from 2 to n. */
for (L = 2; L <= len; L++) {
// For substring of length L, set different possible starting indexes
for (i = 0; i < len - L + 1; i++) {
j = i + L - 1; // Ending index
// If L is 2, then we just need to
for (subLen = 2; subLen <= len; subLen++) {
// For substring of length subLen, set different possible starting indexes
for (i = 0; i < len - subLen + 1; i++) {
j = i + subLen - 1; // Ending index
// If subLen is 2, then we just need to
// compare two characters. Else need to
// check two corner characters and value
// of P[i+1][j-1]
if (L == 2) {
if (subLen == 2) {
isPalindrome[i][j] = (word.charAt(i) == word.charAt(j));
} else {
isPalindrome[i][j] = (word.charAt(i) == word.charAt(j)) && isPalindrome[i + 1][j - 1];

View File

@ -6,13 +6,13 @@ final class ShortestSuperSequence {
}
// Function to find length of the
// shortest supersequence of X and Y.
static int shortestSuperSequence(String X, String Y) {
int m = X.length();
int n = Y.length();
// shortest supersequence of x and y.
static int shortestSuperSequence(String x, String y) {
int m = x.length();
int n = y.length();
// find lcs
int l = lcs(X, Y, m, n);
int l = lcs(x, y, m, n);
// Result is sum of input string
// lengths - length of lcs
@ -20,39 +20,39 @@ final class ShortestSuperSequence {
}
// Returns length of LCS
// for X[0..m - 1], Y[0..n - 1]
static int lcs(String X, String Y, int m, int n) {
int[][] L = new int[m + 1][n + 1];
// for x[0..m - 1], y[0..n - 1]
static int lcs(String x, String y, int m, int n) {
int[][] lN = new int[m + 1][n + 1];
int i;
int j;
// Following steps build L[m + 1][n + 1]
// Following steps build lN[m + 1][n + 1]
// in bottom up fashion. Note that
// L[i][j] contains length of LCS
// of X[0..i - 1]and Y[0..j - 1]
// lN[i][j] contains length of lNCS
// of x[0..i - 1]and y[0..j - 1]
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
L[i][j] = 0;
} else if (X.charAt(i - 1) == Y.charAt(j - 1)) {
L[i][j] = L[i - 1][j - 1] + 1;
lN[i][j] = 0;
} else if (x.charAt(i - 1) == y.charAt(j - 1)) {
lN[i][j] = lN[i - 1][j - 1] + 1;
} else {
L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
lN[i][j] = Math.max(lN[i - 1][j], lN[i][j - 1]);
}
}
}
// L[m][n] contains length of LCS
// for X[0..n - 1] and Y[0..m - 1]
return L[m][n];
// lN[m][n] contains length of LCS
// for x[0..n - 1] and y[0..m - 1]
return lN[m][n];
}
// Driver code
public static void main(String[] args) {
String X = "AGGTAB";
String Y = "GXTXAYB";
String x = "AGGTAB";
String y = "GXTXAYB";
System.out.println("Length of the shortest "
+ "supersequence is " + shortestSuperSequence(X, Y));
+ "supersequence is " + shortestSuperSequence(x, y));
}
}

View File

@ -22,7 +22,7 @@ public final class CrossCorrelation {
public static double[] crossCorrelation(double[] x, double[] y) {
// The result signal's length is the sum of the input signals' lengths minus 1
double[] result = new double[x.length + y.length - 1];
int N = result.length;
int n = result.length;
/*
To find the cross-correlation between 2 discrete signals x & y, we start by "placing" the second signal
@ -60,13 +60,13 @@ public final class CrossCorrelation {
To find the result[i] value for each i:0->N-1, the positions of x-signal in which the 2 signals meet
To find the result[i] value for each i:0->n-1, the positions of x-signal in which the 2 signals meet
are calculated: kMin<=k<=kMax.
The variable 'yStart' indicates the starting index of y in each sum calculation.
The variable 'count' increases the index of y-signal by 1, to move to the next value.
*/
int yStart = y.length;
for (int i = 0; i < N; i++) {
for (int i = 0; i < n; i++) {
result[i] = 0;
int kMin = Math.max(i - (y.length - 1), 0);

View File

@ -186,16 +186,16 @@ public final class FFT {
public static ArrayList<Complex> fft(ArrayList<Complex> x, boolean inverse) {
/* Pad the signal with zeros if necessary */
paddingPowerOfTwo(x);
int N = x.size();
int log2N = findLog2(N);
x = fftBitReversal(N, log2N, x);
int n = x.size();
int log2n = findLog2(n);
x = fftBitReversal(n, log2n, x);
int direction = inverse ? -1 : 1;
/* Main loop of the algorithm */
for (int len = 2; len <= N; len *= 2) {
for (int len = 2; len <= n; len *= 2) {
double angle = -2 * Math.PI / len * direction;
Complex wlen = new Complex(Math.cos(angle), Math.sin(angle));
for (int i = 0; i < N; i += len) {
for (int i = 0; i < n; i += len) {
Complex w = new Complex(1, 0);
for (int j = 0; j < len / 2; j++) {
Complex u = x.get(i + j);
@ -206,24 +206,24 @@ public final class FFT {
}
}
}
x = inverseFFT(N, inverse, x);
x = inverseFFT(n, inverse, x);
return x;
}
/* Find the log2(N) */
public static int findLog2(int N) {
int log2N = 0;
while ((1 << log2N) < N) {
log2N++;
/* Find the log2(n) */
public static int findLog2(int n) {
int log2n = 0;
while ((1 << log2n) < n) {
log2n++;
}
return log2N;
return log2n;
}
/* Swap the values of the signal with bit-reversal method */
public static ArrayList<Complex> fftBitReversal(int N, int log2N, ArrayList<Complex> x) {
public static ArrayList<Complex> fftBitReversal(int n, int log2n, ArrayList<Complex> x) {
int reverse;
for (int i = 0; i < N; i++) {
reverse = reverseBits(i, log2N);
for (int i = 0; i < n; i++) {
reverse = reverseBits(i, log2n);
if (i < reverse) {
Collections.swap(x, i, reverse);
}
@ -231,12 +231,12 @@ public final class FFT {
return x;
}
/* Divide by N if we want the inverse FFT */
public static ArrayList<Complex> inverseFFT(int N, boolean inverse, ArrayList<Complex> x) {
/* Divide by n if we want the inverse FFT */
public static ArrayList<Complex> inverseFFT(int n, boolean inverse, ArrayList<Complex> x) {
if (inverse) {
for (int i = 0; i < x.size(); i++) {
Complex z = x.get(i);
x.set(i, z.divide(N));
x.set(i, z.divide(n));
}
}
return x;
@ -247,7 +247,7 @@ public final class FFT {
* FFT algorithm.
*
* <p>
* 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
*
* <p>
@ -255,14 +255,14 @@ public final class FFT {
* https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/
*
* @param num The integer you want to reverse its bits.
* @param log2N The number of bits you want to reverse.
* @param log2n The number of bits you want to reverse.
* @return The reversed number
*/
private static int reverseBits(int num, int log2N) {
private static int reverseBits(int num, int log2n) {
int reversed = 0;
for (int i = 0; i < log2N; i++) {
for (int i = 0; i < log2n; i++) {
if ((num & (1 << i)) != 0) {
reversed |= 1 << (log2N - 1 - i);
reversed |= 1 << (log2n - 1 - i);
}
}
return reversed;

View File

@ -26,8 +26,8 @@ public final class FFTBluestein {
* @param inverse True if you want to find the inverse FFT.
*/
public static void fftBluestein(ArrayList<FFT.Complex> 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<FFT.Complex> an = new ArrayList<>();
ArrayList<FFT.Complex> bn = new ArrayList<>();
@ -38,32 +38,32 @@ public final class FFTBluestein {
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<FFT.Complex> 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));
}
}
}

View File

@ -26,24 +26,24 @@ final class KeithNumber {
}
// 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

View File

@ -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)) {

View File

@ -18,32 +18,32 @@ public final class MagicSquare {
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();
}

View File

@ -19,19 +19,19 @@ public class SimpsonIntegration {
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 class SimpsonIntegration {
*
* @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<Integer, Double> 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

View File

@ -111,15 +111,15 @@ public class VectorCrossProduct {
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);
}
}

View File

@ -21,27 +21,27 @@ public final class InsertDeleteInArray {
// 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++) {

View File

@ -28,20 +28,20 @@ class PageRank {
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 @@ class PageRank {
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

View File

@ -30,18 +30,18 @@ public final class ReturnSubsequence {
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;
}

View File

@ -10,27 +10,27 @@ public final class RootPrecision {
// 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;

View File

@ -86,16 +86,16 @@ final class Sudoku {
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 @@ final class Sudoku {
{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");
}

View File

@ -3,25 +3,25 @@ package com.thealgorithms.searches;
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 @@ class KMPSearch {
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 @@ class KMPSearch {
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;

View File

@ -18,7 +18,7 @@ public final class 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 @@ public final class OrderAgnosticBinarySearch {
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

View File

@ -6,9 +6,9 @@ public final class 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 @@ public final class DNFSort {
}
/* 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 @@ public final class DNFSort {
/*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);
}
}

View File

@ -11,10 +11,10 @@ public class SwapSort implements SortAlgorithm {
@Override
public <T extends Comparable<T>> 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) {

View File

@ -8,13 +8,13 @@ public final class 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";

View File

@ -67,24 +67,24 @@ final class WordLadder {
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++;

View File

@ -13,20 +13,20 @@ final class zigZagPattern {
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;
}
}

View File

@ -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);
}
}

View File

@ -15,11 +15,11 @@ public class OptimalJobSchedulingTest {
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 class OptimalJobSchedulingTest {
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 class OptimalJobSchedulingTest {
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 class OptimalJobSchedulingTest {
{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();