Format code with prettier (#3375)

This commit is contained in:
acbin 2022-10-03 17:23:00 +08:00 committed by GitHub
parent 32b9b11ed5
commit e96f567bfc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
464 changed files with 11483 additions and 6189 deletions

View File

@ -22,7 +22,9 @@ public class IIRFilter {
*/ */
public IIRFilter(int order) throws IllegalArgumentException { public IIRFilter(int order) throws IllegalArgumentException {
if (order < 1) { if (order < 1) {
throw new IllegalArgumentException("order must be greater than zero"); throw new IllegalArgumentException(
"order must be greater than zero"
);
} }
this.order = order; this.order = order;
@ -45,17 +47,24 @@ public class IIRFilter {
* @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is * @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is
* not of size {@code order}, or if {@code aCoeffs[0]} is 0.0 * not of size {@code order}, or if {@code aCoeffs[0]} is 0.0
*/ */
public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException { public void setCoeffs(double[] aCoeffs, double[] bCoeffs)
throws IllegalArgumentException {
if (aCoeffs.length != order) { if (aCoeffs.length != order) {
throw new IllegalArgumentException("aCoeffs must be of size " + order + ", got " + aCoeffs.length); throw new IllegalArgumentException(
"aCoeffs must be of size " + order + ", got " + aCoeffs.length
);
} }
if (aCoeffs[0] == 0.0) { if (aCoeffs[0] == 0.0) {
throw new IllegalArgumentException("aCoeffs.get(0) must not be zero"); throw new IllegalArgumentException(
"aCoeffs.get(0) must not be zero"
);
} }
if (bCoeffs.length != order) { if (bCoeffs.length != order) {
throw new IllegalArgumentException("bCoeffs must be of size " + order + ", got " + bCoeffs.length); throw new IllegalArgumentException(
"bCoeffs must be of size " + order + ", got " + bCoeffs.length
);
} }
for (int i = 0; i <= order; i++) { for (int i = 0; i <= order; i++) {
@ -75,7 +84,8 @@ public class IIRFilter {
// Process // Process
for (int i = 1; i <= order; i++) { for (int i = 1; i <= order; i++) {
result += (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]); result +=
(coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]);
} }
result = (result + coeffsB[0] * sample) / coeffsA[0]; result = (result + coeffsB[0] * sample) / coeffsA[0];

View File

@ -7,7 +7,9 @@ import java.util.*;
* @author Alan Piao (https://github.com/cpiao3) * @author Alan Piao (https://github.com/cpiao3)
*/ */
public class Combination { public class Combination {
private static int length; private static int length;
/** /**
* Find all combinations of given array using backtracking * Find all combinations of given array using backtracking
* @param arr the array. * @param arr the array.
@ -26,6 +28,7 @@ public class Combination {
backtracking(array, 0, new TreeSet<T>(), result); backtracking(array, 0, new TreeSet<T>(), result);
return result; return result;
} }
/** /**
* Backtrack all possible combinations of a given array * Backtrack all possible combinations of a given array
* @param arr the array. * @param arr the array.
@ -34,7 +37,12 @@ public class Combination {
* @param result the list contains all combination. * @param result the list contains all combination.
* @param <T> the type of elements in the array. * @param <T> the type of elements in the array.
*/ */
private static <T> void backtracking(T[] arr, int index, TreeSet<T> currSet, List<TreeSet<T>> result) { private static <T> void backtracking(
T[] arr,
int index,
TreeSet<T> currSet,
List<TreeSet<T>> result
) {
if (index + length - currSet.size() > arr.length) return; if (index + length - currSet.size() > arr.length) return;
if (length - 1 == currSet.size()) { if (length - 1 == currSet.size()) {
for (int i = index; i < arr.length; i++) { for (int i = index; i < arr.length; i++) {

View File

@ -14,11 +14,9 @@ public class FloodFill {
* @param y The y co-ordinate of which color is to be obtained * @param y The y co-ordinate of which color is to be obtained
*/ */
public static int getPixel(int[][] image, int x, int y) { public static int getPixel(int[][] image, int x, int y) {
return image[x][y];
return image[x][y]; }
}
/** /**
* Put the color at the given co-odrinates of a 2D image * Put the color at the given co-odrinates of a 2D image
@ -27,12 +25,9 @@ public class FloodFill {
* @param x The x co-ordinate at which color is to be filled * @param x The x co-ordinate at which color is to be filled
* @param y The y co-ordinate at which color is to be filled * @param y The y co-ordinate at which color is to be filled
*/ */
public static void putPixel(int[][] image, int x, int y, int newColor) { public static void putPixel(int[][] image, int x, int y, int newColor) {
image[x][y] = newColor;
image[x][y] = newColor; }
}
/** /**
* Fill the 2D image with new color * Fill the 2D image with new color
@ -44,26 +39,29 @@ public class FloodFill {
* @param oldColor The old color which is to be replaced in the image * @param oldColor The old color which is to be replaced in the image
* @return * @return
*/ */
public static void floodFill(int[][] image, int x, int y, int newColor, int oldColor) { public static void floodFill(
int[][] image,
int x,
int y,
int newColor,
int oldColor
) {
if (x < 0 || x >= image.length) return;
if (y < 0 || y >= image[x].length) return;
if (getPixel(image, x, y) != oldColor) return;
if(x < 0 || x >= image.length) return; putPixel(image, x, y, newColor);
if(y < 0 || y >= image[x].length) return;
if(getPixel(image, x, y) != oldColor) return;
putPixel(image, x, y, newColor); /* Recursively check for horizontally & vertically adjacent coordinates */
floodFill(image, x + 1, y, newColor, oldColor);
/* Recursively check for horizontally & vertically adjacent coordinates */ floodFill(image, x - 1, y, newColor, oldColor);
floodFill(image, x + 1, y, newColor, oldColor); floodFill(image, x, y + 1, newColor, oldColor);
floodFill(image, x - 1, y, newColor, oldColor); floodFill(image, x, y - 1, newColor, oldColor);
floodFill(image, x, y + 1, newColor, oldColor);
floodFill(image, x, y - 1, newColor, oldColor);
/* Recursively check for diagonally adjacent coordinates */
floodFill(image, x + 1, y - 1, newColor, oldColor);
floodFill(image, x - 1, y + 1, newColor, oldColor);
floodFill(image, x + 1, y + 1, newColor, oldColor);
floodFill(image, x - 1, y - 1, newColor, oldColor);
}
/* Recursively check for diagonally adjacent coordinates */
floodFill(image, x + 1, y - 1, newColor, oldColor);
floodFill(image, x - 1, y + 1, newColor, oldColor);
floodFill(image, x + 1, y + 1, newColor, oldColor);
floodFill(image, x - 1, y - 1, newColor, oldColor);
}
} }

View File

@ -25,10 +25,19 @@ import java.util.*;
*/ */
public class KnightsTour { public class KnightsTour {
private final static int base = 12; private static final int base = 12;
private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}}; // Possible moves by knight on chess private static final int[][] moves = {
private static int[][] grid; // chess grid { 1, -2 },
private static int total; // total squares in chess { 2, -1 },
{ 2, 1 },
{ 1, 2 },
{ -1, 2 },
{ -2, 1 },
{ -2, -1 },
{ -1, -2 },
}; // Possible moves by knight on chess
private static int[][] grid; // chess grid
private static int total; // total squares in chess
public static void main(String[] args) { public static void main(String[] args) {
grid = new int[base][base]; grid = new int[base][base];
@ -52,7 +61,6 @@ public class KnightsTour {
} else { } else {
System.out.println("no result"); System.out.println("no result");
} }
} }
// Return True when solvable // Return True when solvable
@ -67,17 +75,23 @@ public class KnightsTour {
return false; return false;
} }
Collections.sort(neighbor, new Comparator<int[]>() { Collections.sort(
public int compare(int[] a, int[] b) { neighbor,
return a[2] - b[2]; new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[2] - b[2];
}
} }
}); );
for (int[] nb : neighbor) { for (int[] nb : neighbor) {
row = nb[0]; row = nb[0];
column = nb[1]; column = nb[1];
grid[row][column] = count; grid[row][column] = count;
if (!orphanDetected(count, row, column) && solve(row, column, count + 1)) { if (
!orphanDetected(count, row, column) &&
solve(row, column, count + 1)
) {
return true; return true;
} }
grid[row][column] = 0; grid[row][column] = 0;
@ -95,7 +109,7 @@ public class KnightsTour {
int y = m[1]; int y = m[1];
if (grid[row + y][column + x] == 0) { if (grid[row + y][column + x] == 0) {
int num = countNeighbors(row + y, column + x); int num = countNeighbors(row + y, column + x);
neighbour.add(new int[]{row + y, column + x, num}); neighbour.add(new int[] { row + y, column + x, num });
} }
} }
return neighbour; return neighbour;

View File

@ -2,157 +2,154 @@ package com.thealgorithms.backtracking;
public class MazeRecursion { public class MazeRecursion {
public static void mazeRecursion() { public static void mazeRecursion() {
// First create a 2 dimensions array to mimic a maze map // First create a 2 dimensions array to mimic a maze map
int[][] map = new int[8][7]; int[][] map = new int[8][7];
int[][] map2 = new int[8][7]; int[][] map2 = new int[8][7];
// We use 1 to indicate wall // We use 1 to indicate wall
// Set the ceiling and floor to 1 // Set the ceiling and floor to 1
for (int i = 0; i < 7; i++) { for (int i = 0; i < 7; i++) {
map[0][i] = 1; map[0][i] = 1;
map[7][i] = 1; map[7][i] = 1;
} }
// Then we set the left and right wall to 1 // Then we set the left and right wall to 1
for (int i = 0; i < 8; i++) { for (int i = 0; i < 8; i++) {
map[i][0] = 1; map[i][0] = 1;
map[i][6] = 1; map[i][6] = 1;
} }
// Now we have created a maze with its wall initialized // Now we have created a maze with its wall initialized
// Here we set the obstacle // Here we set the obstacle
map[3][1] = 1; map[3][1] = 1;
map[3][2] = 1; map[3][2] = 1;
// Print the current map // Print the current map
System.out.println("The condition of the map "); System.out.println("The condition of the map ");
for (int i = 0; i < 8; i++) { for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) { for (int j = 0; j < 7; j++) {
System.out.print(map[i][j] + " "); System.out.print(map[i][j] + " ");
} }
System.out.println(); System.out.println();
} }
// clone another map for setWay2 method // clone another map for setWay2 method
for (int i = 0; i < map.length; i++) { for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) { for (int j = 0; j < map[i].length; j++) {
map2[i][j] = map[i][j]; map2[i][j] = map[i][j];
} }
} }
// By using recursive backtracking to let your ball(target) find its way in the // By using recursive backtracking to let your ball(target) find its way in the
// maze // maze
// The first parameter is the map // The first parameter is the map
// Second parameter is x coordinate of your target // Second parameter is x coordinate of your target
// Thrid parameter is the y coordinate of your target // Thrid parameter is the y coordinate of your target
setWay(map, 1, 1); setWay(map, 1, 1);
setWay2(map2, 1, 1); setWay2(map2, 1, 1);
// Print out the new map1, with the ball footprint // Print out the new map1, with the ball footprint
System.out.println("After the ball goes through the map1show the current map1 condition"); System.out.println(
for (int i = 0; i < 8; i++) { "After the ball goes through the map1show the current map1 condition"
for (int j = 0; j < 7; j++) { );
System.out.print(map[i][j] + " "); for (int i = 0; i < 8; i++) {
} for (int j = 0; j < 7; j++) {
System.out.println(); System.out.print(map[i][j] + " ");
} }
System.out.println();
}
// Print out the new map2, with the ball footprint // Print out the new map2, with the ball footprint
System.out.println("After the ball goes through the map2show the current map2 condition"); System.out.println(
for (int i = 0; i < 8; i++) { "After the ball goes through the map2show the current map2 condition"
for (int j = 0; j < 7; j++) { );
System.out.print(map2[i][j] + " "); for (int i = 0; i < 8; i++) {
} for (int j = 0; j < 7; j++) {
System.out.println(); System.out.print(map2[i][j] + " ");
} }
} System.out.println();
}
}
// Using recursive path finding to help the ball find its way in the maze
// Description
// 1. map (means the maze)
// 2. i, j (means the initial coordinate of the ball in the maze)
// 3. if the ball can reach the end of maze, that is position of map[6][5],
// means the we have found a path for the ball
// 4. Additional Information 0 in the map[i][j] means the ball has not gone
// through this position, 1 means the wall, 2 means the path is feasible, 3
// means the ball has gone through the path but this path is dead end
// 5. We will need strategy for the ball to pass through the maze for example:
// Down -> Right -> Up -> Left, if the path doesn't work, then backtrack
/**
*
* @Description
* @author OngLipWei
* @date Jun 23, 202111:36:14 AM
* @param map The maze
* @param i x coordinate of your ball(target)
* @param j y coordinate of your ball(target)
* @return If we did find a path for the ballreturn trueelse false
*/
public static boolean setWay(int[][] map, int i, int j) {
if (map[6][5] == 2) { // means the ball find its path, ending condition
return true;
}
if (map[i][j] == 0) { // if the ball haven't gone through this point
// then the ball follows the move strategy : down -> right -> up -> left
map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first
if (setWay(map, i + 1, j)) { // go down
return true;
} else if (setWay(map, i, j + 1)) { // go right
return true;
} else if (setWay(map, i - 1, j)) { // go up
return true;
} else if (setWay(map, i, j - 1)) { // go left
return true;
} else {
// means that the current point is the dead end, the ball cannot proceed, set
// the current point to 3 and return false, the backtraking will start, it will
// go to the previous step and check for feasible path again
map[i][j] = 3;
return false;
}
} else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the
// ball cannot hit the wall, cannot go to the path that has gone though before,
// and cannot head to deadend.
return false;
}
}
// Here is another move strategy for the ball: up->right->down->left
// Using recursive path finding to help the ball find its way in the maze public static boolean setWay2(int[][] map, int i, int j) {
// Description if (map[6][5] == 2) { // means the ball find its path, ending condition
// 1. map (means the maze) return true;
// 2. i, j (means the initial coordinate of the ball in the maze) }
// 3. if the ball can reach the end of maze, that is position of map[6][5], if (map[i][j] == 0) { // if the ball haven't gone through this point
// means the we have found a path for the ball // then the ball follows the move strategy : up->right->down->left
// 4. Additional Information 0 in the map[i][j] means the ball has not gone map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first
// through this position, 1 means the wall, 2 means the path is feasible, 3 if (setWay2(map, i - 1, j)) { // go up
// means the ball has gone through the path but this path is dead end return true;
// 5. We will need strategy for the ball to pass through the maze for example: } else if (setWay2(map, i, j + 1)) { // go right
// Down -> Right -> Up -> Left, if the path doesn't work, then backtrack return true;
/** } else if (setWay2(map, i + 1, j)) { // go down
* return true;
* @Description } else if (setWay2(map, i, j - 1)) { // go left
* @author OngLipWei return true;
* @date Jun 23, 202111:36:14 AM } else {
* @param map The maze // means that the current point is the dead end, the ball cannot proceed, set
* @param i x coordinate of your ball(target) // the current point to 3 and return false, the backtraking will start, it will
* @param j y coordinate of your ball(target) // go to the previous step and check for feasible path again
* @return If we did find a path for the ballreturn trueelse false map[i][j] = 3;
*/ return false;
public static boolean setWay(int[][] map, int i, int j) { }
if (map[6][5] == 2) {// means the ball find its path, ending condition } else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the
return true; // ball cannot hit the wall, cannot go to the path that has gone though before,
} // and cannot head to deadend.
if (map[i][j] == 0) { // if the ball haven't gone through this point return false;
// then the ball follows the move strategy : down -> right -> up -> left }
map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first }
if (setWay(map, i + 1, j)) { // go down
return true;
} else if (setWay(map, i, j + 1)) { // go right
return true;
} else if (setWay(map, i - 1, j)) { // go up
return true;
} else if (setWay(map, i, j - 1)) { // go left
return true;
} else {
// means that the current point is the dead end, the ball cannot proceed, set
// the current point to 3 and return false, the backtraking will start, it will
// go to the previous step and check for feasible path again
map[i][j] = 3;
return false;
}
} else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the
// ball cannot hit the wall, cannot go to the path that has gone though before,
// and cannot head to deadend.
return false;
}
}
// Here is another move strategy for the ball: up->right->down->left
public static boolean setWay2(int[][] map, int i, int j) {
if (map[6][5] == 2) {// means the ball find its path, ending condition
return true;
}
if (map[i][j] == 0) { // if the ball haven't gone through this point
// then the ball follows the move strategy : up->right->down->left
map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first
if (setWay2(map, i - 1, j)) { // go up
return true;
} else if (setWay2(map, i, j + 1)) { // go right
return true;
} else if (setWay2(map, i + 1, j)) { // go down
return true;
} else if (setWay2(map, i, j - 1)) { // go left
return true;
} else {
// means that the current point is the dead end, the ball cannot proceed, set
// the current point to 3 and return false, the backtraking will start, it will
// go to the previous step and check for feasible path again
map[i][j] = 3;
return false;
}
} else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the
// ball cannot hit the wall, cannot go to the path that has gone though before,
// and cannot head to deadend.
return false;
}
}
} }

View File

@ -47,7 +47,14 @@ public class NQueens {
List<List<String>> arrangements = new ArrayList<List<String>>(); List<List<String>> arrangements = new ArrayList<List<String>>();
getSolution(queens, arrangements, new int[queens], 0); getSolution(queens, arrangements, new int[queens], 0);
if (arrangements.isEmpty()) { if (arrangements.isEmpty()) {
System.out.println("There is no way to place " + queens + " queens on board of size " + queens + "x" + queens); System.out.println(
"There is no way to place " +
queens +
" queens on board of size " +
queens +
"x" +
queens
);
} else { } else {
System.out.println("Arrangement for placing " + queens + " queens"); System.out.println("Arrangement for placing " + queens + " queens");
} }
@ -65,7 +72,12 @@ public class NQueens {
* @param columns: columns[i] = rowId where queen is placed in ith column. * @param columns: columns[i] = rowId where queen is placed in ith column.
* @param columnIndex: This is the column in which queen is being placed * @param columnIndex: This is the column in which queen is being placed
*/ */
private static void getSolution(int boardSize, List<List<String>> solutions, int[] columns, int columnIndex) { private static void getSolution(
int boardSize,
List<List<String>> solutions,
int[] columns,
int columnIndex
) {
if (columnIndex == boardSize) { if (columnIndex == boardSize) {
// this means that all queens have been placed // this means that all queens have been placed
List<String> sol = new ArrayList<String>(); List<String> sol = new ArrayList<String>();
@ -99,7 +111,11 @@ public class NQueens {
* @param columnIndex: column in which queen is being placed * @param columnIndex: column in which queen is being placed
* @return true: if queen can be placed safely false: otherwise * @return true: if queen can be placed safely false: otherwise
*/ */
private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) { private static boolean isPlacedCorrectly(
int[] columns,
int rowIndex,
int columnIndex
) {
for (int i = 0; i < columnIndex; i++) { for (int i = 0; i < columnIndex; i++) {
int diff = Math.abs(columns[i] - rowIndex); int diff = Math.abs(columns[i] - rowIndex);
if (diff == 0 || columnIndex - i == diff) { if (diff == 0 || columnIndex - i == diff) {

View File

@ -8,6 +8,7 @@ import java.util.List;
* @author Alan Piao (https://github.com/cpiao3) * @author Alan Piao (https://github.com/cpiao3)
*/ */
public class Permutation { public class Permutation {
/** /**
* Find all permutations of given array using backtracking * Find all permutations of given array using backtracking
* @param arr the array. * @param arr the array.
@ -20,6 +21,7 @@ public class Permutation {
backtracking(array, 0, result); backtracking(array, 0, result);
return result; return result;
} }
/** /**
* Backtrack all possible orders of a given array * Backtrack all possible orders of a given array
* @param arr the array. * @param arr the array.
@ -37,6 +39,7 @@ public class Permutation {
swap(index, i, arr); swap(index, i, arr);
} }
} }
/** /**
* Swap two element for a given array * Swap two element for a given array
* @param a first index * @param a first index

View File

@ -18,10 +18,17 @@ public class PowerSum {
PowerSum ps = new PowerSum(); PowerSum ps = new PowerSum();
int count = ps.powSum(N, X); int count = ps.powSum(N, X);
//printing the answer. //printing the answer.
System.out.println("Number of combinations of different natural number's raised to " + X + " having sum " + N + " are : "); System.out.println(
"Number of combinations of different natural number's raised to " +
X +
" having sum " +
N +
" are : "
);
System.out.println(count); System.out.println(count);
sc.close(); sc.close();
} }
private int count = 0, sum = 0; private int count = 0, sum = 0;
public int powSum(int N, int X) { public int powSum(int N, int X) {

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
package com.thealgorithms.ciphers; package com.thealgorithms.ciphers;
import javax.crypto.*;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
/** /**
* This example program shows how AES encryption and decryption can be done in * This example program shows how AES encryption and decryption can be done in
@ -26,8 +26,12 @@ public class AESEncryption {
String decryptedText = decryptText(cipherText, secKey); String decryptedText = decryptText(cipherText, secKey);
System.out.println("Original Text:" + plainText); System.out.println("Original Text:" + plainText);
System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())); System.out.println(
System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText)); "AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())
);
System.out.println(
"Encrypted Text (Hex Form):" + bytesToHex(cipherText)
);
System.out.println("Descrypted Text:" + decryptedText); System.out.println("Descrypted Text:" + decryptedText);
} }
@ -38,7 +42,8 @@ public class AESEncryption {
* @return secKey (Secret key that we encrypt using it) * @return secKey (Secret key that we encrypt using it)
* @throws NoSuchAlgorithmException (from KeyGenrator) * @throws NoSuchAlgorithmException (from KeyGenrator)
*/ */
public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException { public static SecretKey getSecretEncryptionKey()
throws NoSuchAlgorithmException {
KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES"); KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES");
aesKeyGenerator.init(128); // The AES key size in number of bits aesKeyGenerator.init(128); // The AES key size in number of bits
return aesKeyGenerator.generateKey(); return aesKeyGenerator.generateKey();
@ -55,8 +60,7 @@ public class AESEncryption {
* @throws IllegalBlockSizeException (from Cipher) * @throws IllegalBlockSizeException (from Cipher)
*/ */
public static byte[] encryptText(String plainText, SecretKey secKey) public static byte[] encryptText(String plainText, SecretKey secKey)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
IllegalBlockSizeException, BadPaddingException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7 // AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES"); Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey); aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
@ -69,8 +73,7 @@ public class AESEncryption {
* @return plainText * @return plainText
*/ */
public static String decryptText(byte[] byteCipherText, SecretKey secKey) public static String decryptText(byte[] byteCipherText, SecretKey secKey)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
IllegalBlockSizeException, BadPaddingException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7 // AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES"); Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, secKey); aesCipher.init(Cipher.DECRYPT_MODE, secKey);

View File

@ -15,10 +15,9 @@ class AffineCipher {
{here x is msg[i] and m is 26} and added 'A' to {here x is msg[i] and m is 26} and added 'A' to
bring it in range of ascii alphabet[ 65-90 | A-Z ] */ bring it in range of ascii alphabet[ 65-90 | A-Z ] */
if (msg[i] != ' ') { if (msg[i] != ' ') {
cipher = cipher cipher =
+ (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
} else // else simply append space character } else { // else simply append space character
{
cipher += msg[i]; cipher += msg[i];
} }
} }
@ -46,10 +45,12 @@ class AffineCipher {
{here x is cipher[i] and m is 26} and added 'A' {here x is cipher[i] and m is 26} and added 'A'
to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
if (cipher.charAt(i) != ' ') { if (cipher.charAt(i) != ' ') {
msg = msg + (char) (((a_inv msg =
* ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'); msg +
} else //else simply append space character (char) (
{ ((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'
);
} else { //else simply append space character
msg += cipher.charAt(i); msg += cipher.charAt(i);
} }
} }
@ -66,7 +67,8 @@ class AffineCipher {
System.out.println("Encrypted Message is : " + cipherText); System.out.println("Encrypted Message is : " + cipherText);
// Calling Decryption function // Calling Decryption function
System.out.println("Decrypted Message is: " + decryptCipher(cipherText)); System.out.println(
"Decrypted Message is: " + decryptCipher(cipherText)
);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -25,21 +25,16 @@ public class Caesar {
final int length = message.length(); final int length = message.length();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
// int current = message.charAt(i); //using char to shift characters because ascii // int current = message.charAt(i); //using char to shift characters because ascii
// is in-order latin alphabet // is in-order latin alphabet
char current = message.charAt(i); // Java law : char + int = char char current = message.charAt(i); // Java law : char + int = char
if (IsCapitalLatinLetter(current)) { if (IsCapitalLatinLetter(current)) {
current += shift; current += shift;
encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
} else if (IsSmallLatinLetter(current)) { } else if (IsSmallLatinLetter(current)) {
current += shift; current += shift;
encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
} else { } else {
encoded.append(current); encoded.append(current);
} }
@ -62,15 +57,11 @@ public class Caesar {
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
char current = encryptedMessage.charAt(i); char current = encryptedMessage.charAt(i);
if (IsCapitalLatinLetter(current)) { if (IsCapitalLatinLetter(current)) {
current -= shift; current -= shift;
decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
} else if (IsSmallLatinLetter(current)) { } else if (IsSmallLatinLetter(current)) {
current -= shift; current -= shift;
decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
} else { } else {
decoded.append(current); decoded.append(current);
} }
@ -91,12 +82,13 @@ public class Caesar {
private static boolean IsSmallLatinLetter(char c) { private static boolean IsSmallLatinLetter(char c) {
return c >= 'a' && c <= 'z'; return c >= 'a' && c <= 'z';
} }
/** /**
* @return string array which contains all the possible decoded combination. * @return string array which contains all the possible decoded combination.
*/ */
public static String[] bruteforce(String encryptedMessage) { public static String[] bruteforce(String encryptedMessage) {
String[] listOfAllTheAnswers = new String[27]; String[] listOfAllTheAnswers = new String[27];
for (int i=0; i<=26; i++) { for (int i = 0; i <= 26; i++) {
listOfAllTheAnswers[i] = decode(encryptedMessage, i); listOfAllTheAnswers[i] = decode(encryptedMessage, i);
} }
@ -117,19 +109,27 @@ public class Caesar {
System.out.println("Please enter the shift number"); System.out.println("Please enter the shift number");
shift = input.nextInt() % 26; shift = input.nextInt() % 26;
System.out.println( System.out.println(
"ENCODED MESSAGE IS \n" + encode(message, shift)); // send our function to handle "ENCODED MESSAGE IS \n" + encode(message, shift)
); // send our function to handle
break; break;
case 'D': case 'D':
case 'd': case 'd':
System.out.println("Please enter the shift number"); System.out.println("Please enter the shift number");
shift = input.nextInt() % 26; shift = input.nextInt() % 26;
System.out.println("DECODED MESSAGE IS \n" + decode(message, shift)); System.out.println(
"DECODED MESSAGE IS \n" + decode(message, shift)
);
break; break;
case 'B': case 'B':
case 'b': case 'b':
String[] listOfAllTheAnswers = bruteforce(message); String[] listOfAllTheAnswers = bruteforce(message);
for (int i =0; i<=26; i++) { for (int i = 0; i <= 26; i++) {
System.out.println("FOR SHIFT " + String.valueOf(i) + " decoded message is " + listOfAllTheAnswers[i]); System.out.println(
"FOR SHIFT " +
String.valueOf(i) +
" decoded message is " +
listOfAllTheAnswers[i]
);
} }
default: default:
System.out.println("default case"); System.out.println("default case");

View File

@ -12,8 +12,9 @@ public class ColumnarTranspositionCipher {
private static String keyword; private static String keyword;
private static Object[][] table; private static Object[][] table;
private static String abecedarium; private static String abecedarium;
public static final String ABECEDARIUM public static final String ABECEDARIUM =
= "abcdefghijklmnopqrstuvwxyzABCDEFG" + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; "abcdefghijklmnopqrstuvwxyzABCDEFG" +
"HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@";
private static final String ENCRYPTION_FIELD = ""; private static final String ENCRYPTION_FIELD = "";
private static final char ENCRYPTION_FIELD_CHAR = '≈'; private static final char ENCRYPTION_FIELD_CHAR = '≈';
@ -49,9 +50,14 @@ public class ColumnarTranspositionCipher {
* @return a String with the word encrypted by the Columnar Transposition * @return a String with the word encrypted by the Columnar Transposition
* Cipher Rule * Cipher Rule
*/ */
public static String encrpyter(String word, String keyword, String abecedarium) { public static String encrpyter(
String word,
String keyword,
String abecedarium
) {
ColumnarTranspositionCipher.keyword = keyword; ColumnarTranspositionCipher.keyword = keyword;
ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM); ColumnarTranspositionCipher.abecedarium =
Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
table = tableBuilder(word); table = tableBuilder(word);
Object[][] sortedTable = sortTable(table); Object[][] sortedTable = sortTable(table);
StringBuilder wordEncrypted = new StringBuilder(); StringBuilder wordEncrypted = new StringBuilder();
@ -114,7 +120,9 @@ public class ColumnarTranspositionCipher {
* order to respect the Columnar Transposition Cipher Rule. * order to respect the Columnar Transposition Cipher Rule.
*/ */
private static int numberOfRows(String word) { private static int numberOfRows(String word) {
if (word.length() / keyword.length() > word.length() / keyword.length()) { if (
word.length() / keyword.length() > word.length() / keyword.length()
) {
return (word.length() / keyword.length()) + 1; return (word.length() / keyword.length()) + 1;
} else { } else {
return word.length() / keyword.length(); return word.length() / keyword.length();
@ -139,12 +147,22 @@ public class ColumnarTranspositionCipher {
private static Object[][] sortTable(Object[][] table) { private static Object[][] sortTable(Object[][] table) {
Object[][] tableSorted = new Object[table.length][table[0].length]; Object[][] tableSorted = new Object[table.length][table[0].length];
for (int i = 0; i < tableSorted.length; i++) { for (int i = 0; i < tableSorted.length; i++) {
System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length); System.arraycopy(
table[i],
0,
tableSorted[i],
0,
tableSorted[i].length
);
} }
for (int i = 0; i < tableSorted[0].length; i++) { for (int i = 0; i < tableSorted[0].length; i++) {
for (int j = i + 1; j < tableSorted[0].length; j++) { for (int j = i + 1; j < tableSorted[0].length; j++) {
if ((int) tableSorted[0][i] > (int) table[0][j]) { if ((int) tableSorted[0][i] > (int) table[0][j]) {
Object[] column = getColumn(tableSorted, tableSorted.length, i); Object[] column = getColumn(
tableSorted,
tableSorted.length,
i
);
switchColumns(tableSorted, j, i, column); switchColumns(tableSorted, j, i, column);
} }
} }
@ -164,7 +182,11 @@ public class ColumnarTranspositionCipher {
} }
private static void switchColumns( private static void switchColumns(
Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) { Object[][] table,
int firstColumnIndex,
int secondColumnIndex,
Object[] columnToSwitch
) {
for (int i = 0; i < table.length; i++) { for (int i = 0; i < table.length; i++) {
table[i][secondColumnIndex] = table[i][firstColumnIndex]; table[i][secondColumnIndex] = table[i][firstColumnIndex];
table[i][firstColumnIndex] = columnToSwitch[i]; table[i][firstColumnIndex] = columnToSwitch[i];
@ -195,13 +217,22 @@ public class ColumnarTranspositionCipher {
public static void main(String[] args) { public static void main(String[] args) {
String keywordForExample = "asd215"; String keywordForExample = "asd215";
String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher"; String wordBeingEncrypted =
System.out.println("### Example of Columnar Transposition Cipher ###\n"); "This is a test of the Columnar Transposition Cipher";
System.out.println(
"### Example of Columnar Transposition Cipher ###\n"
);
System.out.println("Word being encryped ->>> " + wordBeingEncrypted); System.out.println("Word being encryped ->>> " + wordBeingEncrypted);
System.out.println( System.out.println(
"Word encrypted ->>> " "Word encrypted ->>> " +
+ ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample)); ColumnarTranspositionCipher.encrpyter(
System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter()); wordBeingEncrypted,
keywordForExample
)
);
System.out.println(
"Word decryped ->>> " + ColumnarTranspositionCipher.decrypter()
);
System.out.println("\n### Encrypted Table ###"); System.out.println("\n### Encrypted Table ###");
showTable(); showTable();
} }

View File

@ -29,7 +29,7 @@ public class HillCipher {
} }
} }
//check if det = 0 //check if det = 0
validateDeterminant(keyMatrix,matrixSize); validateDeterminant(keyMatrix, matrixSize);
int[][] messageVector = new int[matrixSize][1]; int[][] messageVector = new int[matrixSize][1];
String CipherText = ""; String CipherText = "";
@ -76,7 +76,7 @@ public class HillCipher {
} }
} }
//check if det = 0 //check if det = 0
validateDeterminant(keyMatrix,n); validateDeterminant(keyMatrix, n);
//solving for the required plaintext message //solving for the required plaintext message
int[][] messageVector = new int[n][1]; int[][] messageVector = new int[n][1];
@ -155,9 +155,11 @@ public class HillCipher {
} }
} }
static void validateDeterminant(int[][] keyMatrix, int n){ static void validateDeterminant(int[][] keyMatrix, int n) {
if (determinant(keyMatrix, n) % 26 == 0) { if (determinant(keyMatrix, n) % 26 == 0) {
System.out.println("Invalid key, as determinant = 0. Program Terminated"); System.out.println(
"Invalid key, as determinant = 0. Program Terminated"
);
return; return;
} }
} }

View File

@ -15,12 +15,12 @@ package com.thealgorithms.ciphers;
public class Polybius { public class Polybius {
private static final char[][] key = { private static final char[][] key = {
// 0 1 2 3 4 // 0 1 2 3 4
/* 0 */ {'A', 'B', 'C', 'D', 'E'}, /* 0 */{ 'A', 'B', 'C', 'D', 'E' },
/* 1 */ {'F', 'G', 'H', 'I', 'J'}, /* 1 */{ 'F', 'G', 'H', 'I', 'J' },
/* 2 */ {'K', 'L', 'M', 'N', 'O'}, /* 2 */{ 'K', 'L', 'M', 'N', 'O' },
/* 3 */ {'P', 'Q', 'R', 'S', 'T'}, /* 3 */{ 'P', 'Q', 'R', 'S', 'T' },
/* 4 */ {'V', 'W', 'X', 'Y', 'Z'} /* 4 */{ 'V', 'W', 'X', 'Y', 'Z' },
}; };
private static String findLocationByCharacter(final char character) { private static String findLocationByCharacter(final char character) {
@ -49,7 +49,7 @@ public class Polybius {
public static String decrypt(final String ciphertext) { public static String decrypt(final String ciphertext) {
final char[] chars = ciphertext.toCharArray(); final char[] chars = ciphertext.toCharArray();
final StringBuilder plaintext = new StringBuilder(); final StringBuilder plaintext = new StringBuilder();
for(int i = 0; i < chars.length; i+=2) { for (int i = 0; i < chars.length; i += 2) {
int pozitionX = Character.getNumericValue(chars[i]); int pozitionX = Character.getNumericValue(chars[i]);
int pozitionY = Character.getNumericValue(chars[i + 1]); int pozitionY = Character.getNumericValue(chars[i + 1]);
plaintext.append(key[pozitionX][pozitionY]); plaintext.append(key[pozitionX][pozitionY]);

View File

@ -68,5 +68,4 @@ class ProductCipher {
System.out.println(plaintext); System.out.println(plaintext);
sc.close(); sc.close();
} }
} }

View File

@ -1,8 +1,8 @@
package com.thealgorithms.ciphers; package com.thealgorithms.ciphers;
import javax.swing.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.SecureRandom; import java.security.SecureRandom;
import javax.swing.*;
/** /**
* @author Nguyen Duy Tiep on 23-Oct-17. * @author Nguyen Duy Tiep on 23-Oct-17.
@ -10,14 +10,21 @@ import java.security.SecureRandom;
public final class RSA { public final class RSA {
public static void main(String[] args) { public static void main(String[] args) {
RSA rsa = new RSA(1024); RSA rsa = new RSA(1024);
String text1 = JOptionPane.showInputDialog("Enter a message to encrypt :"); String text1 = JOptionPane.showInputDialog(
"Enter a message to encrypt :"
);
String ciphertext = rsa.encrypt(text1); String ciphertext = rsa.encrypt(text1);
JOptionPane.showMessageDialog(null, "Your encrypted message : " + ciphertext); JOptionPane.showMessageDialog(
null,
"Your encrypted message : " + ciphertext
);
JOptionPane.showMessageDialog(null, "Your message after decrypt : " + rsa.decrypt(ciphertext)); JOptionPane.showMessageDialog(
null,
"Your message after decrypt : " + rsa.decrypt(ciphertext)
);
} }
private BigInteger modulus, privateKey, publicKey; private BigInteger modulus, privateKey, publicKey;
@ -30,7 +37,8 @@ public final class RSA {
* @return encrypted message * @return encrypted message
*/ */
public synchronized String encrypt(String message) { public synchronized String encrypt(String message) {
return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); return (new BigInteger(message.getBytes())).modPow(publicKey, modulus)
.toString();
} }
/** /**
@ -44,7 +52,10 @@ public final class RSA {
* @return plain message * @return plain message
*/ */
public synchronized String decrypt(String encryptedMessage) { public synchronized String decrypt(String encryptedMessage) {
return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray()); return new String(
(new BigInteger(encryptedMessage)).modPow(privateKey, modulus)
.toByteArray()
);
} }
/** /**
@ -63,7 +74,8 @@ public final class RSA {
BigInteger q = new BigInteger(bits / 2, 100, r); BigInteger q = new BigInteger(bits / 2, 100, r);
modulus = p.multiply(q); modulus = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); BigInteger m =
(p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
publicKey = new BigInteger("3"); publicKey = new BigInteger("3");

View File

@ -84,9 +84,11 @@ public class SimpleSubCipher {
} }
public static void main(String[] args) { public static void main(String[] args) {
String a = encode("defend the east wall of the castle", "phqgiumeaylnofdxjkrcvstzwb"); String a = encode(
"defend the east wall of the castle",
"phqgiumeaylnofdxjkrcvstzwb"
);
String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb"); String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb");
System.out.println(b); System.out.println(b);
} }
} }

View File

@ -85,7 +85,10 @@ public class SimpleSubstitutionCipher {
* TODO remove main and make JUnit Testing * TODO remove main and make JUnit Testing
*/ */
public static void main(String[] args) { public static void main(String[] args) {
String a = encode("defend the east wall of the castle", "phqgiumeaylnofdxjkrcvstzwb"); String a = encode(
"defend the east wall of the castle",
"phqgiumeaylnofdxjkrcvstzwb"
);
String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb"); String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb");
System.out.println(b); System.out.println(b);
} }

View File

@ -9,17 +9,27 @@ package com.thealgorithms.ciphers;
public class Vigenere { public class Vigenere {
public static String encrypt(final String message, final String key) { public static String encrypt(final String message, final String key) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
for (int i = 0, j = 0; i < message.length(); i++) { for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i); char c = message.charAt(i);
if (Character.isLetter(c)) { if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) { if (Character.isUpperCase(c)) {
result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A')); result.append(
(char) (
(c + key.toUpperCase().charAt(j) - 2 * 'A') %
26 +
'A'
)
);
} else { } else {
result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a')); result.append(
(char) (
(c + key.toLowerCase().charAt(j) - 2 * 'a') %
26 +
'a'
)
);
} }
} else { } else {
result.append(c); result.append(c);
@ -33,14 +43,20 @@ public class Vigenere {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
for (int i = 0, j = 0; i < message.length(); i++) { for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i); char c = message.charAt(i);
if (Character.isLetter(c)) { if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) { if (Character.isUpperCase(c)) {
result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26)); result.append(
(char) (
'Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26
)
);
} else { } else {
result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26)); result.append(
(char) (
'z' - (25 - (c - key.toLowerCase().charAt(j))) % 26
)
);
} }
} else { } else {
result.append(c); result.append(c);

View File

@ -4,21 +4,22 @@ import java.util.BitSet;
// https://en.wikipedia.org/wiki/A5/1 // https://en.wikipedia.org/wiki/A5/1
public class A5Cipher { public class A5Cipher {
private final A5KeyStreamGenerator keyStreamGenerator; private final A5KeyStreamGenerator keyStreamGenerator;
private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
public A5Cipher( BitSet sessionKey, BitSet frameCounter ) { public A5Cipher(BitSet sessionKey, BitSet frameCounter) {
keyStreamGenerator = new A5KeyStreamGenerator(); keyStreamGenerator = new A5KeyStreamGenerator();
keyStreamGenerator.initialize( sessionKey, frameCounter ); keyStreamGenerator.initialize(sessionKey, frameCounter);
} }
public BitSet encrypt( BitSet plainTextBits ) { public BitSet encrypt(BitSet plainTextBits) {
// create a copy // create a copy
var result = new BitSet( KEY_STREAM_LENGTH ); var result = new BitSet(KEY_STREAM_LENGTH);
result.xor( plainTextBits ); result.xor(plainTextBits);
var key = keyStreamGenerator.getNextKeyStream(); var key = keyStreamGenerator.getNextKeyStream();
result.xor( key ); result.xor(key);
return result; return result;
} }
@ -26,5 +27,4 @@ public class A5Cipher {
public void resetCounter() { public void resetCounter() {
keyStreamGenerator.reInitialize(); keyStreamGenerator.reInitialize();
} }
} }

View File

@ -4,6 +4,7 @@ import java.util.BitSet;
// TODO: raise exceptions for improper use // TODO: raise exceptions for improper use
public class A5KeyStreamGenerator extends CompositeLFSR { public class A5KeyStreamGenerator extends CompositeLFSR {
private BitSet initialFrameCounter; private BitSet initialFrameCounter;
private BitSet frameCounter; private BitSet frameCounter;
private BitSet sessionKey; private BitSet sessionKey;
@ -11,32 +12,35 @@ public class A5KeyStreamGenerator extends CompositeLFSR {
private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
@Override @Override
public void initialize( BitSet sessionKey, BitSet frameCounter ) { public void initialize(BitSet sessionKey, BitSet frameCounter) {
this.sessionKey = sessionKey; this.sessionKey = sessionKey;
this.frameCounter = (BitSet) frameCounter.clone(); this.frameCounter = (BitSet) frameCounter.clone();
this.initialFrameCounter = (BitSet) frameCounter.clone(); this.initialFrameCounter = (BitSet) frameCounter.clone();
registers.clear(); registers.clear();
LFSR lfsr1 = new LFSR( 19, 8, new int[]{ 13, 16, 17, 18 } ); LFSR lfsr1 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 });
LFSR lfsr2 = new LFSR( 22, 10, new int[]{ 20, 21 } ); LFSR lfsr2 = new LFSR(22, 10, new int[] { 20, 21 });
LFSR lfsr3 = new LFSR( 23, 10, new int[]{ 7, 20, 21, 22 } ); LFSR lfsr3 = new LFSR(23, 10, new int[] { 7, 20, 21, 22 });
registers.add( lfsr1 ); registers.add(lfsr1);
registers.add( lfsr2 ); registers.add(lfsr2);
registers.add( lfsr3 ); registers.add(lfsr3);
registers.forEach( lfsr -> lfsr.initialize( sessionKey, frameCounter ) ); registers.forEach(lfsr -> lfsr.initialize(sessionKey, frameCounter));
} }
public void reInitialize() { public void reInitialize() {
this.initialize( sessionKey, initialFrameCounter ); this.initialize(sessionKey, initialFrameCounter);
} }
public BitSet getNextKeyStream() { public BitSet getNextKeyStream() {
for ( int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle ) for (
this.clock(); int cycle = 1;
cycle <= INITIAL_CLOCKING_CYCLES;
++cycle
) this.clock();
BitSet result = new BitSet( KEY_STREAM_LENGTH ); BitSet result = new BitSet(KEY_STREAM_LENGTH);
for ( int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle ) { for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) {
boolean outputBit = this.clock(); boolean outputBit = this.clock();
result.set( cycle - 1, outputBit ); result.set(cycle - 1, outputBit);
} }
reInitializeRegisters(); reInitializeRegisters();
@ -45,10 +49,10 @@ public class A5KeyStreamGenerator extends CompositeLFSR {
private void reInitializeRegisters() { private void reInitializeRegisters() {
incrementFrameCounter(); incrementFrameCounter();
registers.forEach( lfsr -> lfsr.initialize( sessionKey, frameCounter ) ); registers.forEach(lfsr -> lfsr.initialize(sessionKey, frameCounter));
} }
private void incrementFrameCounter() { private void incrementFrameCounter() {
Utils.increment( frameCounter, FRAME_COUNTER_LENGTH ); Utils.increment(frameCounter, FRAME_COUNTER_LENGTH);
} }
} }

View File

@ -6,6 +6,7 @@ import java.util.Map;
import java.util.TreeMap; import java.util.TreeMap;
public abstract class CompositeLFSR implements BaseLFSR { public abstract class CompositeLFSR implements BaseLFSR {
protected final List<LFSR> registers = new ArrayList<>(); protected final List<LFSR> registers = new ArrayList<>();
/** /**
@ -16,20 +17,24 @@ public abstract class CompositeLFSR implements BaseLFSR {
public boolean clock() { public boolean clock() {
boolean majorityBit = getMajorityBit(); boolean majorityBit = getMajorityBit();
boolean result = false; boolean result = false;
for ( var register : registers ) { for (var register : registers) {
result ^= register.getLastBit(); result ^= register.getLastBit();
if ( register.getClockBit() == majorityBit ) if (register.getClockBit() == majorityBit) register.clock();
register.clock();
} }
return result; return result;
} }
private boolean getMajorityBit() { private boolean getMajorityBit() {
Map<Boolean, Integer> bitCount = new TreeMap<>(); Map<Boolean, Integer> bitCount = new TreeMap<>();
bitCount.put( false, 0 ); bitCount.put(false, 0);
bitCount.put( true, 0 ); bitCount.put(true, 0);
registers.forEach( lfsr -> bitCount.put( lfsr.getClockBit(), bitCount.get( lfsr.getClockBit() ) + 1 ) ); registers.forEach(lfsr ->
return bitCount.get( false ) <= bitCount.get( true ); bitCount.put(
lfsr.getClockBit(),
bitCount.get(lfsr.getClockBit()) + 1
)
);
return bitCount.get(false) <= bitCount.get(true);
} }
} }

View File

@ -3,71 +3,72 @@ package com.thealgorithms.ciphers.a5;
import java.util.BitSet; import java.util.BitSet;
public class LFSR implements BaseLFSR { public class LFSR implements BaseLFSR {
private final BitSet register; private final BitSet register;
private final int length; private final int length;
private final int clockBitIndex; private final int clockBitIndex;
private final int[] tappingBitsIndices; private final int[] tappingBitsIndices;
public LFSR( int length, int clockBitIndex, int[] tappingBitsIndices ) { public LFSR(int length, int clockBitIndex, int[] tappingBitsIndices) {
this.length = length; this.length = length;
this.clockBitIndex = clockBitIndex; this.clockBitIndex = clockBitIndex;
this.tappingBitsIndices = tappingBitsIndices; this.tappingBitsIndices = tappingBitsIndices;
register = new BitSet( length ); register = new BitSet(length);
} }
@Override @Override
public void initialize( BitSet sessionKey, BitSet frameCounter ) { public void initialize(BitSet sessionKey, BitSet frameCounter) {
register.clear(); register.clear();
clock( sessionKey, SESSION_KEY_LENGTH ); clock(sessionKey, SESSION_KEY_LENGTH);
clock( frameCounter, FRAME_COUNTER_LENGTH ); clock(frameCounter, FRAME_COUNTER_LENGTH);
} }
private void clock( BitSet key, int keyLength ) { private void clock(BitSet key, int keyLength) {
// We start from reverse because LFSR 0 index is the left most bit // We start from reverse because LFSR 0 index is the left most bit
// while key 0 index is right most bit, so we reverse it // while key 0 index is right most bit, so we reverse it
for ( int i = keyLength - 1; i >= 0; --i ) { for (int i = keyLength - 1; i >= 0; --i) {
var newBit = key.get( i ) ^ xorTappingBits(); var newBit = key.get(i) ^ xorTappingBits();
pushBit( newBit ); pushBit(newBit);
} }
} }
@Override @Override
public boolean clock() { public boolean clock() {
return pushBit( xorTappingBits() ); return pushBit(xorTappingBits());
} }
public boolean getClockBit() { public boolean getClockBit() {
return register.get( clockBitIndex ); return register.get(clockBitIndex);
} }
public boolean get( int bitIndex ) { public boolean get(int bitIndex) {
return register.get( bitIndex ); return register.get(bitIndex);
} }
public boolean getLastBit() { public boolean getLastBit() {
return register.get( length - 1 ); return register.get(length - 1);
} }
private boolean xorTappingBits() { private boolean xorTappingBits() {
boolean result = false; boolean result = false;
for ( int i : tappingBitsIndices ) { for (int i : tappingBitsIndices) {
result ^= register.get( i ); result ^= register.get(i);
} }
return result; return result;
} }
private boolean pushBit( boolean bit ) { private boolean pushBit(boolean bit) {
boolean discardedBit = rightShift(); boolean discardedBit = rightShift();
register.set( 0, bit ); register.set(0, bit);
return discardedBit; return discardedBit;
} }
private boolean rightShift() { private boolean rightShift() {
boolean discardedBit = get( length - 1 ); boolean discardedBit = get(length - 1);
for ( int i = length - 1; i > 0; --i ) { for (int i = length - 1; i > 0; --i) {
register.set( i, get( i - 1 ) ); register.set(i, get(i - 1));
} }
register.set( 0, false ); register.set(0, false);
return discardedBit; return discardedBit;
} }

View File

@ -7,15 +7,16 @@ package com.thealgorithms.ciphers.a5;
import java.util.BitSet; import java.util.BitSet;
public class Utils { public class Utils {
public static boolean increment( BitSet bits, int size ) {
public static boolean increment(BitSet bits, int size) {
int i = size - 1; int i = size - 1;
while ( i >= 0 && bits.get( i ) ) { while (i >= 0 && bits.get(i)) {
bits.set( i--, false );/*from w w w . j a v a 2s .c o m*/ bits.set(i--, false);/*from w w w . j a v a 2s .c o m*/
} }
if ( i < 0 ) { if (i < 0) {
return false; return false;
} }
bits.set( i, true ); bits.set(i, true);
return true; return true;
} }
} }

View File

@ -31,7 +31,12 @@ public class AnyBaseToAnyBase {
System.out.print("Enter number: "); System.out.print("Enter number: ");
n = in.next(); n = in.next();
System.out.print( System.out.print(
"Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); "Enter beginning base (between " +
MINIMUM_BASE +
" and " +
MAXIMUM_BASE +
"): "
);
b1 = in.nextInt(); b1 = in.nextInt();
if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) { if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) {
System.out.println("Invalid base!"); System.out.println("Invalid base!");
@ -42,7 +47,12 @@ public class AnyBaseToAnyBase {
continue; continue;
} }
System.out.print( System.out.print(
"Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); "Enter end base (between " +
MINIMUM_BASE +
" and " +
MAXIMUM_BASE +
"): "
);
b2 = in.nextInt(); b2 = in.nextInt();
if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) { if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) {
System.out.println("Invalid base!"); System.out.println("Invalid base!");
@ -63,8 +73,42 @@ public class AnyBaseToAnyBase {
*/ */
public static boolean validForBase(String n, int base) { public static boolean validForBase(String n, int base) {
char[] validDigits = { char[] validDigits = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', '0',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' '1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
}; };
// digitsForBase contains all the valid digits for the base given // digitsForBase contains all the valid digits for the base given
char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base); char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base);

View File

@ -1,6 +1,7 @@
package com.thealgorithms.conversions; package com.thealgorithms.conversions;
import java.util.Scanner; import java.util.Scanner;
// given a source number , source base, destination base, this code can give you the destination // given a source number , source base, destination base, this code can give you the destination
// number. // number.
// sn ,sb,db ---> ()dn . this is what we have to do . // sn ,sb,db ---> ()dn . this is what we have to do .

View File

@ -11,7 +11,9 @@ import java.util.ArrayList;
public class DecimalToAnyBase { public class DecimalToAnyBase {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
System.out.println("Enter the decimal input below: "); System.out.println("Enter the decimal input below: ");
int decInput = Integer.parseInt(br.readLine()); int decInput = Integer.parseInt(br.readLine());
System.out.println(); System.out.println();
@ -22,7 +24,13 @@ public class DecimalToAnyBase {
System.out.println("Decimal Input" + " is: " + decInput); System.out.println("Decimal Input" + " is: " + decInput);
System.out.println( System.out.println(
"Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base)); "Value of " +
decInput +
" in base " +
base +
" is: " +
convertToAnyBase(decInput, base)
);
br.close(); br.close();
} }

View File

@ -24,7 +24,9 @@ class DecimalToBinary {
public static void conventionalConversion() { public static void conventionalConversion() {
int n, b = 0, c = 0, d; int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in); Scanner input = new Scanner(System.in);
System.out.printf("Conventional conversion.%n Enter the decimal number: "); System.out.printf(
"Conventional conversion.%n Enter the decimal number: "
);
n = input.nextInt(); n = input.nextInt();
while (n != 0) { while (n != 0) {
d = n % 2; d = n % 2;

View File

@ -7,7 +7,22 @@ class DecimalToHexaDecimal {
private static final int numberOfBitsInAHalfByte = 4; private static final int numberOfBitsInAHalfByte = 4;
private static final int halfByte = 0x0F; private static final int halfByte = 0x0F;
private static final char[] hexDigits = { private static final char[] hexDigits = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'A',
'B',
'C',
'D',
'E',
'F',
}; };
// Returns the hex value of the dec entered in the parameter. // Returns the hex value of the dec entered in the parameter.

View File

@ -61,9 +61,7 @@ public class HexToOct {
hexadecnum = scan.nextLine(); hexadecnum = scan.nextLine();
// first convert hexadecimal to decimal // first convert hexadecimal to decimal
decnum decnum = hex2decimal(hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
= hex2decimal(
hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
// variable decnum // variable decnum
// convert decimal to octal // convert decimal to octal

View File

@ -22,9 +22,20 @@ public class HexaDecimalToBinary {
} }
public static void main(String[] args) { public static void main(String[] args) {
// Testing Numbers: // Testing Numbers:
String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", "19", "01", "02", "03", "04"}; String[] hexNums = {
"1",
"A1",
"ef",
"BA",
"AA",
"BB",
"19",
"01",
"02",
"03",
"04",
};
HexaDecimalToBinary objConvert = new HexaDecimalToBinary(); HexaDecimalToBinary objConvert = new HexaDecimalToBinary();
for (String num : hexNums) { for (String num : hexNums) {

View File

@ -9,10 +9,36 @@ package com.thealgorithms.conversions;
*/ */
public class IntegerToRoman { public class IntegerToRoman {
private static int[] allArabianRomanNumbers private static int[] allArabianRomanNumbers = new int[] {
= new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 1000,
private static String[] allRomanNumbers 900,
= new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 500,
400,
100,
90,
50,
40,
10,
9,
5,
4,
1,
};
private static String[] allRomanNumbers = new String[] {
"M",
"CM",
"D",
"CD",
"C",
"XC",
"L",
"XL",
"X",
"IX",
"V",
"IV",
"I",
};
// Value must be > 0 // Value must be > 0
public static String integerToRoman(int num) { public static String integerToRoman(int num) {

View File

@ -32,7 +32,6 @@ public class OctalToDecimal {
* @return The decimal number * @return The decimal number
*/ */
public static int convertOctalToDecimal(String inputOctal) { public static int convertOctalToDecimal(String inputOctal) {
try { try {
// Actual conversion of Octal to Decimal: // Actual conversion of Octal to Decimal:
Integer outputDecimal = Integer.parseInt(inputOctal, 8); Integer outputDecimal = Integer.parseInt(inputOctal, 8);

View File

@ -47,7 +47,6 @@ public class OctalToHexadecimal {
} }
public static void main(String args[]) { public static void main(String args[]) {
Scanner input = new Scanner(System.in); Scanner input = new Scanner(System.in);
System.out.print("Enter the Octal number: "); System.out.print("Enter the Octal number: ");
// Take octal number as input from user in a string // Take octal number as input from user in a string

View File

@ -19,30 +19,69 @@ public class RgbHsvConversion {
// Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html // Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html
// Test hsvToRgb-method // Test hsvToRgb-method
assert Arrays.equals(hsvToRgb(0, 0, 0), new int[]{0, 0, 0}); assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] { 0, 0, 0 });
assert Arrays.equals(hsvToRgb(0, 0, 1), new int[]{255, 255, 255}); assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] { 255, 255, 255 });
assert Arrays.equals(hsvToRgb(0, 1, 1), new int[]{255, 0, 0}); assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] { 255, 0, 0 });
assert Arrays.equals(hsvToRgb(60, 1, 1), new int[]{255, 255, 0}); assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] { 255, 255, 0 });
assert Arrays.equals(hsvToRgb(120, 1, 1), new int[]{0, 255, 0}); assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] { 0, 255, 0 });
assert Arrays.equals(hsvToRgb(240, 1, 1), new int[]{0, 0, 255}); assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] { 0, 0, 255 });
assert Arrays.equals(hsvToRgb(300, 1, 1), new int[]{255, 0, 255}); assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] { 255, 0, 255 });
assert Arrays.equals(hsvToRgb(180, 0.5, 0.5), new int[]{64, 128, 128}); assert Arrays.equals(
assert Arrays.equals(hsvToRgb(234, 0.14, 0.88), new int[]{193, 196, 224}); hsvToRgb(180, 0.5, 0.5),
assert Arrays.equals(hsvToRgb(330, 0.75, 0.5), new int[]{128, 32, 80}); new int[] { 64, 128, 128 }
);
assert Arrays.equals(
hsvToRgb(234, 0.14, 0.88),
new int[] { 193, 196, 224 }
);
assert Arrays.equals(
hsvToRgb(330, 0.75, 0.5),
new int[] { 128, 32, 80 }
);
// Test rgbToHsv-method // Test rgbToHsv-method
// approximate-assertions needed because of small deviations due to converting between // approximate-assertions needed because of small deviations due to converting between
// int-values and double-values. // int-values and double-values.
assert approximatelyEqualHsv(rgbToHsv(0, 0, 0), new double[]{0, 0, 0}); assert approximatelyEqualHsv(
assert approximatelyEqualHsv(rgbToHsv(255, 255, 255), new double[]{0, 0, 1}); rgbToHsv(0, 0, 0),
assert approximatelyEqualHsv(rgbToHsv(255, 0, 0), new double[]{0, 1, 1}); new double[] { 0, 0, 0 }
assert approximatelyEqualHsv(rgbToHsv(255, 255, 0), new double[]{60, 1, 1}); );
assert approximatelyEqualHsv(rgbToHsv(0, 255, 0), new double[]{120, 1, 1}); assert approximatelyEqualHsv(
assert approximatelyEqualHsv(rgbToHsv(0, 0, 255), new double[]{240, 1, 1}); rgbToHsv(255, 255, 255),
assert approximatelyEqualHsv(rgbToHsv(255, 0, 255), new double[]{300, 1, 1}); new double[] { 0, 0, 1 }
assert approximatelyEqualHsv(rgbToHsv(64, 128, 128), new double[]{180, 0.5, 0.5}); );
assert approximatelyEqualHsv(rgbToHsv(193, 196, 224), new double[]{234, 0.14, 0.88}); assert approximatelyEqualHsv(
assert approximatelyEqualHsv(rgbToHsv(128, 32, 80), new double[]{330, 0.75, 0.5}); rgbToHsv(255, 0, 0),
new double[] { 0, 1, 1 }
);
assert approximatelyEqualHsv(
rgbToHsv(255, 255, 0),
new double[] { 60, 1, 1 }
);
assert approximatelyEqualHsv(
rgbToHsv(0, 255, 0),
new double[] { 120, 1, 1 }
);
assert approximatelyEqualHsv(
rgbToHsv(0, 0, 255),
new double[] { 240, 1, 1 }
);
assert approximatelyEqualHsv(
rgbToHsv(255, 0, 255),
new double[] { 300, 1, 1 }
);
assert approximatelyEqualHsv(
rgbToHsv(64, 128, 128),
new double[] { 180, 0.5, 0.5 }
);
assert approximatelyEqualHsv(
rgbToHsv(193, 196, 224),
new double[] { 234, 0.14, 0.88 }
);
assert approximatelyEqualHsv(
rgbToHsv(128, 32, 80),
new double[] { 330, 0.75, 0.5 }
);
} }
/** /**
@ -55,23 +94,35 @@ public class RgbHsvConversion {
*/ */
public static int[] hsvToRgb(double hue, double saturation, double value) { public static int[] hsvToRgb(double hue, double saturation, double value) {
if (hue < 0 || hue > 360) { if (hue < 0 || hue > 360) {
throw new IllegalArgumentException("hue should be between 0 and 360"); throw new IllegalArgumentException(
"hue should be between 0 and 360"
);
} }
if (saturation < 0 || saturation > 1) { if (saturation < 0 || saturation > 1) {
throw new IllegalArgumentException("saturation should be between 0 and 1"); throw new IllegalArgumentException(
"saturation should be between 0 and 1"
);
} }
if (value < 0 || value > 1) { if (value < 0 || value > 1) {
throw new IllegalArgumentException("value should be between 0 and 1"); throw new IllegalArgumentException(
"value should be between 0 and 1"
);
} }
double chroma = value * saturation; double chroma = value * saturation;
double hueSection = hue / 60; double hueSection = hue / 60;
double secondLargestComponent = chroma * (1 - Math.abs(hueSection % 2 - 1)); double secondLargestComponent =
chroma * (1 - Math.abs(hueSection % 2 - 1));
double matchValue = value - chroma; double matchValue = value - chroma;
return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent); return getRgbBySection(
hueSection,
chroma,
matchValue,
secondLargestComponent
);
} }
/** /**
@ -84,15 +135,21 @@ public class RgbHsvConversion {
*/ */
public static double[] rgbToHsv(int red, int green, int blue) { public static double[] rgbToHsv(int red, int green, int blue) {
if (red < 0 || red > 255) { if (red < 0 || red > 255) {
throw new IllegalArgumentException("red should be between 0 and 255"); throw new IllegalArgumentException(
"red should be between 0 and 255"
);
} }
if (green < 0 || green > 255) { if (green < 0 || green > 255) {
throw new IllegalArgumentException("green should be between 0 and 255"); throw new IllegalArgumentException(
"green should be between 0 and 255"
);
} }
if (blue < 0 || blue > 255) { if (blue < 0 || blue > 255) {
throw new IllegalArgumentException("blue should be between 0 and 255"); throw new IllegalArgumentException(
"blue should be between 0 and 255"
);
} }
double dRed = (double) red / 255; double dRed = (double) red / 255;
@ -115,7 +172,7 @@ public class RgbHsvConversion {
hue = (hue + 360) % 360; hue = (hue + 360) % 360;
return new double[]{hue, saturation, value}; return new double[] { hue, saturation, value };
} }
private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) { private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) {
@ -127,7 +184,11 @@ public class RgbHsvConversion {
} }
private static int[] getRgbBySection( private static int[] getRgbBySection(
double hueSection, double chroma, double matchValue, double secondLargestComponent) { double hueSection,
double chroma,
double matchValue,
double secondLargestComponent
) {
int red; int red;
int green; int green;
int blue; int blue;
@ -158,7 +219,7 @@ public class RgbHsvConversion {
blue = convertToInt(secondLargestComponent + matchValue); blue = convertToInt(secondLargestComponent + matchValue);
} }
return new int[]{red, green, blue}; return new int[] { red, green, blue };
} }
private static int convertToInt(double input) { private static int convertToInt(double input) {

View File

@ -4,8 +4,7 @@ import java.util.*;
public class RomanToInteger { public class RomanToInteger {
private static Map<Character, Integer> map private static Map<Character, Integer> map = new HashMap<Character, Integer>() {
= new HashMap<Character, Integer>() {
/** /**
* */ * */
private static final long serialVersionUID = 87605733047260530L; private static final long serialVersionUID = 87605733047260530L;
@ -20,6 +19,7 @@ public class RomanToInteger {
put('M', 1000); put('M', 1000);
} }
}; };
// Roman Number = Roman Numerals // Roman Number = Roman Numerals
/** /**
@ -29,7 +29,6 @@ public class RomanToInteger {
* @return integer * @return integer
*/ */
public static int romanToInt(String A) { public static int romanToInt(String A) {
A = A.toUpperCase(); A = A.toUpperCase();
char prev = ' '; char prev = ' ';

View File

@ -29,13 +29,40 @@ public class TurkishToLatinConversion {
* @return String * @return String
*/ */
public static String convertTurkishToLatin(String param) { public static String convertTurkishToLatin(String param) {
char[] turkishChars char[] turkishChars = new char[] {
= new char[]{0x131, 0x130, 0xFC, 0xDC, 0xF6, 0xD6, 0x15F, 0x15E, 0xE7, 0xC7, 0x11F, 0x11E}; 0x131,
char[] latinChars = new char[]{'i', 'I', 'u', 'U', 'o', 'O', 's', 'S', 'c', 'C', 'g', 'G'}; 0x130,
0xFC,
0xDC,
0xF6,
0xD6,
0x15F,
0x15E,
0xE7,
0xC7,
0x11F,
0x11E,
};
char[] latinChars = new char[] {
'i',
'I',
'u',
'U',
'o',
'O',
's',
'S',
'c',
'C',
'g',
'G',
};
for (int i = 0; i < turkishChars.length; i++) { for (int i = 0; i < turkishChars.length; i++) {
param param =
= param.replaceAll( param.replaceAll(
new String(new char[]{turkishChars[i]}), new String(new char[]{latinChars[i]})); new String(new char[] { turkishChars[i] }),
new String(new char[] { latinChars[i] })
);
} }
return param; return param;
} }

View File

@ -1,6 +1,5 @@
package com.thealgorithms.datastructures.bloomfilter; package com.thealgorithms.datastructures.bloomfilter;
import java.util.BitSet; import java.util.BitSet;
public class BloomFilter<T> { public class BloomFilter<T> {
@ -23,14 +22,14 @@ public class BloomFilter<T> {
} }
public void insert(T key) { public void insert(T key) {
for (Hash<T> hash : hashFunctions){ for (Hash<T> hash : hashFunctions) {
int position = hash.compute(key) % bitArray.size(); int position = hash.compute(key) % bitArray.size();
bitArray.set(position); bitArray.set(position);
} }
} }
public boolean contains(T key) { public boolean contains(T key) {
for (Hash<T> hash : hashFunctions){ for (Hash<T> hash : hashFunctions) {
int position = hash.compute(key) % bitArray.size(); int position = hash.compute(key) % bitArray.size();
if (!bitArray.get(position)) { if (!bitArray.get(position)) {
return false; return false;
@ -43,21 +42,20 @@ public class BloomFilter<T> {
int index; int index;
public Hash(int index){ public Hash(int index) {
this.index = index; this.index = index;
} }
public int compute(T key){ public int compute(T key) {
return index * asciiString(String.valueOf(key)); return index * asciiString(String.valueOf(key));
} }
private int asciiString(String word){ private int asciiString(String word) {
int number = 0; int number = 0;
for (int i=0;i<word.length();i++){ for (int i = 0; i < word.length(); i++) {
number += word.charAt(i); number += word.charAt(i);
} }
return number; return number;
} }
} }
} }

View File

@ -32,7 +32,6 @@ public class CircularBuffer {
// if we have data to read // if we have data to read
if (_readable_data.get() > 0) { if (_readable_data.get() > 0) {
result = Character.valueOf(_buffer[getTrueIndex(_read_index)]); result = Character.valueOf(_buffer[getTrueIndex(_read_index)]);
_readable_data.decrementAndGet(); _readable_data.decrementAndGet();
_read_index++; _read_index++;

View File

@ -7,36 +7,37 @@ import java.util.Map;
* Java program for LFU Cache (https://en.wikipedia.org/wiki/Least_frequently_used) * Java program for LFU Cache (https://en.wikipedia.org/wiki/Least_frequently_used)
* @author Akshay Dubey (https://github.com/itsAkshayDubey) * @author Akshay Dubey (https://github.com/itsAkshayDubey)
*/ */
public class LFUCache<K,V> { public class LFUCache<K, V> {
private class Node { private class Node {
private K key;
private V value;
private int frequency;
private Node previous;
private Node next;
public Node(K key, V value, int frequency) { private K key;
this.key = key; private V value;
this.value = value; private int frequency;
this.frequency = frequency; private Node previous;
} private Node next;
}
private Node head; public Node(K key, V value, int frequency) {
private Node tail; this.key = key;
private Map<K,Node> map = null; this.value = value;
private Integer capacity; this.frequency = frequency;
private static final int DEFAULT_CAPACITY = 100; }
}
public LFUCache() { private Node head;
this.capacity = DEFAULT_CAPACITY; private Node tail;
} private Map<K, Node> map = null;
private Integer capacity;
private static final int DEFAULT_CAPACITY = 100;
public LFUCache(Integer capacity) { public LFUCache() {
this.capacity = capacity; this.capacity = DEFAULT_CAPACITY;
this.map = new HashMap<>(); }
}
public LFUCache(Integer capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
}
/** /**
* This method returns value present in the cache corresponding to the key passed as parameter * This method returns value present in the cache corresponding to the key passed as parameter
@ -44,18 +45,18 @@ public class LFUCache<K,V> {
* @param <K> key for which value is to be retrieved * @param <K> key for which value is to be retrieved
* @returns <V> object corresponding to the key passed as parameter, returns null if <K> key is not present in the cache * @returns <V> object corresponding to the key passed as parameter, returns null if <K> key is not present in the cache
*/ */
public V get(K key) { public V get(K key) {
if(this.map.get(key) == null) { if (this.map.get(key) == null) {
return null; return null;
} }
Node node = map.get(key); Node node = map.get(key);
removeNode(node); removeNode(node);
node.frequency += 1; node.frequency += 1;
addNodeWithUpdatedFrequency(node); addNodeWithUpdatedFrequency(node);
return node.value; return node.value;
} }
/** /**
* This method stores <K> key and <V> value in the cache * This method stores <K> key and <V> value in the cache
@ -63,85 +64,79 @@ public class LFUCache<K,V> {
* @param <K> key which is to be stored in the cache * @param <K> key which is to be stored in the cache
* @param <V> value which is to be stored in the cache * @param <V> value which is to be stored in the cache
*/ */
public void put(K key, V value) { public void put(K key, V value) {
if(map.containsKey(key)) { if (map.containsKey(key)) {
Node node = map.get(key); Node node = map.get(key);
node.value = value; node.value = value;
node.frequency += 1; node.frequency += 1;
removeNode(node); removeNode(node);
addNodeWithUpdatedFrequency(node); addNodeWithUpdatedFrequency(node);
} } else {
else { if (map.size() >= capacity) {
if(map.size() >= capacity) { map.remove(this.head.key);
map.remove(this.head.key); removeNode(head);
removeNode(head); }
} Node node = new Node(key, value, 1);
Node node = new Node(key,value,1); addNodeWithUpdatedFrequency(node);
addNodeWithUpdatedFrequency(node); map.put(key, node);
map.put(key, node); }
} }
}
/** /**
* This method stores the node in the cache with updated frequency * This method stores the node in the cache with updated frequency
* *
* @param Node node which is to be updated in the cache * @param Node node which is to be updated in the cache
*/ */
private void addNodeWithUpdatedFrequency(Node node) { private void addNodeWithUpdatedFrequency(Node node) {
if(tail != null && head != null) { if (tail != null && head != null) {
Node temp = this.head; Node temp = this.head;
while(temp != null) { while (temp != null) {
if(temp.frequency > node.frequency) { if (temp.frequency > node.frequency) {
if(temp==head) { if (temp == head) {
node.next = temp; node.next = temp;
temp.previous = node; temp.previous = node;
this.head = node; this.head = node;
break; break;
} } else {
else { node.next = temp;
node.next = temp; node.previous = temp.previous;
node.previous = temp.previous; temp.previous.next = node;
temp.previous.next = node; node.previous = temp.previous;
node.previous = temp.previous; break;
break; }
} } else {
} temp = temp.next;
else { if (temp == null) {
temp = temp.next; tail.next = node;
if(temp == null) { node.previous = tail;
tail.next = node; node.next = null;
node.previous = tail; tail = node;
node.next = null; break;
tail = node; }
break; }
} }
} } else {
} tail = node;
} head = tail;
else { }
tail = node; }
head = tail;
}
}
/** /**
* This method removes node from the cache * This method removes node from the cache
* *
* @param Node node which is to be removed in the cache * @param Node node which is to be removed in the cache
*/ */
private void removeNode(Node node) { private void removeNode(Node node) {
if(node.previous != null) { if (node.previous != null) {
node.previous.next = node.next; node.previous.next = node.next;
} } else {
else { this.head = node.next;
this.head = node.next; }
}
if(node.next != null) { if (node.next != null) {
node.next.previous = node.previous; node.next.previous = node.previous;
} } else {
else { this.tail = node.previous;
this.tail = node.previous; }
} }
}
} }

View File

@ -126,10 +126,14 @@ public class LRUCache<K, V> {
private I key; private I key;
private J value; private J value;
public Entry() { public Entry() {}
}
public Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) { public Entry(
Entry<I, J> preEntry,
Entry<I, J> nextEntry,
I key,
J value
) {
this.preEntry = preEntry; this.preEntry = preEntry;
this.nextEntry = nextEntry; this.nextEntry = nextEntry;
this.key = key; this.key = key;

View File

@ -124,10 +124,14 @@ public class MRUCache<K, V> {
private I key; private I key;
private J value; private J value;
public Entry() { public Entry() {}
}
public Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) { public Entry(
Entry<I, J> preEntry,
Entry<I, J> nextEntry,
I key,
J value
) {
this.preEntry = preEntry; this.preEntry = preEntry;
this.nextEntry = nextEntry; this.nextEntry = nextEntry;
this.key = key; this.key = key;

View File

@ -6,8 +6,6 @@ public class DisjointSets<T> {
return new Node<T>(x); return new Node<T>(x);
} }
;
public Node<T> FindSet(Node<T> node) { public Node<T> FindSet(Node<T> node) {
if (node != node.parent) { if (node != node.parent) {
node.parent = FindSet(node.parent); node.parent = FindSet(node.parent);

View File

@ -44,7 +44,8 @@ public class DynamicArray<E> implements Iterable<E> {
*/ */
public void add(final E element) { public void add(final E element) {
if (this.size == this.elements.length) { if (this.size == this.elements.length) {
this.elements = Arrays.copyOf(this.elements, newCapacity(2 * this.capacity)); this.elements =
Arrays.copyOf(this.elements, newCapacity(2 * this.capacity));
} }
this.elements[this.size] = element; this.elements[this.size] = element;
@ -83,7 +84,8 @@ public class DynamicArray<E> implements Iterable<E> {
fastRemove(this.elements, index); fastRemove(this.elements, index);
if (this.capacity > DEFAULT_CAPACITY && size * 4 <= this.capacity) { if (this.capacity > DEFAULT_CAPACITY && size * 4 <= this.capacity) {
this.elements = Arrays.copyOf(this.elements, newCapacity(this.capacity / 2)); this.elements =
Arrays.copyOf(this.elements, newCapacity(this.capacity / 2));
} }
return oldElement; return oldElement;
} }
@ -114,7 +116,13 @@ public class DynamicArray<E> implements Iterable<E> {
final int newSize = this.size - 1; final int newSize = this.size - 1;
if (newSize > index) { if (newSize > index) {
System.arraycopy(elements, index + 1, elements, index, newSize - index); System.arraycopy(
elements,
index + 1,
elements,
index,
newSize - index
);
} }
elements[this.size = newSize] = null; elements[this.size = newSize] = null;
@ -136,7 +144,9 @@ public class DynamicArray<E> implements Iterable<E> {
*/ */
@Override @Override
public String toString() { public String toString() {
return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray()); return Arrays.toString(
Arrays.stream(this.elements).filter(Objects::nonNull).toArray()
);
} }
/** /**

View File

@ -8,6 +8,7 @@ import java.util.*;
public class A_Star { public class A_Star {
private static class Graph { private static class Graph {
// Graph's structure can be changed only applying changes to this class. // Graph's structure can be changed only applying changes to this class.
private ArrayList<ArrayList<Edge>> graph; private ArrayList<ArrayList<Edge>> graph;
@ -26,8 +27,10 @@ public class A_Star {
// Graph is bidirectional, for just one direction remove second instruction of this method. // Graph is bidirectional, for just one direction remove second instruction of this method.
private void addEdge(Edge edge) { private void addEdge(Edge edge) {
this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); this.graph.get(edge.getFrom())
this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); .add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight()));
this.graph.get(edge.getTo())
.add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
} }
} }
@ -63,7 +66,11 @@ public class A_Star {
private ArrayList<Integer> path; // list of visited nodes in this path. private ArrayList<Integer> path; // list of visited nodes in this path.
private int estimated; // heuristic value associated to the last node od the path (current node). private int estimated; // heuristic value associated to the last node od the path (current node).
public PathAndDistance(int distance, ArrayList<Integer> path, int estimated) { public PathAndDistance(
int distance,
ArrayList<Integer> path,
int estimated
) {
this.distance = distance; this.distance = distance;
this.path = path; this.path = path;
this.estimated = estimated; this.estimated = estimated;
@ -84,16 +91,24 @@ public class A_Star {
private void printSolution() { private void printSolution() {
if (this.path != null) { if (this.path != null) {
System.out.println( System.out.println(
"Optimal path: " + this.path + ", distance: " + this.distance); "Optimal path: " +
this.path +
", distance: " +
this.distance
);
} else { } else {
System.out.println("There is no path available to connect the points"); System.out.println(
"There is no path available to connect the points"
);
} }
} }
} }
private static void initializeGraph(Graph graph, ArrayList<Integer> data) { private static void initializeGraph(Graph graph, ArrayList<Integer> data) {
for (int i = 0; i < data.size(); i += 4) { for (int i = 0; i < data.size(); i += 4) {
graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2))); graph.addEdge(
new Edge(data.get(i), data.get(i + 1), data.get(i + 2))
);
} }
/* /*
.x. node .x. node
@ -127,30 +142,146 @@ public class A_Star {
public static void main(String[] args) { public static void main(String[] args) {
// heuristic function optimistic values // heuristic function optimistic values
int[] heuristic = { int[] heuristic = {
366, 0, 160, 242, 161, 178, 77, 151, 226, 244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374 366,
0,
160,
242,
161,
178,
77,
151,
226,
244,
241,
234,
380,
98,
193,
253,
329,
80,
199,
374,
}; };
Graph graph = new Graph(20); Graph graph = new Graph(20);
ArrayList<Integer> graphData ArrayList<Integer> graphData = new ArrayList<>(
= new ArrayList<>( Arrays.asList(
Arrays.asList( 0,
0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, 19,
null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, 75,
146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, 15, 5, 99, null, 14, null,
13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null, 0,
17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87)); 15,
140,
null,
0,
16,
118,
null,
19,
12,
71,
null,
12,
15,
151,
null,
16,
9,
111,
null,
9,
10,
70,
null,
10,
3,
75,
null,
3,
2,
120,
null,
2,
14,
146,
null,
2,
13,
138,
null,
2,
6,
115,
null,
15,
14,
80,
null,
15,
5,
99,
null,
14,
13,
97,
null,
5,
1,
211,
null,
13,
1,
101,
null,
6,
1,
160,
null,
1,
17,
85,
null,
17,
7,
98,
null,
7,
4,
86,
null,
17,
18,
142,
null,
18,
8,
92,
null,
8,
11,
87
)
);
initializeGraph(graph, graphData); initializeGraph(graph, graphData);
PathAndDistance solution = aStar(3, 1, graph, heuristic); PathAndDistance solution = aStar(3, 1, graph, heuristic);
solution.printSolution(); solution.printSolution();
} }
public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) { public static PathAndDistance aStar(
int from,
int to,
Graph graph,
int[] heuristic
) {
// nodes are prioritised by the less value of the current distance of their paths, and the // nodes are prioritised by the less value of the current distance of their paths, and the
// estimated value // estimated value
// given by the heuristic function to reach the destination point from the current point. // given by the heuristic function to reach the destination point from the current point.
PriorityQueue<PathAndDistance> queue PriorityQueue<PathAndDistance> queue = new PriorityQueue<>(
= new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))); Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))
);
// dummy data to start the algorithm from the beginning point // dummy data to start the algorithm from the beginning point
queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0)); queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0));
@ -159,26 +290,33 @@ public class A_Star {
PathAndDistance currentData = new PathAndDistance(-1, null, -1); PathAndDistance currentData = new PathAndDistance(-1, null, -1);
while (!queue.isEmpty() && !solutionFound) { while (!queue.isEmpty() && !solutionFound) {
currentData = queue.poll(); // first in the queue, best node so keep exploring. currentData = queue.poll(); // first in the queue, best node so keep exploring.
int currentPosition int currentPosition = currentData
= currentData.getPath().get(currentData.getPath().size() - 1); // current node. .getPath()
.get(currentData.getPath().size() - 1); // current node.
if (currentPosition == to) { if (currentPosition == to) {
solutionFound = true; solutionFound = true;
} else { } else {
for (Edge edge : graph.getNeighbours(currentPosition)) { for (Edge edge : graph.getNeighbours(currentPosition)) {
if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles
ArrayList<Integer> updatedPath = new ArrayList<>(currentData.getPath()); ArrayList<Integer> updatedPath = new ArrayList<>(
currentData.getPath()
);
updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance, updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance,
// and the heuristic function value associated to that path. // and the heuristic function value associated to that path.
queue.add( queue.add(
new PathAndDistance( new PathAndDistance(
currentData.getDistance() + edge.getWeight(), currentData.getDistance() + edge.getWeight(),
updatedPath, updatedPath,
heuristic[edge.getTo()])); heuristic[edge.getTo()]
)
);
} }
} }
} }
} }
return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1); return (solutionFound)
? currentData
: new PathAndDistance(-1, null, -1);
// Out of while loop, if there is a solution, the current Data stores the optimal path, and its // Out of while loop, if there is a solution, the current Data stores the optimal path, and its
// distance // distance
} }

View File

@ -3,7 +3,7 @@ package com.thealgorithms.datastructures.graphs;
import java.util.*; import java.util.*;
class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have
start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/ { start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{
int vertex, edge; int vertex, edge;
private Edge edges[]; private Edge edges[];
@ -37,8 +37,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
* @param i Current vertex under consideration * @param i Current vertex under consideration
*/ */
void printPath(int p[], int i) { void printPath(int p[], int i) {
if (p[i] == -1) // Found the path back to parent if (p[i] == -1) { // Found the path back to parent
{
return; return;
} }
printPath(p, p[i]); printPath(p, p[i]);
@ -50,10 +49,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
obj.go(); obj.go();
} }
public void public void go() { // shows distance to all vertices // Interactive run for understanding the class first time. Assumes source vertex is 0 and
go() // Interactive run for understanding the class first time. Assumes source vertex is 0 and
// shows distance to all vertices
{
Scanner sc = new Scanner(System.in); // Grab scanner object for user input Scanner sc = new Scanner(System.in); // Grab scanner object for user input
int i, v, e, u, ve, w, j, neg = 0; int i, v, e, u, ve, w, j, neg = 0;
System.out.println("Enter no. of vertices and edges please"); System.out.println("Enter no. of vertices and edges please");
@ -67,8 +63,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
w = sc.nextInt(); w = sc.nextInt();
arr[i] = new Edge(u, ve, w); arr[i] = new Edge(u, ve, w);
} }
int dist[] int dist[] = new int[v]; // Distance array for holding the finalized shortest path distance between source
= new int[v]; // Distance array for holding the finalized shortest path distance between source
// and all vertices // and all vertices
int p[] = new int[v]; // Parent array for holding the paths int p[] = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) { for (i = 0; i < v; i++) {
@ -78,8 +73,10 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
p[0] = -1; p[0] = -1;
for (i = 0; i < v - 1; i++) { for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) { for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE if (
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { (int) dist[arr[j].u] != Integer.MAX_VALUE &&
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u; p[arr[j].v] = arr[j].u;
} }
@ -87,14 +84,16 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
} }
// Final cycle for negative checking // Final cycle for negative checking
for (j = 0; j < e; j++) { for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { if (
(int) dist[arr[j].u] != Integer.MAX_VALUE &&
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
) {
neg = 1; neg = 1;
System.out.println("Negative cycle"); System.out.println("Negative cycle");
break; break;
} }
} }
if (neg == 0) // Go ahead and show results of computation if (neg == 0) { // Go ahead and show results of computation
{
System.out.println("Distances are: "); System.out.println("Distances are: ");
for (i = 0; i < v; i++) { for (i = 0; i < v; i++) {
System.out.println(i + " " + dist[i]); System.out.println(i + " " + dist[i]);
@ -114,15 +113,9 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
* @param end Ending vertex * @param end Ending vertex
* @param Edge Array of edges * @param Edge Array of edges
*/ */
public void show( public void show(int source, int end, Edge arr[]) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should
int source,
int end,
Edge arr[]) // Just shows results of computation, if graph is passed to it. The graph should
// be created by using addEdge() method and passed by calling getEdgeArray() method
{
int i, j, v = vertex, e = edge, neg = 0; int i, j, v = vertex, e = edge, neg = 0;
double dist[] double dist[] = new double[v]; // Distance array for holding the finalized shortest path distance between source
= new double[v]; // Distance array for holding the finalized shortest path distance between source
// and all vertices // and all vertices
int p[] = new int[v]; // Parent array for holding the paths int p[] = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) { for (i = 0; i < v; i++) {
@ -132,8 +125,10 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
p[source] = -1; p[source] = -1;
for (i = 0; i < v - 1; i++) { for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) { for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE if (
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { (int) dist[arr[j].u] != Integer.MAX_VALUE &&
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u; p[arr[j].v] = arr[j].u;
} }
@ -141,14 +136,16 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
} }
// Final cycle for negative checking // Final cycle for negative checking
for (j = 0; j < e; j++) { for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { if (
(int) dist[arr[j].u] != Integer.MAX_VALUE &&
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
) {
neg = 1; neg = 1;
System.out.println("Negative cycle"); System.out.println("Negative cycle");
break; break;
} }
} }
if (neg == 0) // Go ahead and show results of computaion if (neg == 0) { // Go ahead and show results of computaion
{
System.out.println("Distance is: " + dist[end]); System.out.println("Distance is: " + dist[end]);
System.out.println("Path followed:"); System.out.println("Path followed:");
System.out.print(source + " "); System.out.print(source + " ");
@ -162,8 +159,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
* @param y End vertex * @param y End vertex
* @param z Weight * @param z Weight
*/ */
public void addEdge(int x, int y, int z) // Adds unidirectional edge public void addEdge(int x, int y, int z) { // Adds unidirectional edge
{
edges[index++] = new Edge(x, y, z); edges[index++] = new Edge(x, y, z);
} }

View File

@ -16,7 +16,12 @@ import java.util.Arrays;
*/ */
public class BipartiteGrapfDFS { public class BipartiteGrapfDFS {
private static boolean bipartite(int V, ArrayList<ArrayList<Integer>> adj, int[] color, int node) { private static boolean bipartite(
int V,
ArrayList<ArrayList<Integer>> adj,
int[] color,
int node
) {
if (color[node] == -1) { if (color[node] == -1) {
color[node] = 1; color[node] = 1;
} }
@ -33,7 +38,10 @@ public class BipartiteGrapfDFS {
return true; return true;
} }
public static boolean isBipartite(int V, ArrayList<ArrayList<Integer>> adj) { public static boolean isBipartite(
int V,
ArrayList<ArrayList<Integer>> adj
) {
// Code here // Code here
int[] color = new int[V + 1]; int[] color = new int[V + 1];
Arrays.fill(color, -1); Arrays.fill(color, -1);
@ -49,7 +57,9 @@ public class BipartiteGrapfDFS {
} }
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); BufferedReader read = new BufferedReader(
new InputStreamReader(System.in)
);
int t = Integer.parseInt(read.readLine().trim()); int t = Integer.parseInt(read.readLine().trim());
while (t-- > 0) { while (t-- > 0) {
String[] S = read.readLine().trim().split(" "); String[] S = read.readLine().trim().split(" ");

View File

@ -137,7 +137,11 @@ public class ConnectedComponent {
graphInts.addEdge(8, 10); graphInts.addEdge(8, 10);
graphInts.addEdge(10, 8); graphInts.addEdge(10, 8);
System.out.println("Amount of different char-graphs: " + graphChars.countGraphs()); System.out.println(
System.out.println("Amount of different int-graphs: " + graphInts.countGraphs()); "Amount of different char-graphs: " + graphChars.countGraphs()
);
System.out.println(
"Amount of different int-graphs: " + graphInts.countGraphs()
);
} }
} }

View File

@ -24,7 +24,9 @@ class Cycle {
visited[i] = false; visited[i] = false;
} }
System.out.println("Enter the details of each edges <Start Node> <End Node>"); System.out.println(
"Enter the details of each edges <Start Node> <End Node>"
);
for (int i = 0; i < edges; i++) { for (int i = 0; i < edges; i++) {
int start, end; int start, end;

View File

@ -40,13 +40,17 @@ class dijkstras {
dist[src] = 0; dist[src] = 0;
for (int c = 0; c < k - 1; c++) { for (int c = 0; c < k - 1; c++) {
int u = minDist(dist, Set); int u = minDist(dist, Set);
Set[u] = true; Set[u] = true;
for (int v = 0; v < k; v++) { 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]; dist[v] = dist[u] + graph[u][v];
} }
} }
@ -56,21 +60,21 @@ class dijkstras {
} }
public static void main(String[] args) { public static void main(String[] args) {
int graph[][] = new int[][]{{0, 4, 0, 0, 0, 0, 0, 8, 0}, int graph[][] = new int[][] {
{4, 0, 8, 0, 0, 0, 0, 11, 0}, { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{0, 8, 0, 7, 0, 4, 0, 0, 2}, { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{0, 0, 7, 0, 9, 14, 0, 0, 0}, { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{0, 0, 0, 9, 0, 10, 0, 0, 0}, { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{0, 0, 4, 14, 10, 0, 2, 0, 0}, { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{0, 0, 0, 0, 0, 2, 0, 1, 6}, { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{8, 11, 0, 0, 0, 0, 1, 0, 7}, { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{0, 0, 2, 0, 0, 0, 6, 7, 0}}; { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 },
};
dijkstras t = new dijkstras(); dijkstras t = new dijkstras();
t.dijkstra(graph, 0); t.dijkstra(graph, 0);
}//main } //main
} //djikstras
}//djikstras
/* /*
OUTPUT : OUTPUT :
Vertex Distance Vertex Distance

View File

@ -9,31 +9,42 @@ public class FloydWarshall {
public static final int INFINITY = 999; public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices) { public FloydWarshall(int numberofvertices) {
DistanceMatrix DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source
= new int[numberofvertices + 1][numberofvertices
+ 1]; // stores the value of distance from all the possible path form the source
// vertex to destination vertex // vertex to destination vertex
// The matrix is initialized with 0's by default // The matrix is initialized with 0's by default
this.numberofvertices = numberofvertices; this.numberofvertices = numberofvertices;
} }
public void floydwarshall( public void floydwarshall(int AdjacencyMatrix[][]) { // calculates all the distances from source to destination vertex
int AdjacencyMatrix[][]) // calculates all the distances from source to destination vertex
{
for (int source = 1; source <= numberofvertices; source++) { for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) { for (
DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination]; int destination = 1;
destination <= numberofvertices;
destination++
) {
DistanceMatrix[source][destination] =
AdjacencyMatrix[source][destination];
} }
} }
for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) { for (
int intermediate = 1;
intermediate <= numberofvertices;
intermediate++
) {
for (int source = 1; source <= numberofvertices; source++) { for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) { for (
if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination] int destination = 1;
< DistanceMatrix[source][destination]) // if the new distance calculated is less then the earlier shortest destination <= numberofvertices;
// calculated distance it get replaced as new shortest distance destination++
{ ) {
if (
DistanceMatrix[source][intermediate] +
DistanceMatrix[intermediate][destination] <
DistanceMatrix[source][destination] DistanceMatrix[source][destination]
= DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][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];
} }
} }
} }
@ -44,7 +55,11 @@ public class FloydWarshall {
System.out.println(); System.out.println();
for (int source = 1; source <= numberofvertices; source++) { for (int source = 1; source <= numberofvertices; source++) {
System.out.print(source + "\t"); System.out.print(source + "\t");
for (int destination = 1; destination <= numberofvertices; destination++) { for (
int destination = 1;
destination <= numberofvertices;
destination++
) {
System.out.print(DistanceMatrix[source][destination] + "\t"); System.out.print(DistanceMatrix[source][destination] + "\t");
} }
System.out.println(); System.out.println();
@ -55,10 +70,15 @@ public class FloydWarshall {
Scanner scan = new Scanner(System.in); Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of vertices"); System.out.println("Enter the number of vertices");
int numberOfVertices = scan.nextInt(); int numberOfVertices = scan.nextInt();
int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1]; int[][] adjacencyMatrix = new int[numberOfVertices +
1][numberOfVertices + 1];
System.out.println("Enter the Weighted Matrix for the graph"); System.out.println("Enter the Weighted Matrix for the graph");
for (int source = 1; source <= numberOfVertices; source++) { for (int source = 1; source <= numberOfVertices; source++) {
for (int destination = 1; destination <= numberOfVertices; destination++) { for (
int destination = 1;
destination <= numberOfVertices;
destination++
) {
adjacencyMatrix[source][destination] = scan.nextInt(); adjacencyMatrix[source][destination] = scan.nextInt();
if (source == destination) { if (source == destination) {
adjacencyMatrix[source][destination] = 0; adjacencyMatrix[source][destination] = 0;

View File

@ -17,12 +17,12 @@ public class HamiltonianCycle {
* @return Array containing hamiltonian cycle * @return Array containing hamiltonian cycle
* else returns 1D array with value -1. * else returns 1D array with value -1.
*/ */
public int[] findHamiltonianCycle(int[][] graph){ public int[] findHamiltonianCycle(int[][] graph) {
this.V = graph.length; this.V = graph.length;
this.cycle = new int[this.V+1]; this.cycle = new int[this.V + 1];
//Initialize path array with -1 value //Initialize path array with -1 value
for(int i=0 ; i<this.cycle.length ; i++) { for (int i = 0; i < this.cycle.length; i++) {
this.cycle[i] = -1; this.cycle[i] = -1;
} }
@ -30,13 +30,12 @@ public class HamiltonianCycle {
this.cycle[0] = 0; this.cycle[0] = 0;
this.pathCount = 1; this.pathCount = 1;
if(!isPathFound(0)) { if (!isPathFound(0)) {
for(int i=0 ; i<this.cycle.length ; i++) { for (int i = 0; i < this.cycle.length; i++) {
this.cycle[i] = -1; this.cycle[i] = -1;
} }
} } else {
else { this.cycle[this.cycle.length - 1] = this.cycle[0];
this.cycle[this.cycle.length-1] = this.cycle[0];
} }
return cycle; return cycle;
@ -57,9 +56,9 @@ public class HamiltonianCycle {
return false; return false;
} }
for (int v = 0; v < this.V; v++){ for (int v = 0; v < this.V; v++) {
/** if connected **/ /** if connected **/
if (this.graph[vertex][v] == 1 ){ if (this.graph[vertex][v] == 1) {
/** add to path **/ /** add to path **/
this.cycle[this.pathCount++] = v; this.cycle[this.pathCount++] = v;
@ -87,8 +86,7 @@ public class HamiltonianCycle {
* Check if path is already selected * Check if path is already selected
* @param vertex Starting vertex * @param vertex Starting vertex
*/ */
public boolean isPresent(int vertex){ public boolean isPresent(int vertex) {
for (int i = 0; i < pathCount - 1; i++) { for (int i = 0; i < pathCount - 1; i++) {
if (cycle[i] == vertex) { if (cycle[i] == vertex) {
return true; return true;

View File

@ -1,12 +1,12 @@
package com.thealgorithms.datastructures.graphs; package com.thealgorithms.datastructures.graphs;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.HashMap; import java.util.HashMap;
import java.util.Set; import java.util.LinkedHashMap;
import java.util.Queue;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
/** /**
* An algorithm that sorts a graph in toplogical order. * An algorithm that sorts a graph in toplogical order.
@ -124,7 +124,6 @@ class TopologicalSort<E extends Comparable<E>> {
} }
return answer; return answer;
} }
} }
@ -134,7 +133,6 @@ class TopologicalSort<E extends Comparable<E>> {
public class KahnsAlgorithm { public class KahnsAlgorithm {
public static void main(String[] args) { public static void main(String[] args) {
//Graph definition and initialization //Graph definition and initialization
AdjacencyList<String> graph = new AdjacencyList<>(); AdjacencyList<String> graph = new AdjacencyList<>();
graph.addEdge("a", "b"); graph.addEdge("a", "b");

View File

@ -30,7 +30,12 @@ public class Kruskal {
} }
} }
private static void addEdge(HashSet<Edge>[] graph, int from, int to, int weight) { private static void addEdge(
HashSet<Edge>[] graph,
int from,
int to,
int weight
) {
graph[from].add(new Edge(from, to, weight)); graph[from].add(new Edge(from, to, weight));
} }
@ -53,7 +58,9 @@ public class Kruskal {
System.out.println("Initial Graph: "); System.out.println("Initial Graph: ");
for (int i = 0; i < graph.length; i++) { for (int i = 0; i < graph.length; i++) {
for (Edge edge : graph[i]) { for (Edge edge : graph[i]) {
System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); System.out.println(
i + " <-- weight " + edge.weight + " --> " + edge.to
);
} }
} }
@ -63,7 +70,9 @@ public class Kruskal {
System.out.println("\nMinimal Graph: "); System.out.println("\nMinimal Graph: ");
for (int i = 0; i < solGraph.length; i++) { for (int i = 0; i < solGraph.length; i++) {
for (Edge edge : solGraph[i]) { for (Edge edge : solGraph[i]) {
System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); System.out.println(
i + " <-- weight " + edge.weight + " --> " + edge.to
);
} }
} }
} }
@ -74,7 +83,9 @@ public class Kruskal {
// captain of i, stores the set with all the connected nodes to i // captain of i, stores the set with all the connected nodes to i
HashSet<Integer>[] connectedGroups = new HashSet[nodes]; HashSet<Integer>[] connectedGroups = new HashSet[nodes];
HashSet<Edge>[] minGraph = new HashSet[nodes]; HashSet<Edge>[] minGraph = new HashSet[nodes];
PriorityQueue<Edge> edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight))); PriorityQueue<Edge> edges = new PriorityQueue<>(
(Comparator.comparingInt(edge -> edge.weight))
);
for (int i = 0; i < nodes; i++) { for (int i = 0; i < nodes; i++) {
minGraph[i] = new HashSet<>(); minGraph[i] = new HashSet<>();
connectedGroups[i] = new HashSet<>(); connectedGroups[i] = new HashSet<>();
@ -87,12 +98,18 @@ public class Kruskal {
while (connectedElements != nodes && !edges.isEmpty()) { while (connectedElements != nodes && !edges.isEmpty()) {
Edge edge = edges.poll(); Edge edge = edges.poll();
// This if avoids cycles // This if avoids cycles
if (!connectedGroups[captain[edge.from]].contains(edge.to) if (
&& !connectedGroups[captain[edge.to]].contains(edge.from)) { !connectedGroups[captain[edge.from]].contains(edge.to) &&
!connectedGroups[captain[edge.to]].contains(edge.from)
) {
// merge sets of the captains of each point connected by the edge // merge sets of the captains of each point connected by the edge
connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]); connectedGroups[captain[edge.from]].addAll(
connectedGroups[captain[edge.to]]
);
// update captains of the elements merged // update captains of the elements merged
connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]); connectedGroups[captain[edge.from]].forEach(i ->
captain[i] = captain[edge.from]
);
// add Edge to minimal graph // add Edge to minimal graph
addEdge(minGraph, edge.from, edge.to, edge.weight); addEdge(minGraph, edge.from, edge.to, edge.weight);
// count how many elements have been merged // count how many elements have been merged

View File

@ -1,9 +1,9 @@
package com.thealgorithms.datastructures.graphs; package com.thealgorithms.datastructures.graphs;
import java.util.List;
import java.util.Queue;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/** /**
* Implementation of a graph in a matrix form Also known as an adjacency matrix * Implementation of a graph in a matrix form Also known as an adjacency matrix
@ -71,7 +71,9 @@ class AdjacencyMatrixGraph {
public AdjacencyMatrixGraph(int givenNumberOfVertices) { public AdjacencyMatrixGraph(int givenNumberOfVertices) {
this.setNumberOfVertices(givenNumberOfVertices); this.setNumberOfVertices(givenNumberOfVertices);
this.setNumberOfEdges(0); this.setNumberOfEdges(0);
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]); this.setAdjacency(
new int[givenNumberOfVertices][givenNumberOfVertices]
);
for (int i = 0; i < givenNumberOfVertices; i++) { for (int i = 0; i < givenNumberOfVertices; i++) {
for (int j = 0; j < givenNumberOfVertices; j++) { for (int j = 0; j < givenNumberOfVertices; j++) {
this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE; this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
@ -101,7 +103,7 @@ class AdjacencyMatrixGraph {
* Updates the number of edges in the graph * Updates the number of edges in the graph
* *
* @param newNumberOfEdges * @param newNumberOfEdges
* *
*/ */
private void setNumberOfEdges(int newNumberOfEdges) { private void setNumberOfEdges(int newNumberOfEdges) {
this._numberOfEdges = newNumberOfEdges; this._numberOfEdges = newNumberOfEdges;
@ -249,7 +251,11 @@ class AdjacencyMatrixGraph {
* has been visited * has been visited
* @param orderList the list to add vertices to as they are visited * @param orderList the list to add vertices to as they are visited
*/ */
private void depthFirstOrder(int currentVertex, boolean[] visited, List<Integer> orderList) { private void depthFirstOrder(
int currentVertex,
boolean[] visited,
List<Integer> orderList
) {
// If this vertex has already been visited, do nothing and return // If this vertex has already been visited, do nothing and return
if (visited[currentVertex]) { if (visited[currentVertex]) {
return; return;
@ -262,9 +268,11 @@ class AdjacencyMatrixGraph {
// Get the adjacency array for this vertex // Get the adjacency array for this vertex
int[] adjacent = _adjacency[currentVertex]; int[] adjacent = _adjacency[currentVertex];
for (int i = 0; i < adjacent.length; i++) // If an edge exists between the currentVertex and the vertex for (
// we are considering exploring, recurse on it 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) { if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) {
depthFirstOrder(i, visited, orderList); depthFirstOrder(i, visited, orderList);
} }
@ -313,9 +321,11 @@ class AdjacencyMatrixGraph {
// Get the adjacency array for the currentVertex and // Get the adjacency array for the currentVertex and
// check each node // check each node
int[] adjacent = _adjacency[currentVertex]; int[] adjacent = _adjacency[currentVertex];
for (int vertex = 0; vertex < adjacent.length; vertex++) // If an edge exists between the current vertex and the for (
// vertex we are considering exploring, we add it to the queue 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) { if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) {
queue.add(vertex); queue.add(vertex);
} }

View File

@ -5,6 +5,7 @@ package com.thealgorithms.datastructures.graphs;
* matrix representation of the graph * matrix representation of the graph
*/ */
class PrimMST { class PrimMST {
// Number of vertices in the graph // Number of vertices in the graph
private static final int V = 5; private static final int V = 5;
@ -30,7 +31,9 @@ class PrimMST {
void printMST(int parent[], int n, int graph[][]) { void printMST(int parent[], int n, int graph[][]) {
System.out.println("Edge Weight"); System.out.println("Edge Weight");
for (int i = 1; i < V; i++) { for (int i = 1; i < V; i++) {
System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]); System.out.println(
parent[i] + " - " + i + " " + graph[i][parent[i]]
);
} }
} }
@ -69,11 +72,17 @@ class PrimMST {
// Update key value and parent index of the adjacent // Update key value and parent index of the adjacent
// vertices of the picked vertex. Consider only those // vertices of the picked vertex. Consider only those
// vertices which are not yet included in MST // vertices which are not yet included in MST
for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m for (
// mstSet[v] is false for vertices not yet included in MST int v = 0;
// Update the key only if graph[u][v] is smaller than key[v] v < V;
v++
) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is false for vertices not yet included in MST // graph[u][v] is non zero only for adjacent vertices of m
{ {
if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { if (
graph[u][v] != 0 &&
mstSet[v] == false &&
graph[u][v] < key[v]
) {
parent[v] = u; parent[v] = u;
key[v] = graph[u][v]; key[v] = graph[u][v];
} }
@ -94,9 +103,13 @@ class PrimMST {
(3)-------(4) (3)-------(4)
9 */ 9 */
PrimMST t = new PrimMST(); PrimMST t = new PrimMST();
int graph[][] int graph[][] = new int[][] {
= new int[][]{ { 0, 2, 0, 6, 0 },
{0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0},}; { 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 },
};
// Print the solution // Print the solution
t.primMST(graph); t.primMST(graph);

View File

@ -5,6 +5,7 @@ import java.util.LinkedList;
// implementation of generic hashmaps using array of Linked Lists // implementation of generic hashmaps using array of Linked Lists
public class GenericHashMapUsingArray<K, V> { public class GenericHashMapUsingArray<K, V> {
private int size; // n (total number of key-value pairs) private int size; // n (total number of key-value pairs)
private LinkedList<Node>[] buckets; // N = buckets.length private LinkedList<Node>[] buckets; // N = buckets.length
private float lf = 0.75f; private float lf = 0.75f;
@ -13,6 +14,7 @@ public class GenericHashMapUsingArray<K, V> {
initBuckets(16); initBuckets(16);
size = 0; size = 0;
} }
// load factor = 0.75 means if we need to add 100 items and we have added // load factor = 0.75 means if we need to add 100 items and we have added
// 75, then adding 76th item it will double the size, copy all elements // 75, then adding 76th item it will double the size, copy all elements
// & then add 76th item. // & then add 76th item.
@ -114,6 +116,7 @@ public class GenericHashMapUsingArray<K, V> {
} }
public class Node { public class Node {
K key; K key;
V value; V value;

View File

@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
public class GenericHashMapUsingArrayList<K, V> { public class GenericHashMapUsingArrayList<K, V> {
ArrayList<LinkedList<Node>> buckets; ArrayList<LinkedList<Node>> buckets;
private float lf = 0.5f; private float lf = 0.5f;
private int size; private int size;
@ -100,6 +101,7 @@ public class GenericHashMapUsingArrayList<K, V> {
} }
private class Node { private class Node {
K key; K key;
V val; V val;
@ -108,5 +110,4 @@ public class GenericHashMapUsingArrayList<K, V> {
this.val = val; this.val = val;
} }
} }
} }

View File

@ -1,6 +1,5 @@
package com.thealgorithms.datastructures.hashmap.hashing; package com.thealgorithms.datastructures.hashmap.hashing;
import java.lang.Math; import java.lang.Math;
import java.util.Objects; import java.util.Objects;
@ -71,19 +70,26 @@ public class HashMapCuckooHashing {
int hash, loopCounter = 0; int hash, loopCounter = 0;
if (isFull()) { if (isFull()) {
System.out.println("Hash table is full, lengthening & rehashing table"); System.out.println(
"Hash table is full, lengthening & rehashing table"
);
reHashTableIncreasesTableSize(); reHashTableIncreasesTableSize();
} }
if (checkTableContainsKey(key)) { if (checkTableContainsKey(key)) {
throw new IllegalArgumentException("Key already inside, no duplicates allowed"); throw new IllegalArgumentException(
"Key already inside, no duplicates allowed"
);
} }
while (loopCounter <= thresh) { while (loopCounter <= thresh) {
loopCounter++; loopCounter++;
hash = hashFunction1(key); hash = hashFunction1(key);
if ((buckets[hash] == null) || Objects.equals(buckets[hash], AVAILABLE)) { if (
(buckets[hash] == null) ||
Objects.equals(buckets[hash], AVAILABLE)
) {
buckets[hash] = wrappedInt; buckets[hash] = wrappedInt;
size++; size++;
checkLoadFactor(); checkLoadFactor();
@ -110,7 +116,9 @@ public class HashMapCuckooHashing {
buckets[hash] = wrappedInt; buckets[hash] = wrappedInt;
wrappedInt = temp; wrappedInt = temp;
} }
System.out.println("Infinite loop occurred, lengthening & rehashing table"); System.out.println(
"Infinite loop occurred, lengthening & rehashing table"
);
reHashTableIncreasesTableSize(); reHashTableIncreasesTableSize();
insertKey2HashTable(key); insertKey2HashTable(key);
} }
@ -132,7 +140,6 @@ public class HashMapCuckooHashing {
this.thresh = (int) (Math.log(tableSize) / Math.log(2)) + 2; this.thresh = (int) (Math.log(tableSize) / Math.log(2)) + 2;
} }
/** /**
* deletes a key from the hash map and adds an available placeholder * deletes a key from the hash map and adds an available placeholder
* *
@ -157,7 +164,9 @@ public class HashMapCuckooHashing {
size--; size--;
return; return;
} }
throw new IllegalArgumentException("Key " + key + " already inside, no duplicates allowed"); throw new IllegalArgumentException(
"Key " + key + " already inside, no duplicates allowed"
);
} }
/** /**
@ -168,7 +177,9 @@ public class HashMapCuckooHashing {
if ((buckets[i] == null) || Objects.equals(buckets[i], AVAILABLE)) { if ((buckets[i] == null) || Objects.equals(buckets[i], AVAILABLE)) {
System.out.println("Bucket " + i + ": Empty"); System.out.println("Bucket " + i + ": Empty");
} else { } else {
System.out.println("Bucket " + i + ": " + buckets[i].toString()); System.out.println(
"Bucket " + i + ": " + buckets[i].toString()
);
} }
} }
System.out.println(); System.out.println();
@ -191,20 +202,32 @@ public class HashMapCuckooHashing {
if (Objects.equals(buckets[hash], wrappedInt)) return hash; if (Objects.equals(buckets[hash], wrappedInt)) return hash;
hash = hashFunction2(key); hash = hashFunction2(key);
if (!Objects.equals(buckets[hash], wrappedInt)) if (
throw new IllegalArgumentException("Key " + key + " not found in table"); !Objects.equals(buckets[hash], wrappedInt)
else { ) throw new IllegalArgumentException(
"Key " + key + " not found in table"
); else {
return hash; return hash;
} }
} }
/** /**
* checks if key is inside without any output other than returned boolean. * checks if key is inside without any output other than returned boolean.
* *
* @param key the desired key to be found * @param key the desired key to be found
* @return int the index where the key is located * @return int the index where the key is located
*/ */
public boolean checkTableContainsKey(int key){ public boolean checkTableContainsKey(int key) {
return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key)) || (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key)); return (
(
buckets[hashFunction1(key)] != null &&
buckets[hashFunction1(key)].equals(key)
) ||
(
buckets[hashFunction2(key)] != null &&
buckets[hashFunction2(key)] == key
)
);
} }
/** /**
@ -214,7 +237,10 @@ public class HashMapCuckooHashing {
public double checkLoadFactor() { public double checkLoadFactor() {
double factor = (double) size / tableSize; double factor = (double) size / tableSize;
if (factor > .7) { if (factor > .7) {
System.out.printf("Load factor is %.2f , rehashing table\n", factor); System.out.printf(
"Load factor is %.2f , rehashing table\n",
factor
);
reHashTableIncreasesTableSize(); reHashTableIncreasesTableSize();
} }
return factor; return factor;
@ -250,5 +276,8 @@ public class HashMapCuckooHashing {
} }
return response; return response;
} }
public int getNumberOfKeysInTable(){return size;}
public int getNumberOfKeysInTable() {
return size;
}
} }

View File

@ -107,7 +107,9 @@ public class HashMapLinearProbing {
if (buckets[i] == null || buckets[i] == AVAILABLE) { if (buckets[i] == null || buckets[i] == AVAILABLE) {
System.out.println("Bucket " + i + ": Empty"); System.out.println("Bucket " + i + ": Empty");
} else { } else {
System.out.println("Bucket " + i + ": " + buckets[i].toString()); System.out.println(
"Bucket " + i + ": " + buckets[i].toString()
);
} }
} }
} }
@ -133,8 +135,7 @@ public class HashMapLinearProbing {
buckets[hash] = AVAILABLE; buckets[hash] = AVAILABLE;
return hash; return hash;
} }
} catch (Exception E) { } catch (Exception E) {}
}
if (hash + 1 < hsize) { if (hash + 1 < hsize) {
hash++; hash++;
@ -159,7 +160,9 @@ public class HashMapLinearProbing {
public void checkLoadFactor() { public void checkLoadFactor() {
double factor = (double) size / hsize; double factor = (double) size / hsize;
if (factor > .7) { if (factor > .7) {
System.out.println("Load factor is " + factor + ", lengthening table"); System.out.println(
"Load factor is " + factor + ", lengthening table"
);
lengthenTable(); lengthenTable();
} else { } else {
System.out.println("Load factor is " + factor); System.out.println("Load factor is " + factor);

View File

@ -15,7 +15,9 @@ import java.util.Map;
public class Intersection { public class Intersection {
public static List<Integer> intersection(int[] arr1, int[] arr2) { public static List<Integer> intersection(int[] arr1, int[] arr2) {
if (arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0) { if (
arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0
) {
return Collections.emptyList(); return Collections.emptyList();
} }
Map<Integer, Integer> cnt = new HashMap<>(16); Map<Integer, Integer> cnt = new HashMap<>(16);
@ -32,7 +34,5 @@ public class Intersection {
return res; return res;
} }
private Intersection() { private Intersection() {}
}
} }

View File

@ -5,7 +5,6 @@ import java.util.Scanner;
public class Main { public class Main {
public static void main(String[] args) { public static void main(String[] args) {
int choice, key; int choice, key;
HashMap h = new HashMap(7); HashMap h = new HashMap(7);
@ -21,27 +20,31 @@ public class Main {
choice = In.nextInt(); choice = In.nextInt();
switch (choice) { switch (choice) {
case 1: { case 1:
System.out.println("Enter the Key: "); {
key = In.nextInt(); System.out.println("Enter the Key: ");
h.insertHash(key); key = In.nextInt();
break; h.insertHash(key);
} break;
case 2: { }
System.out.println("Enter the Key delete: "); case 2:
key = In.nextInt(); {
h.deleteHash(key); System.out.println("Enter the Key delete: ");
break; key = In.nextInt();
} h.deleteHash(key);
case 3: { break;
System.out.println("Print table"); }
h.displayHashtable(); case 3:
break; {
} System.out.println("Print table");
case 4: { h.displayHashtable();
In.close(); break;
return; }
} case 4:
{
In.close();
return;
}
} }
} }
} }

View File

@ -3,8 +3,8 @@ package com.thealgorithms.datastructures.hashmap.hashing;
import java.util.Scanner; import java.util.Scanner;
public class MainCuckooHashing { public class MainCuckooHashing {
public static void main(String[] args) {
public static void main(String[] args) {
int choice, key; int choice, key;
HashMapCuckooHashing h = new HashMapCuckooHashing(7); HashMapCuckooHashing h = new HashMapCuckooHashing(7);
@ -24,41 +24,59 @@ public class MainCuckooHashing {
choice = In.nextInt(); choice = In.nextInt();
switch (choice) { switch (choice) {
case 1: { case 1:
System.out.println("Enter the Key: "); {
key = In.nextInt(); System.out.println("Enter the Key: ");
h.insertKey2HashTable(key); key = In.nextInt();
break; h.insertKey2HashTable(key);
} break;
case 2: { }
System.out.println("Enter the Key delete: "); case 2:
key = In.nextInt(); {
h.deleteKeyFromHashTable(key); System.out.println("Enter the Key delete: ");
break; key = In.nextInt();
} h.deleteKeyFromHashTable(key);
case 3: { break;
System.out.println("Print table:\n"); }
h.displayHashtable(); case 3:
break; {
} System.out.println("Print table:\n");
case 4: { h.displayHashtable();
In.close(); break;
return; }
} case 4:
case 5: { {
System.out.println("Enter the Key to find and print: "); In.close();
key = In.nextInt(); return;
System.out.println("Key: " + key + " is at index: " + h.findKeyInTable(key) + "\n"); }
break; case 5:
} {
case 6: { System.out.println(
System.out.printf("Load factor is: %.2f\n", h.checkLoadFactor()); "Enter the Key to find and print: "
break; );
} key = In.nextInt();
case 7: { System.out.println(
h.reHashTableIncreasesTableSize(); "Key: " +
break; key +
} " is at index: " +
h.findKeyInTable(key) +
"\n"
);
break;
}
case 6:
{
System.out.printf(
"Load factor is: %.2f\n",
h.checkLoadFactor()
);
break;
}
case 7:
{
h.reHashTableIncreasesTableSize();
break;
}
} }
} }
} }

View File

@ -5,7 +5,6 @@ import java.util.Scanner;
public class MainLinearProbing { public class MainLinearProbing {
public static void main(String[] args) { public static void main(String[] args) {
int choice, key; int choice, key;
HashMapLinearProbing h = new HashMapLinearProbing(7); HashMapLinearProbing h = new HashMapLinearProbing(7);
@ -23,37 +22,47 @@ public class MainLinearProbing {
choice = In.nextInt(); choice = In.nextInt();
switch (choice) { switch (choice) {
case 1: { case 1:
System.out.println("Enter the Key: "); {
key = In.nextInt(); System.out.println("Enter the Key: ");
h.insertHash(key); key = In.nextInt();
break; h.insertHash(key);
} break;
case 2: { }
System.out.println("Enter the Key delete: "); case 2:
key = In.nextInt(); {
h.deleteHash(key); System.out.println("Enter the Key delete: ");
break; key = In.nextInt();
} h.deleteHash(key);
case 3: { break;
System.out.println("Print table"); }
h.displayHashtable(); case 3:
break; {
} System.out.println("Print table");
case 4: { h.displayHashtable();
In.close(); break;
return; }
} case 4:
case 5: { {
System.out.println("Enter the Key to find and print: "); In.close();
key = In.nextInt(); return;
System.out.println("Key: " + key + " is at index: " + h.findHash(key)); }
break; case 5:
} {
case 6: { System.out.println(
h.checkLoadFactor(); "Enter the Key to find and print: "
break; );
} key = In.nextInt();
System.out.println(
"Key: " + key + " is at index: " + h.findHash(key)
);
break;
}
case 6:
{
h.checkLoadFactor();
break;
}
} }
} }
} }

View File

@ -1,6 +1,5 @@
package com.thealgorithms.datastructures.heaps; package com.thealgorithms.datastructures.heaps;
public class FibonacciHeap { public class FibonacciHeap {
private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2; private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;
@ -48,7 +47,7 @@ public class FibonacciHeap {
* $ret = the HeapNode we inserted * $ret = the HeapNode we inserted
*/ */
public HeapNode insert(int key) { public HeapNode insert(int key) {
HeapNode toInsert = new HeapNode(key); //creates the node HeapNode toInsert = new HeapNode(key); //creates the node
if (this.empty()) { if (this.empty()) {
this.min = toInsert; this.min = toInsert;
} else { //tree is not empty } else { //tree is not empty
@ -142,9 +141,12 @@ public class FibonacciHeap {
*/ */
public int[] countersRep() { public int[] countersRep() {
if (this.empty()) { if (this.empty()) {
return new int[0]; ///return an empty array return new int[0]; ///return an empty array
} }
int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; //creates the array int[] rankArray = new int[(int) Math.floor(
Math.log(this.size()) / Math.log(GOLDEN_RATIO)
) +
1]; //creates the array
rankArray[this.min.rank]++; rankArray[this.min.rank]++;
HeapNode curr = this.min.next; HeapNode curr = this.min.next;
while (curr != this.min) { while (curr != this.min) {
@ -161,8 +163,8 @@ public class FibonacciHeap {
* @post (numOfnodes = = $prev numOfnodes - 1) * @post (numOfnodes = = $prev numOfnodes - 1)
*/ */
public void delete(HeapNode x) { public void delete(HeapNode x) {
this.decreaseKey(x, x.getKey() + 1); //change key to be the minimal (-1) this.decreaseKey(x, x.getKey() + 1); //change key to be the minimal (-1)
this.deleteMin(); //delete it this.deleteMin(); //delete it
} }
/** /**
@ -174,7 +176,7 @@ public class FibonacciHeap {
private void decreaseKey(HeapNode x, int delta) { private void decreaseKey(HeapNode x, int delta) {
int newKey = x.getKey() - delta; int newKey = x.getKey() - delta;
x.key = newKey; x.key = newKey;
if (x.isRoot()) {//no parent to x if (x.isRoot()) { //no parent to x
this.updateMin(x); this.updateMin(x);
return; return;
} }
@ -229,7 +231,7 @@ public class FibonacciHeap {
* @post (numOfnodes == $prev numOfnodes) * @post (numOfnodes == $prev numOfnodes)
*/ */
private void cascadingCuts(HeapNode curr) { private void cascadingCuts(HeapNode curr) {
if (!curr.isMarked()) { //stop the recursion if (!curr.isMarked()) { //stop the recursion
curr.mark(); curr.mark();
if (!curr.isRoot()) this.markedHeapNoodesCounter++; if (!curr.isRoot()) this.markedHeapNoodesCounter++;
return; return;
@ -257,7 +259,7 @@ public class FibonacciHeap {
if (curr.parent.child == curr) { //we should change the parent's child if (curr.parent.child == curr) { //we should change the parent's child
if (curr.next == curr) { //curr do not have brothers if (curr.next == curr) { //curr do not have brothers
curr.parent.child = null; curr.parent.child = null;
} else {//curr have brothers } else { //curr have brothers
curr.parent.child = curr.next; curr.parent.child = curr.next;
} }
} }
@ -272,7 +274,6 @@ public class FibonacciHeap {
totalCuts++; totalCuts++;
} }
/* /*
* *
*/ */
@ -285,7 +286,10 @@ public class FibonacciHeap {
* *
*/ */
private HeapNode[] toBuckets(HeapNode curr) { private HeapNode[] toBuckets(HeapNode curr) {
HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; HeapNode[] buckets = new HeapNode[(int) Math.floor(
Math.log(this.size()) / Math.log(GOLDEN_RATIO)
) +
1];
curr.prev.next = null; curr.prev.next = null;
HeapNode tmpCurr; HeapNode tmpCurr;
while (curr != null) { while (curr != null) {
@ -347,7 +351,6 @@ public class FibonacciHeap {
return c1; return c1;
} }
/** /**
* public class HeapNode * public class HeapNode
* each HeapNode belongs to a heap (Inner class) * each HeapNode belongs to a heap (Inner class)
@ -381,7 +384,6 @@ public class FibonacciHeap {
return this.key; return this.key;
} }
/* /*
* checks whether the node is marked * checks whether the node is marked
* $ret = true if one child has been cut * $ret = true if one child has been cut
@ -397,7 +399,7 @@ public class FibonacciHeap {
private void mark() { private void mark() {
if (this.isRoot()) { if (this.isRoot()) {
return; return;
} //check if the node is a root } //check if the node is a root
this.marked = true; this.marked = true;
} }

View File

@ -2,70 +2,88 @@ package com.thealgorithms.datastructures.heaps;
import java.util.*; import java.util.*;
public class GenericHeap <T extends Comparable <T> >{ public class GenericHeap<T extends Comparable<T>> {
ArrayList <T> data=new ArrayList<>();
HashMap<T,Integer> map=new HashMap<>(); ArrayList<T> data = new ArrayList<>();
public void add(T item) { HashMap<T, Integer> map = new HashMap<>();
this.data.add(item);
map.put(item,this.data.size()-1);// public void add(T item) {
upHeapify(this.data.size()-1); this.data.add(item);
} map.put(item, this.data.size() - 1); //
private void upHeapify(int ci) { upHeapify(this.data.size() - 1);
int pi=(ci-1)/2; }
if(isLarger(this.data.get(ci),this.data.get(pi))>0) {
swap(pi,ci); private void upHeapify(int ci) {
upHeapify(pi); int pi = (ci - 1) / 2;
} if (isLarger(this.data.get(ci), this.data.get(pi)) > 0) {
} swap(pi, ci);
public void display() { upHeapify(pi);
System.out.println(this.data); }
} }
public int size() {
return this.data.size(); public void display() {
} System.out.println(this.data);
public boolean isEmpty() { }
return this.size()==0;
} public int size() {
public T remove() { return this.data.size();
this.swap(0,this.size()-1); }
T rv=this.data.remove(this.size()-1);
downHeapify(0); public boolean isEmpty() {
map.remove(rv); return this.size() == 0;
return rv; }
}
private void downHeapify(int pi) { public T remove() {
int lci=2*pi+1; this.swap(0, this.size() - 1);
int rci=2*pi+2; T rv = this.data.remove(this.size() - 1);
int mini=pi; downHeapify(0);
if(lci<this.size() && isLarger(this.data.get(lci),this.data.get(mini))>0) { map.remove(rv);
mini=lci; return rv;
} }
if(rci<this.size() && isLarger(this.data.get(rci),this.data.get(mini))>0) {
mini=rci; private void downHeapify(int pi) {
} int lci = 2 * pi + 1;
if(mini!=pi) { int rci = 2 * pi + 2;
this.swap(pi,mini); int mini = pi;
downHeapify(mini); if (
} lci < this.size() &&
} isLarger(this.data.get(lci), this.data.get(mini)) > 0
public T get() { ) {
return this.data.get(0); mini = lci;
} }
//t has higher property then return +ve if (
private int isLarger(T t,T o) { rci < this.size() &&
return t.compareTo(o); isLarger(this.data.get(rci), this.data.get(mini)) > 0
} ) {
private void swap(int i,int j) { mini = rci;
T ith=this.data.get(i); }
T jth=this.data.get(j); if (mini != pi) {
this.data.set(i,jth); this.swap(pi, mini);
this.data.set(j,ith); downHeapify(mini);
map.put(ith,j); }
map.put(jth,i); }
}
public void updatePriority(T item) { public T get() {
int index=map.get(item); return this.data.get(0);
//because we enter lesser value then old vale }
upHeapify(index);
} //t has higher property then return +ve
private int isLarger(T t, T o) {
return t.compareTo(o);
}
private void swap(int i, int j) {
T ith = this.data.get(i);
T jth = this.data.get(j);
this.data.set(i, jth);
this.data.set(j, ith);
map.put(ith, j);
map.put(jth, i);
}
public void updatePriority(T item) {
int index = map.get(item);
//because we enter lesser value then old vale
upHeapify(index);
}
} }

View File

@ -19,7 +19,6 @@ package com.thealgorithms.datastructures.heaps;
* @author Nicolas Renard * @author Nicolas Renard
*/ */
public interface Heap { public interface Heap {
/** /**
* @return the top element in the heap, the one with lowest key for min-heap * @return the top element in the heap, the one with lowest key for min-heap
* or with the highest key for max-heap * or with the highest key for max-heap

View File

@ -122,8 +122,10 @@ public class HeapElement {
return false; return false;
} }
HeapElement otherHeapElement = (HeapElement) o; HeapElement otherHeapElement = (HeapElement) o;
return (this.key == otherHeapElement.key) return (
&& (this.additionalInfo.equals(otherHeapElement.additionalInfo)); (this.key == otherHeapElement.key) &&
(this.additionalInfo.equals(otherHeapElement.additionalInfo))
);
} }
return false; return false;
} }
@ -132,7 +134,10 @@ public class HeapElement {
public int hashCode() { public int hashCode() {
int result = 0; int result = 0;
result = 31 * result + (int) key; result = 31 * result + (int) key;
result = 31 * result + (additionalInfo != null ? additionalInfo.hashCode() : 0); result =
31 *
result +
(additionalInfo != null ? additionalInfo.hashCode() : 0);
return result; return result;
} }
} }

View File

@ -70,22 +70,30 @@ public class MaxHeap implements Heap {
// than any of its children's // than any of its children's
private void toggleDown(int elementIndex) { private void toggleDown(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey(); double key = maxHeap.get(elementIndex - 1).getKey();
boolean wrongOrder boolean wrongOrder =
= (key < getElementKey(elementIndex * 2)) (key < getElementKey(elementIndex * 2)) ||
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) { while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any. // Check whether it shall swap the element with its left child or its right one if any.
if ((2 * elementIndex < maxHeap.size()) if (
&& (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) { (2 * elementIndex < maxHeap.size()) &&
(
getElementKey(elementIndex * 2 + 1) >
getElementKey(elementIndex * 2)
)
) {
swap(elementIndex, 2 * elementIndex + 1); swap(elementIndex, 2 * elementIndex + 1);
elementIndex = 2 * elementIndex + 1; elementIndex = 2 * elementIndex + 1;
} else { } else {
swap(elementIndex, 2 * elementIndex); swap(elementIndex, 2 * elementIndex);
elementIndex = 2 * elementIndex; elementIndex = 2 * elementIndex;
} }
wrongOrder wrongOrder =
= (key < getElementKey(elementIndex * 2)) (key < getElementKey(elementIndex * 2)) ||
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); (
key <
getElementKey(Math.min(elementIndex * 2, maxHeap.size()))
);
} }
} }
@ -103,9 +111,10 @@ public class MaxHeap implements Heap {
@Override @Override
public void deleteElement(int elementIndex) { public void deleteElement(int elementIndex) {
if (maxHeap.isEmpty()) if (maxHeap.isEmpty()) try {
try { throw new EmptyHeapException(
throw new EmptyHeapException("Attempt to delete an element from an empty heap"); "Attempt to delete an element from an empty heap"
);
} catch (EmptyHeapException e) { } catch (EmptyHeapException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -116,13 +125,22 @@ public class MaxHeap implements Heap {
maxHeap.set(elementIndex - 1, getElement(maxHeap.size())); maxHeap.set(elementIndex - 1, getElement(maxHeap.size()));
maxHeap.remove(maxHeap.size()); maxHeap.remove(maxHeap.size());
// Shall the new element be moved up... // Shall the new element be moved up...
if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) { if (
getElementKey(elementIndex) >
getElementKey((int) Math.floor(elementIndex / 2.0))
) {
toggleUp(elementIndex); toggleUp(elementIndex);
} // ... or down ? } // ... or down ?
else if (((2 * elementIndex <= maxHeap.size()) else if (
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) (
|| ((2 * elementIndex < maxHeap.size()) (2 * elementIndex <= maxHeap.size()) &&
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) { (getElementKey(elementIndex) < getElementKey(elementIndex * 2))
) ||
(
(2 * elementIndex < maxHeap.size()) &&
(getElementKey(elementIndex) < getElementKey(elementIndex * 2))
)
) {
toggleDown(elementIndex); toggleDown(elementIndex);
} }
} }
@ -132,7 +150,9 @@ public class MaxHeap implements Heap {
try { try {
return extractMax(); return extractMax();
} catch (Exception e) { } catch (Exception e) {
throw new EmptyHeapException("Heap is empty. Error retrieving element"); throw new EmptyHeapException(
"Heap is empty. Error retrieving element"
);
} }
} }
} }

View File

@ -64,22 +64,30 @@ public class MinHeap implements Heap {
// than any of its children's // than any of its children's
private void toggleDown(int elementIndex) { private void toggleDown(int elementIndex) {
double key = minHeap.get(elementIndex - 1).getKey(); double key = minHeap.get(elementIndex - 1).getKey();
boolean wrongOrder boolean wrongOrder =
= (key > getElementKey(elementIndex * 2)) (key > getElementKey(elementIndex * 2)) ||
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
while ((2 * elementIndex <= minHeap.size()) && wrongOrder) { while ((2 * elementIndex <= minHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any. // Check whether it shall swap the element with its left child or its right one if any.
if ((2 * elementIndex < minHeap.size()) if (
&& (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) { (2 * elementIndex < minHeap.size()) &&
(
getElementKey(elementIndex * 2 + 1) <
getElementKey(elementIndex * 2)
)
) {
swap(elementIndex, 2 * elementIndex + 1); swap(elementIndex, 2 * elementIndex + 1);
elementIndex = 2 * elementIndex + 1; elementIndex = 2 * elementIndex + 1;
} else { } else {
swap(elementIndex, 2 * elementIndex); swap(elementIndex, 2 * elementIndex);
elementIndex = 2 * elementIndex; elementIndex = 2 * elementIndex;
} }
wrongOrder wrongOrder =
= (key > getElementKey(elementIndex * 2)) (key > getElementKey(elementIndex * 2)) ||
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); (
key >
getElementKey(Math.min(elementIndex * 2, minHeap.size()))
);
} }
} }
@ -97,9 +105,10 @@ public class MinHeap implements Heap {
@Override @Override
public void deleteElement(int elementIndex) { public void deleteElement(int elementIndex) {
if (minHeap.isEmpty()) if (minHeap.isEmpty()) try {
try { throw new EmptyHeapException(
throw new EmptyHeapException("Attempt to delete an element from an empty heap"); "Attempt to delete an element from an empty heap"
);
} catch (EmptyHeapException e) { } catch (EmptyHeapException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -110,13 +119,22 @@ public class MinHeap implements Heap {
minHeap.set(elementIndex - 1, getElement(minHeap.size())); minHeap.set(elementIndex - 1, getElement(minHeap.size()));
minHeap.remove(minHeap.size()); minHeap.remove(minHeap.size());
// Shall the new element be moved up... // Shall the new element be moved up...
if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) { if (
getElementKey(elementIndex) <
getElementKey((int) Math.floor(elementIndex / 2.0))
) {
toggleUp(elementIndex); toggleUp(elementIndex);
} // ... or down ? } // ... or down ?
else if (((2 * elementIndex <= minHeap.size()) else if (
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) (
|| ((2 * elementIndex < minHeap.size()) (2 * elementIndex <= minHeap.size()) &&
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) { (getElementKey(elementIndex) > getElementKey(elementIndex * 2))
) ||
(
(2 * elementIndex < minHeap.size()) &&
(getElementKey(elementIndex) > getElementKey(elementIndex * 2))
)
) {
toggleDown(elementIndex); toggleDown(elementIndex);
} }
} }
@ -126,7 +144,9 @@ public class MinHeap implements Heap {
try { try {
return extractMin(); return extractMin();
} catch (Exception e) { } catch (Exception e) {
throw new EmptyHeapException("Heap is empty. Error retrieving element"); throw new EmptyHeapException(
"Heap is empty. Error retrieving element"
);
} }
} }
} }

View File

@ -88,7 +88,10 @@ public class MinPriorityQueue {
while (2 * k <= this.size || 2 * k + 1 <= this.size) { while (2 * k <= this.size || 2 * k + 1 <= this.size) {
int minIndex; int minIndex;
if (this.heap[2 * k] >= this.heap[k]) { if (this.heap[2 * k] >= this.heap[k]) {
if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) { if (
2 * k + 1 <= this.size &&
this.heap[2 * k + 1] >= this.heap[k]
) {
break; break;
} else if (2 * k + 1 > this.size) { } else if (2 * k + 1 > this.size) {
break; break;
@ -97,8 +100,14 @@ public class MinPriorityQueue {
if (2 * k + 1 > this.size) { if (2 * k + 1 > this.size) {
minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k; minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k;
} else { } else {
if (this.heap[k] > this.heap[2 * k] || this.heap[k] > this.heap[2 * k + 1]) { if (
minIndex = this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1; this.heap[k] > this.heap[2 * k] ||
this.heap[k] > this.heap[2 * k + 1]
) {
minIndex =
this.heap[2 * k] < this.heap[2 * k + 1]
? 2 * k
: 2 * k + 1;
} else { } else {
minIndex = k; minIndex = k;
} }

View File

@ -38,7 +38,9 @@ public class CircleLinkedList<E> {
public void append(E value) { public void append(E value) {
if (value == null) { if (value == null) {
// we do not want to add null elements to the list. // we do not want to add null elements to the list.
throw new NullPointerException("Cannot add null element to the list"); throw new NullPointerException(
"Cannot add null element to the list"
);
} }
// head.next points to the last element; // head.next points to the last element;
if (tail == null) { if (tail == null) {
@ -57,7 +59,7 @@ public class CircleLinkedList<E> {
String s = "[ "; String s = "[ ";
while (p != head) { while (p != head) {
s += p.value; s += p.value;
if (p != tail){ if (p != tail) {
s += " , "; s += " , ";
} }
p = p.next; p = p.next;
@ -68,7 +70,9 @@ public class CircleLinkedList<E> {
public E remove(int pos) { public E remove(int pos) {
if (pos > size || pos < 0) { if (pos > size || pos < 0) {
// catching errors // catching errors
throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); throw new IndexOutOfBoundsException(
"position cannot be greater than size or negative"
);
} }
// we need to keep track of the element before the element we want to remove we can see why // we need to keep track of the element before the element we want to remove we can see why
// bellow. // bellow.

View File

@ -33,15 +33,14 @@ public class CreateAndDetectLoop {
} }
Node temp = head; Node temp = head;
int count = 1; int count = 1;
while (count < k) { // Traverse the list till the kth node while (count < k) { // Traverse the list till the kth node
temp = temp.next; temp = temp.next;
count++; count++;
} }
Node connectedPoint = temp; Node connectedPoint = temp;
while (temp.next != null) // Traverse remaining nodes while (temp.next != null) { // Traverse remaining nodes
{
temp = temp.next; temp = temp.next;
} }

View File

@ -46,12 +46,9 @@ public class CursorLinkedList<T> {
} }
public void printList() { public void printList() {
if (head != -1) { if (head != -1) {
int start = head; int start = head;
while (start != -1) { while (start != -1) {
T element = cursorSpace[start].element; T element = cursorSpace[start].element;
System.out.println(element.toString()); System.out.println(element.toString());
start = cursorSpace[start].next; start = cursorSpace[start].next;
@ -64,7 +61,6 @@ public class CursorLinkedList<T> {
* index of the [cursorSpace] array * index of the [cursorSpace] array
*/ */
public int indexOf(T element) { public int indexOf(T element) {
Objects.requireNonNull(element); Objects.requireNonNull(element);
Node<T> iterator = cursorSpace[head]; Node<T> iterator = cursorSpace[head];
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
@ -84,13 +80,10 @@ public class CursorLinkedList<T> {
* @return * @return
*/ */
public T get(int position) { public T get(int position) {
if (position >= 0 && position < count) { if (position >= 0 && position < count) {
int start = head; int start = head;
int counter = 0; int counter = 0;
while (start != -1) { while (start != -1) {
T element = cursorSpace[start].element; T element = cursorSpace[start].element;
if (counter == position) { if (counter == position) {
return element; return element;
@ -105,16 +98,13 @@ public class CursorLinkedList<T> {
} }
public void removeByIndex(int index) { public void removeByIndex(int index) {
if (index >= 0 && index < count) { if (index >= 0 && index < count) {
T element = get(index); T element = get(index);
remove(element); remove(element);
} }
} }
public void remove(T element) { public void remove(T element) {
Objects.requireNonNull(element); Objects.requireNonNull(element);
// case element is in the head // case element is in the head
@ -124,15 +114,14 @@ public class CursorLinkedList<T> {
free(head); free(head);
head = temp_next; head = temp_next;
} else { // otherwise cases } else { // otherwise cases
int prev_index = head; int prev_index = head;
int current_index = cursorSpace[prev_index].next; int current_index = cursorSpace[prev_index].next;
while (current_index != -1) { while (current_index != -1) {
T current_element = cursorSpace[current_index].element; T current_element = cursorSpace[current_index].element;
if (current_element.equals(element)) { if (current_element.equals(element)) {
cursorSpace[prev_index].next = cursorSpace[current_index].next; cursorSpace[prev_index].next =
cursorSpace[current_index].next;
free(current_index); free(current_index);
break; break;
} }
@ -146,7 +135,6 @@ public class CursorLinkedList<T> {
} }
private void free(int index) { private void free(int index) {
Node os_node = cursorSpace[os]; Node os_node = cursorSpace[os];
int os_next = os_node.next; int os_next = os_node.next;
cursorSpace[os].next = index; cursorSpace[os].next = index;
@ -155,7 +143,6 @@ public class CursorLinkedList<T> {
} }
public void append(T element) { public void append(T element) {
Objects.requireNonNull(element); Objects.requireNonNull(element);
int availableIndex = alloc(); int availableIndex = alloc();
cursorSpace[availableIndex].element = element; cursorSpace[availableIndex].element = element;
@ -179,7 +166,6 @@ public class CursorLinkedList<T> {
* @return the index of the next available node * @return the index of the next available node
*/ */
private int alloc() { private int alloc() {
// 1- get the index at which the os is pointing // 1- get the index at which the os is pointing
int availableNodeIndex = cursorSpace[os].next; int availableNodeIndex = cursorSpace[os].next;

View File

@ -53,7 +53,7 @@ public class DoublyLinkedList {
throw new NullPointerException(); throw new NullPointerException();
} }
for (int i : array) { for (int i : array) {
linkOperations.insertTail(i,this); linkOperations.insertTail(i, this);
} }
size = array.length; size = array.length;
} }
@ -136,13 +136,13 @@ class Link {
public static void main(String args[]) { public static void main(String args[]) {
DoublyLinkedList myList = new DoublyLinkedList(); DoublyLinkedList myList = new DoublyLinkedList();
LinkOperations linkOperations = new LinkOperations(); LinkOperations linkOperations = new LinkOperations();
linkOperations.insertHead(13,myList); linkOperations.insertHead(13, myList);
linkOperations.insertHead(7,myList); linkOperations.insertHead(7, myList);
linkOperations.insertHead(10,myList); linkOperations.insertHead(10, myList);
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) --> myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
myList.displayBackwards(); myList.displayBackwards();
linkOperations.insertTail(11,myList); linkOperations.insertTail(11, myList);
myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) --> myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) -->
myList.displayBackwards(); myList.displayBackwards();
@ -154,11 +154,11 @@ class Link {
myList.display(); // <-- 10(head) <--> 13(tail) --> myList.display(); // <-- 10(head) <--> 13(tail) -->
myList.displayBackwards(); myList.displayBackwards();
linkOperations.insertOrdered(23,myList); linkOperations.insertOrdered(23, myList);
linkOperations.insertOrdered(67,myList); linkOperations.insertOrdered(67, myList);
linkOperations.insertOrdered(3,myList); linkOperations.insertOrdered(3, myList);
myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) --> myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
linkOperations.insertElementByIndex(5, 1,myList); linkOperations.insertElementByIndex(5, 1, myList);
myList.display(); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) --> myList.display(); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
myList.displayBackwards(); myList.displayBackwards();
linkOperations.reverse(); // <-- 67(head) <--> 23 <--> 13 <--> 10 <--> 5 <--> 3(tail) --> linkOperations.reverse(); // <-- 67(head) <--> 23 <--> 13 <--> 10 <--> 5 <--> 3(tail) -->
@ -167,7 +167,7 @@ class Link {
linkOperations.clearList(); linkOperations.clearList();
myList.display(); myList.display();
myList.displayBackwards(); myList.displayBackwards();
linkOperations.insertHead(20,myList); linkOperations.insertHead(20, myList);
myList.display(); myList.display();
myList.displayBackwards(); myList.displayBackwards();
} }
@ -176,7 +176,8 @@ class Link {
/* /*
* This class implements the operations of the Link nodes. * This class implements the operations of the Link nodes.
*/ */
class LinkOperations{ class LinkOperations {
/** /**
* Head refers to the front of the list * Head refers to the front of the list
*/ */
@ -196,10 +197,9 @@ class LinkOperations{
* *
* @param x Element to be inserted * @param x Element to be inserted
*/ */
public void insertHead(int x,DoublyLinkedList doublyLinkedList) { public void insertHead(int x, DoublyLinkedList doublyLinkedList) {
Link newLink = new Link(x); // Create a new link with a value attached to it Link newLink = new Link(x); // Create a new link with a value attached to it
if (doublyLinkedList.isEmpty()) // Set the first element added to be the tail if (doublyLinkedList.isEmpty()) { // Set the first element added to be the tail
{
tail = newLink; tail = newLink;
} else { } else {
head.previous = newLink; // newLink <-- currenthead(head) head.previous = newLink; // newLink <-- currenthead(head)
@ -214,7 +214,7 @@ class LinkOperations{
* *
* @param x Element to be inserted * @param x Element to be inserted
*/ */
public void insertTail(int x,DoublyLinkedList doublyLinkedList) { public void insertTail(int x, DoublyLinkedList doublyLinkedList) {
Link newLink = new Link(x); Link newLink = new Link(x);
newLink.next = null; // currentTail(tail) newlink --> newLink.next = null; // currentTail(tail) newlink -->
if (doublyLinkedList.isEmpty()) { // Check if there are no elements in list then it adds first element if (doublyLinkedList.isEmpty()) { // Check if there are no elements in list then it adds first element
@ -234,15 +234,21 @@ class LinkOperations{
* @param x Element to be inserted * @param x Element to be inserted
* @param index Index(from start) at which the element x to be inserted * @param index Index(from start) at which the element x to be inserted
*/ */
public void insertElementByIndex(int x, int index,DoublyLinkedList doublyLinkedList) { public void insertElementByIndex(
int x,
int index,
DoublyLinkedList doublyLinkedList
) {
if (index > size) { if (index > size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); throw new IndexOutOfBoundsException(
"Index: " + index + ", Size: " + size
);
} }
if (index == 0) { if (index == 0) {
insertHead(x,doublyLinkedList); insertHead(x, doublyLinkedList);
} else { } else {
if (index == size) { if (index == size) {
insertTail(x,doublyLinkedList); insertTail(x, doublyLinkedList);
} else { } else {
Link newLink = new Link(x); Link newLink = new Link(x);
Link previousLink = head; // Link previousLink = head; //
@ -271,8 +277,7 @@ class LinkOperations{
if (head == null) { if (head == null) {
tail = null; tail = null;
} else { } else {
head.previous head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
= null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
} }
--size; --size;
return temp; return temp;
@ -309,7 +314,9 @@ class LinkOperations{
if (current != tail) { if (current != tail) {
current = current.next; current = current.next;
} else { // If we reach the tail and the element is still not found } else { // If we reach the tail and the element is still not found
throw new RuntimeException("The element to be deleted does not exist!"); throw new RuntimeException(
"The element to be deleted does not exist!"
);
} }
} }
@ -329,18 +336,17 @@ class LinkOperations{
* *
* @param x Element to be added * @param x Element to be added
*/ */
public void insertOrdered(int x,DoublyLinkedList doublyLinkedList) { public void insertOrdered(int x, DoublyLinkedList doublyLinkedList) {
Link newLink = new Link(x); Link newLink = new Link(x);
Link current = head; Link current = head;
while (current != null && x > current.value) // Find the position to insert while (current != null && x > current.value) { // Find the position to insert
{
current = current.next; current = current.next;
} }
if (current == head) { if (current == head) {
insertHead(x,doublyLinkedList); insertHead(x, doublyLinkedList);
} else if (current == null) { } else if (current == null) {
insertTail(x,doublyLinkedList); insertTail(x, doublyLinkedList);
} else { // Before: 1 <--> 2(current) <--> 3 } else { // Before: 1 <--> 2(current) <--> 3
newLink.previous = current.previous; // 1 <-- newLink newLink.previous = current.previous; // 1 <-- newLink
current.previous.next = newLink; // 1 <--> newLink current.previous.next = newLink; // 1 <--> newLink
@ -372,8 +378,7 @@ class LinkOperations{
while (linkOne.next != null) { // list is present while (linkOne.next != null) { // list is present
Link linkTwo = linkOne.next; // second link for comparison Link linkTwo = linkOne.next; // second link for comparison
while (linkTwo.next != null) { while (linkTwo.next != null) {
if (linkOne.value == linkTwo.value) // if there are duplicates values then if (linkOne.value == linkTwo.value) { // if there are duplicates values then
{
delete(linkTwo.value); // delete the link delete(linkTwo.value); // delete the link
} }
linkTwo = linkTwo.next; // go to next link linkTwo = linkTwo.next; // go to next link
@ -416,5 +421,4 @@ class LinkOperations{
tail = null; tail = null;
size = 0; size = 0;
} }
} }

View File

@ -36,7 +36,11 @@ public class MergeSortedArrayList {
* @param listB the second list to merge * @param listB the second list to merge
* @param listC the result list after merging * @param listC the result list after merging
*/ */
public static void merge(List<Integer> listA, List<Integer> listB, List<Integer> listC) { public static void merge(
List<Integer> listA,
List<Integer> listB,
List<Integer> listC
) {
int pa = 0; int pa = 0;
/* the index of listA */ /* the index of listA */
int pb = 0; int pb = 0;

View File

@ -12,7 +12,9 @@ public class MergeSortedSinglyLinkedList extends SinglyLinkedList {
} }
assert listA.toString().equals("2->4->6->8->10"); assert listA.toString().equals("2->4->6->8->10");
assert listB.toString().equals("1->3->5->7->9"); assert listB.toString().equals("1->3->5->7->9");
assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10"); assert merge(listA, listB)
.toString()
.equals("1->2->3->4->5->6->7->8->9->10");
} }
/** /**
@ -22,7 +24,10 @@ public class MergeSortedSinglyLinkedList extends SinglyLinkedList {
* @param listB the second sored list * @param listB the second sored list
* @return merged sorted list * @return merged sorted list
*/ */
public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) { public static SinglyLinkedList merge(
SinglyLinkedList listA,
SinglyLinkedList listB
) {
Node headA = listA.getHead(); Node headA = listA.getHead();
Node headB = listB.getHead(); Node headB = listB.getHead();

View File

@ -18,7 +18,9 @@ public class Merge_K_SortedLinkedlist {
*/ */
Node mergeKList(Node[] a, int N) { Node mergeKList(Node[] a, int N) {
// Min Heap // Min Heap
PriorityQueue<Node> min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data)); PriorityQueue<Node> min = new PriorityQueue<>(
Comparator.comparingInt(x -> x.data)
);
// adding head of all linkedList in min heap // adding head of all linkedList in min heap
min.addAll(Arrays.asList(a).subList(0, N)); min.addAll(Arrays.asList(a).subList(0, N));
@ -30,7 +32,6 @@ public class Merge_K_SortedLinkedlist {
// merging LinkedList // merging LinkedList
while (!min.isEmpty()) { while (!min.isEmpty()) {
Node temp = min.poll(); Node temp = min.poll();
curr.next = temp; curr.next = temp;
curr = temp; curr = temp;

View File

@ -22,7 +22,6 @@
* Step 7 : STOP * Step 7 : STOP
*/ */
package com.thealgorithms.datastructures.lists; package com.thealgorithms.datastructures.lists;
import java.util.ArrayList; import java.util.ArrayList;
@ -30,11 +29,13 @@ import java.util.List;
import java.util.Random; import java.util.Random;
public class RandomNode { public class RandomNode {
private List<Integer> list; private List<Integer> list;
private int size; private int size;
private static Random rand = new Random(); private static Random rand = new Random();
static class ListNode { static class ListNode {
int val; int val;
ListNode next; ListNode next;
@ -74,8 +75,6 @@ public class RandomNode {
System.out.println("Random Node : " + randomNum); System.out.println("Random Node : " + randomNum);
} }
} }
/** /**
* OUTPUT : * OUTPUT :
* First output : * First output :
@ -87,7 +86,6 @@ public class RandomNode {
* Time Complexity : O(n) * Time Complexity : O(n)
* Auxiliary Space Complexity : O(1) * Auxiliary Space Complexity : O(1)
*/ */
/** Time Complexity : O(n) /** Time Complexity : O(n)
* Auxiliary Space Complexity : O(1) * Auxiliary Space Complexity : O(1)
*/ */

View File

@ -23,7 +23,10 @@ public class SearchSinglyLinkedListRecursion extends SinglyLinkedList {
* {@code false}. * {@code false}.
*/ */
private boolean searchRecursion(Node node, int key) { private boolean searchRecursion(Node node, int key) {
return node != null && (node.value == key || searchRecursion(node.next, key)); return (
node != null &&
(node.value == key || searchRecursion(node.next, key))
);
} }
@Override @Override

View File

@ -5,7 +5,7 @@ import java.util.StringJoiner;
/** /**
* https://en.wikipedia.org/wiki/Linked_list * https://en.wikipedia.org/wiki/Linked_list
*/ */
public class SinglyLinkedList extends Node{ public class SinglyLinkedList extends Node {
/** /**
* Head refer to the front of the list * Head refer to the front of the list
@ -56,42 +56,40 @@ public class SinglyLinkedList extends Node{
/** /**
* Swaps nodes of two given values a and b. * Swaps nodes of two given values a and b.
* *
*/ */
public void swapNodes(int valueFirst, int valueSecond) { public void swapNodes(int valueFirst, int valueSecond) {
if(valueFirst == valueSecond){ if (valueFirst == valueSecond) {
return; return;
} }
Node previousA = null ,currentA = head; Node previousA = null, currentA = head;
while(currentA != null && currentA.value != valueFirst){ while (currentA != null && currentA.value != valueFirst) {
previousA = currentA; previousA = currentA;
currentA = currentA.next; currentA = currentA.next;
} }
Node previousB = null ,currentB = head; Node previousB = null, currentB = head;
while(currentB != null && currentB.value != valueSecond){ while (currentB != null && currentB.value != valueSecond) {
previousB = currentB; previousB = currentB;
currentB = currentB.next; currentB = currentB.next;
} }
/** If either of 'a' or 'b' is not present, then return */ /** If either of 'a' or 'b' is not present, then return */
if(currentA == null || currentB == null){ if (currentA == null || currentB == null) {
return; return;
} }
// If 'a' is not head node of list // If 'a' is not head node of list
if(previousA != null){ if (previousA != null) {
previousA.next = currentB; previousA.next = currentB;
} } else {
else{
// make 'b' as the new head // make 'b' as the new head
head = currentB; head = currentB;
} }
// If 'b' is not head node of list // If 'b' is not head node of list
if(previousB != null){ if (previousB != null) {
previousB.next = currentA; previousB.next = currentA;
} } else {
else{
// Make 'a' as new head // Make 'a' as new head
head = currentA; head = currentA;
} }
@ -108,7 +106,7 @@ public class SinglyLinkedList extends Node{
*/ */
Node reverseList(Node node) { Node reverseList(Node node) {
Node prevNode = head; Node prevNode = head;
while(prevNode.next!=node){ while (prevNode.next != node) {
prevNode = prevNode.next; prevNode = prevNode.next;
} }
Node prev = null, curr = node, next; Node prev = null, curr = node, next;
@ -216,7 +214,6 @@ public class SinglyLinkedList extends Node{
} }
public void deleteDuplicates() { public void deleteDuplicates() {
Node pred = head; Node pred = head;
// predecessor = the node // predecessor = the node
// having sublist of its duplicates // having sublist of its duplicates
@ -226,13 +223,14 @@ public class SinglyLinkedList extends Node{
// skip all duplicates // skip all duplicates
if (newHead.next != null && newHead.value == newHead.next.value) { if (newHead.next != null && newHead.value == newHead.next.value) {
// move till the end of duplicates sublist // move till the end of duplicates sublist
while (newHead.next != null && newHead.value == newHead.next.value) { while (
newHead.next != null && newHead.value == newHead.next.value
) {
newHead = newHead.next; newHead = newHead.next;
} }
// skip all duplicates // skip all duplicates
pred.next = newHead.next; pred.next = newHead.next;
newHead = null; newHead = null;
// otherwise, move predecessor // otherwise, move predecessor
} }
// move forward // move forward
@ -301,7 +299,6 @@ public class SinglyLinkedList extends Node{
newNode.next = cur.next; newNode.next = cur.next;
cur.next = newNode; cur.next = newNode;
size++; size++;
} }
/** /**
@ -375,6 +372,7 @@ public class SinglyLinkedList extends Node{
throw new IndexOutOfBoundsException(position + ""); throw new IndexOutOfBoundsException(position + "");
} }
} }
/** /**
* Driver Code * Driver Code
*/ */
@ -393,10 +391,15 @@ public class SinglyLinkedList extends Node{
assert list.toString().equals("10->7->5->3->1"); assert list.toString().equals("10->7->5->3->1");
System.out.println(list.toString()); System.out.println(list.toString());
/* Test search function */ /* Test search function */
assert list.search(10) && list.search(5) && list.search(1) && !list.search(100); assert list.search(10) &&
list.search(5) &&
list.search(1) &&
!list.search(100);
/* Test get function */ /* Test get function */
assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1; assert list.getNth(0) == 10 &&
list.getNth(2) == 5 &&
list.getNth(4) == 1;
/* Test delete function */ /* Test delete function */
list.deleteHead(); list.deleteHead();
@ -419,13 +422,14 @@ public class SinglyLinkedList extends Node{
} }
SinglyLinkedList instance = new SinglyLinkedList(); SinglyLinkedList instance = new SinglyLinkedList();
Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4))))); Node head = new Node(
0,
new Node(2, new Node(3, new Node(3, new Node(4))))
);
instance.setHead(head); instance.setHead(head);
instance.deleteDuplicates(); instance.deleteDuplicates();
instance.print(); instance.print();
} }
} }
/** /**
@ -444,8 +448,7 @@ class Node {
*/ */
Node next; Node next;
Node() { Node() {}
}
/** /**
* Constructor * Constructor
@ -466,5 +469,4 @@ class Node {
this.value = value; this.value = value;
this.next = next; this.next = next;
} }
} }

View File

@ -189,23 +189,25 @@ public class SkipList<E extends Comparable<E>> {
} }
Collections.reverse(layers); Collections.reverse(layers);
String result = layers.stream() String result = layers
.map(layer -> { .stream()
StringBuilder acc = new StringBuilder(); .map(layer -> {
for (boolean b : layer) { StringBuilder acc = new StringBuilder();
if (b) { for (boolean b : layer) {
acc.append("[ ]"); if (b) {
} else { acc.append("[ ]");
acc.append("---"); } else {
} acc.append("---");
acc.append(" ");
} }
return acc.toString(); acc.append(" ");
}) }
.collect(Collectors.joining("\n")); return acc.toString();
String positions = IntStream.range(0, sizeWithHeader - 1) })
.mapToObj(i -> String.format("%3d", i)) .collect(Collectors.joining("\n"));
.collect(Collectors.joining(" ")); String positions = IntStream
.range(0, sizeWithHeader - 1)
.mapToObj(i -> String.format("%3d", i))
.collect(Collectors.joining(" "));
return result + String.format("%n H %s%n", positions); return result + String.format("%n H %s%n", positions);
} }
@ -296,14 +298,18 @@ public class SkipList<E extends Comparable<E>> {
public BernoulliHeightStrategy(double probability) { public BernoulliHeightStrategy(double probability) {
if (probability <= 0 || probability >= 1) { if (probability <= 0 || probability >= 1) {
throw new IllegalArgumentException("Probability should be from 0 to 1. But was: " + probability); throw new IllegalArgumentException(
"Probability should be from 0 to 1. But was: " + probability
);
} }
this.probability = probability; this.probability = probability;
} }
@Override @Override
public int height(int expectedSize) { public int height(int expectedSize) {
long height = Math.round(Math.log10(expectedSize) / Math.log10(1 / probability)); long height = Math.round(
Math.log10(expectedSize) / Math.log10(1 / probability)
);
if (height > Integer.MAX_VALUE) { if (height > Integer.MAX_VALUE) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }

View File

@ -69,7 +69,6 @@ public class CircularQueue {
} }
return res; return res;
} }
} }
public int peek() { public int peek() {
@ -86,7 +85,6 @@ public class CircularQueue {
System.out.println("The Queue is deleted!"); System.out.println("The Queue is deleted!");
} }
public static void main(String[] args) { public static void main(String[] args) {
CircularQueue cq = new CircularQueue(5); CircularQueue cq = new CircularQueue(5);
System.out.println(cq.isEmpty()); System.out.println(cq.isEmpty());
@ -110,6 +108,5 @@ public class CircularQueue {
System.out.println(cq.peek()); System.out.println(cq.peek());
System.out.println(cq.peek()); System.out.println(cq.peek());
cq.deleteQueue(); cq.deleteQueue();
} }
} }

View File

@ -121,8 +121,7 @@ public class PriorityQueues {
// [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top // [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top
for (int i = 3; i >= 0; i--) { for (int i = 3; i >= 0; i--) {
System.out.print( System.out.print(myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2]
myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2]
} }
// As you can see, a Priority Queue can be used as a sorting algotithm // As you can see, a Priority Queue can be used as a sorting algotithm
} }

View File

@ -28,13 +28,16 @@ class BalancedBrackets {
*/ */
public static boolean isPaired(char leftBracket, char rightBracket) { public static boolean isPaired(char leftBracket, char rightBracket) {
char[][] pairedBrackets = { char[][] pairedBrackets = {
{'(', ')'}, { '(', ')' },
{'[', ']'}, { '[', ']' },
{'{', '}'}, { '{', '}' },
{'<', '>'} { '<', '>' },
}; };
for (char[] pairedBracket : pairedBrackets) { for (char[] pairedBracket : pairedBrackets) {
if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) { if (
pairedBracket[0] == leftBracket &&
pairedBracket[1] == rightBracket
) {
return true; return true;
} }
} }
@ -63,7 +66,10 @@ class BalancedBrackets {
case ')': case ')':
case ']': case ']':
case '}': case '}':
if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) { if (
bracketsStack.isEmpty() ||
!isPaired(bracketsStack.pop(), bracket)
) {
return false; return false;
} }
break; break;

View File

@ -8,6 +8,7 @@ package com.thealgorithms.datastructures.stacks;
import java.util.*; import java.util.*;
public class CalculateMaxOfMin { public class CalculateMaxOfMin {
public static int calculateMaxOfMin(int[] a) { public static int calculateMaxOfMin(int[] a) {
int n = a.length; int n = a.length;
int[] ans = new int[n]; int[] ans = new int[n];

View File

@ -24,10 +24,30 @@ public class DecimalToAnyUsingStack {
private static String convert(int number, int radix) { private static String convert(int number, int radix) {
if (radix < 2 || radix > 16) { if (radix < 2 || radix > 16) {
throw new ArithmeticException( throw new ArithmeticException(
String.format("Invalid input -> number:%d,radius:%d", number, radix)); String.format(
"Invalid input -> number:%d,radius:%d",
number,
radix
)
);
} }
char[] tables = { char[] tables = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'A',
'B',
'C',
'D',
'E',
'F',
}; };
Stack<Character> bits = new Stack<>(); Stack<Character> bits = new Stack<>();
do { do {

View File

@ -25,7 +25,6 @@ public class DuplicateBrackets {
} }
st.pop(); st.pop();
} }
} else { } else {
st.push(ch); st.push(ch);
} }
@ -40,5 +39,4 @@ public class DuplicateBrackets {
System.out.println(check(str)); System.out.println(check(str));
sc.close(); sc.close();
} }
} }

View File

@ -10,7 +10,8 @@ public class InfixToPostfix {
assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6")); assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6"));
} }
public static String infix2PostFix(String infixExpression) throws Exception { public static String infix2PostFix(String infixExpression)
throws Exception {
if (!BalancedBrackets.isBalanced(infixExpression)) { if (!BalancedBrackets.isBalanced(infixExpression)) {
throw new Exception("invalid expression"); throw new Exception("invalid expression");
} }
@ -27,7 +28,10 @@ public class InfixToPostfix {
} }
stack.pop(); stack.pop();
} else { } else {
while (!stack.isEmpty() && precedence(element) <= precedence(stack.peek())) { while (
!stack.isEmpty() &&
precedence(element) <= precedence(stack.peek())
) {
output.append(stack.pop()); output.append(stack.pop());
} }
stack.push(element); stack.push(element);

View File

@ -8,26 +8,29 @@ import java.util.Stack;
*/ */
public class LargestRectangle { public class LargestRectangle {
public static String largestRectanglehistogram(int[] heights) {
int n = heights.length, maxArea = 0; public static String largestRectanglehistogram(int[] heights) {
Stack<int[]> st = new Stack<>(); int n = heights.length, maxArea = 0;
for(int i=0;i<n;i++) { Stack<int[]> st = new Stack<>();
int start = i; for (int i = 0; i < n; i++) {
while(!st.isEmpty() && st.peek()[1] > heights[i]) { int start = i;
int[] tmp = st.pop(); while (!st.isEmpty() && st.peek()[1] > heights[i]) {
maxArea = Math.max(maxArea, tmp[1]*(i - tmp[0])); int[] tmp = st.pop();
start = tmp[0]; maxArea = Math.max(maxArea, tmp[1] * (i - tmp[0]));
} start = tmp[0];
st.push(new int[]{start, heights[i]}); }
} st.push(new int[] { start, heights[i] });
while(!st.isEmpty()) { }
int[] tmp = st.pop(); while (!st.isEmpty()) {
maxArea = Math.max(maxArea, tmp[1]*(n-tmp[0])); int[] tmp = st.pop();
} maxArea = Math.max(maxArea, tmp[1] * (n - tmp[0]));
return Integer.toString(maxArea); }
} return Integer.toString(maxArea);
public static void main(String[] args) { }
assert largestRectanglehistogram(new int[]{2, 1, 5, 6, 2, 3}).equals("10");
assert largestRectanglehistogram(new int[]{2, 4}).equals("4"); public static void main(String[] args) {
assert largestRectanglehistogram(new int[] { 2, 1, 5, 6, 2, 3 })
.equals("10");
assert largestRectanglehistogram(new int[] { 2, 4 }).equals("4");
} }
} }

View File

@ -97,10 +97,9 @@ public class MaximumMinimumWindow {
} }
public static void main(String args[]) { public static void main(String args[]) {
int[] arr = new int[]{10, 20, 30, 50, 10, 70, 30}; int[] arr = new int[] { 10, 20, 30, 50, 10, 70, 30 };
int[] target = new int[]{70, 30, 20, 10, 10, 10, 10}; int[] target = new int[] { 70, 30, 20, 10, 10, 10, 10 };
int[] res = calculateMaxOfMin(arr, arr.length); int[] res = calculateMaxOfMin(arr, arr.length);
assert Arrays.equals(target, res); assert Arrays.equals(target, res);
} }
} }

View File

@ -1,6 +1,8 @@
package com.thealgorithms.datastructures.stacks; package com.thealgorithms.datastructures.stacks;
import java.util.Arrays; import java.util.Arrays;
import java.util.Stack; import java.util.Stack;
/* /*
Given an array "input" you need to print the first grater element for each element. Given an array "input" you need to print the first grater element for each element.
For a given element x of an array, the Next Grater element of that element is the For a given element x of an array, the Next Grater element of that element is the
@ -38,11 +40,9 @@ import java.util.Stack;
3. If elements are left in stack after completing while loop then their Next Grater element is -1. 3. If elements are left in stack after completing while loop then their Next Grater element is -1.
*/ */
public class NextGraterElement { public class NextGraterElement {
public static int[] findNextGreaterElements(int[] array) { public static int[] findNextGreaterElements(int[] array) {
if (array == null) { if (array == null) {
return array; return array;
} }
@ -60,8 +60,7 @@ public class NextGraterElement {
return result; return result;
} }
public static void main(String[] args) public static void main(String[] args) {
{
int[] input = { 2, 7, 3, 5, 4, 6, 8 }; int[] input = { 2, 7, 3, 5, 4, 6, 8 };
int[] result = findNextGreaterElements(input); int[] result = findNextGreaterElements(input);
System.out.println(Arrays.toString(result)); System.out.println(Arrays.toString(result));

View File

@ -1,8 +1,8 @@
package com.thealgorithms.datastructures.stacks; package com.thealgorithms.datastructures.stacks;
import java.util.Arrays; import java.util.Arrays;
import java.util.Stack; import java.util.Stack;
/* /*
Given an array "input" you need to print the first smaller element for each element to the left side of an array. Given an array "input" you need to print the first smaller element for each element to the left side of an array.
For a given element x of an array, the Next Smaller element of that element is the For a given element x of an array, the Next Smaller element of that element is the
@ -38,8 +38,8 @@ import java.util.Stack;
*/ */
public class NextSmallerElement { public class NextSmallerElement {
public static int[] findNextSmallerElements(int[] array)
{ public static int[] findNextSmallerElements(int[] array) {
// base case // base case
if (array == null) { if (array == null) {
return array; return array;
@ -60,8 +60,7 @@ public class NextSmallerElement {
return result; return result;
} }
public static void main(String[] args) public static void main(String[] args) {
{
int[] input = { 2, 7, 3, 5, 4, 6, 8 }; int[] input = { 2, 7, 3, 5, 4, 6, 8 };
int[] result = findNextSmallerElements(input); int[] result = findNextSmallerElements(input);
System.out.println(Arrays.toString(result)); System.out.println(Arrays.toString(result));

View File

@ -50,8 +50,7 @@ public class NodeStack<Item> {
/** /**
* Constructors for the NodeStack. * Constructors for the NodeStack.
*/ */
public NodeStack() { public NodeStack() {}
}
private NodeStack(Item item) { private NodeStack(Item item) {
this.data = item; this.data = item;
@ -63,7 +62,6 @@ public class NodeStack<Item> {
* @param item : value to be put on the stack. * @param item : value to be put on the stack.
*/ */
public void push(Item item) { public void push(Item item) {
NodeStack<Item> newNs = new NodeStack<Item>(item); NodeStack<Item> newNs = new NodeStack<Item>(item);
if (this.isEmpty()) { if (this.isEmpty()) {
@ -85,7 +83,6 @@ public class NodeStack<Item> {
* @return item : value that is returned. * @return item : value that is returned.
*/ */
public Item pop() { public Item pop() {
Item item = (Item) NodeStack.head.getData(); Item item = (Item) NodeStack.head.getData();
NodeStack.head.setHead(NodeStack.head.getPrevious()); NodeStack.head.setHead(NodeStack.head.getPrevious());

View File

@ -18,11 +18,8 @@ import java.util.Stack;
public class PostfixToInfix { public class PostfixToInfix {
public static boolean isOperator(char token) {
public static boolean isOperator(char token) switch (token) {
{
switch(token)
{
case '+': case '+':
case '-': case '-':
case '/': case '/':
@ -34,43 +31,31 @@ public class PostfixToInfix {
return false; return false;
} }
public static boolean isValidPostfixExpression(String postfix) {
public static boolean isValidPostfixExpression(String postfix)
{
/* Postfix expression length should NOT be less than 3 */ /* Postfix expression length should NOT be less than 3 */
if(postfix.length() < 3) return false; if (postfix.length() < 3) return false;
/* First two characters should NOT be operators */ /* First two characters should NOT be operators */
if(isOperator(postfix.charAt(0))) return false; if (isOperator(postfix.charAt(0))) return false;
if(isOperator(postfix.charAt(1))) return false; if (isOperator(postfix.charAt(1))) return false;
int operandCount = 0; int operandCount = 0;
int operatorCount = 0; int operatorCount = 0;
/* Traverse the postfix string to check if --> Number of operands = Number of operators + 1 */ /* Traverse the postfix string to check if --> Number of operands = Number of operators + 1 */
for(int i = 0; i < postfix.length(); i++) for (int i = 0; i < postfix.length(); i++) {
{
char token = postfix.charAt(i); char token = postfix.charAt(i);
if(isOperator(token)) if (isOperator(token)) {
{
operatorCount++; operatorCount++;
if(operatorCount >= operandCount) return false; if (operatorCount >= operandCount) return false;
} } else {
if (operatorCount == 0) {
else
{
if(operatorCount == 0)
{
operandCount++; operandCount++;
continue; continue;
} }
if(operandCount != operatorCount + 1) return false; if (operandCount != operatorCount + 1) return false;
/* Operand count is set to 2 because:- /* Operand count is set to 2 because:-
* *
@ -81,7 +66,6 @@ public class PostfixToInfix {
*/ */
operandCount = 2; operandCount = 2;
/* Reset operator count */ /* Reset operator count */
operatorCount = 0; operatorCount = 0;
} }
@ -90,17 +74,13 @@ public class PostfixToInfix {
return (operandCount == operatorCount + 1); return (operandCount == operatorCount + 1);
} }
public static String getPostfixToInfix(String postfix) {
public static String getPostfixToInfix(String postfix)
{
String infix = ""; String infix = "";
if(postfix.isEmpty()) return infix; if (postfix.isEmpty()) return infix;
/* Validate Postfix expression before proceeding with the Infix conversion */ /* Validate Postfix expression before proceeding with the Infix conversion */
if(!isValidPostfixExpression(postfix)) if (!isValidPostfixExpression(postfix)) {
{
throw new IllegalArgumentException("Invalid Postfix Expression"); throw new IllegalArgumentException("Invalid Postfix Expression");
} }
@ -110,13 +90,10 @@ public class PostfixToInfix {
String operandA, operandB; String operandA, operandB;
char operator; char operator;
for (int index = 0; index < postfix.length(); index++) {
for(int index = 0; index < postfix.length(); index++)
{
char token = postfix.charAt(index); char token = postfix.charAt(index);
if(!isOperator(token)) if (!isOperator(token)) {
{
stack.push(Character.toString(token)); stack.push(Character.toString(token));
continue; continue;
} }
@ -141,13 +118,12 @@ public class PostfixToInfix {
return infix; return infix;
} }
public static void main(String args[]) {
public static void main(String args[])
{
assert getPostfixToInfix("ABC+/").equals("(A/(B+C))"); assert getPostfixToInfix("ABC+/").equals("(A/(B+C))");
assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))"); assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))");
assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)"); assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)");
assert getPostfixToInfix("ABCDE^*/-").equals("(A-(B/(C*(D^E))))"); assert getPostfixToInfix("ABCDE^*/-").equals("(A-(B/(C*(D^E))))");
assert getPostfixToInfix("AB+CD^/E*FGH+-^").equals("((((A+B)/(C^D))*E)^(F-(G+H)))"); assert getPostfixToInfix("AB+CD^/E*FGH+-^")
.equals("((((A+B)/(C^D))*E)^(F-(G+H)))");
} }
} }

View File

@ -11,9 +11,10 @@ import java.util.Stack;
public class ReverseStack { public class ReverseStack {
public static void main(String args[]) { public static void main(String args[]) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements you wish to insert in the stack"); System.out.println(
"Enter the number of elements you wish to insert in the stack"
);
int n = sc.nextInt(); int n = sc.nextInt();
int i; int i;
Stack<Integer> stack = new Stack<Integer>(); Stack<Integer> stack = new Stack<Integer>();
@ -28,7 +29,6 @@ public class ReverseStack {
System.out.print(stack.peek() + ","); System.out.print(stack.peek() + ",");
stack.pop(); stack.pop();
} }
} }
private static void reverseStack(Stack<Integer> stack) { private static void reverseStack(Stack<Integer> stack) {
@ -46,11 +46,9 @@ public class ReverseStack {
//Insert the topmost element to the bottom of the stack //Insert the topmost element to the bottom of the stack
insertAtBottom(stack, element); insertAtBottom(stack, element);
} }
private static void insertAtBottom(Stack<Integer> stack, int element) { private static void insertAtBottom(Stack<Integer> stack, int element) {
if (stack.isEmpty()) { if (stack.isEmpty()) {
//When stack is empty, insert the element so it will be present at the bottom of the stack //When stack is empty, insert the element so it will be present at the bottom of the stack
stack.push(element); stack.push(element);
@ -66,5 +64,4 @@ public class ReverseStack {
stack.push(ele); stack.push(ele);
} }
} }

View File

@ -9,7 +9,6 @@ import java.util.NoSuchElementException;
class StackOfLinkedList { class StackOfLinkedList {
public static void main(String[] args) { public static void main(String[] args) {
LinkedListStack stack = new LinkedListStack(); LinkedListStack stack = new LinkedListStack();
stack.push(1); stack.push(1);
stack.push(2); stack.push(2);
@ -24,7 +23,9 @@ class StackOfLinkedList {
assert stack.pop() == 5; assert stack.pop() == 5;
assert stack.pop() == 4; assert stack.pop() == 4;
System.out.println("Top element of stack currently is: " + stack.peek()); System.out.println(
"Top element of stack currently is: " + stack.peek()
);
} }
} }
@ -119,7 +120,9 @@ class LinkedListStack {
builder.append(cur.data).append("->"); builder.append(cur.data).append("->");
cur = cur.next; cur = cur.next;
} }
return builder.replace(builder.length() - 2, builder.length(), "").toString(); return builder
.replace(builder.length() - 2, builder.length(), "")
.toString();
} }
/** /**

View File

@ -1,4 +1,3 @@
package com.thealgorithms.datastructures.trees; package com.thealgorithms.datastructures.trees;
/* /*
@ -27,111 +26,106 @@ AVLTree tree=new AVLTree();
*/ */
public class AVLSimple { public class AVLSimple {
private class Node{
int data;
int height;
Node left;
Node right;
Node(int data){
this.data=data;
this.height=1;
}
} private class Node {
private Node root;
public void insert(int data) {
this.root=insert(this.root,data);
}
private Node insert(Node node,int item) {
if(node==null) {
Node add=new Node(item);
return add;
}
if(node.data>item) {
node.left=insert(node.left,item);
}
if(node.data<item) {
node.right=insert(node.right,item);
}
node.height=Math.max(height(node.left),height(node.right))+1;
int bf=bf(node);
//LL case
if(bf>1&&item<node.left.data)
return rightRotate(node);
//RR case
if(bf<-1&&item>node.right.data)
return leftRotate(node);
//RL case
if(bf<-1&&item<node.right.data) {
node.right=rightRotate(node.right);
return leftRotate(node);
}
//LR case
if(bf>1&&item>node.left.data) {
node.left=leftRotate(node.left);
return rightRotate(node);
}
return node; int data;
} int height;
public void display() { Node left;
this.display(this.root); Node right;
System.out.println(this.root.height);
}
private void display (Node node) {
String str="";
if(node.left!=null)
str+=node.left.data+"=>";
else
str+="END=>";
str+=node.data+"";
if(node.right!=null)
str+="<="+node.right.data;
else
str+="<=END";
System.out.println(str);
if(node.left!=null)
display(node.left);
if(node.right!=null)
display(node.right);
}
private int height(Node node) {
if(node==null) {
return 0;
}
return node.height;
} Node(int data) {
private int bf(Node node) { this.data = data;
if(node==null) this.height = 1;
return 0; }
return height(node.left)-height(node.right); }
}
private Node rightRotate(Node c) { private Node root;
Node b=c.left;
Node T3=b.right;
b.right=c; public void insert(int data) {
c.left=T3; this.root = insert(this.root, data);
c.height=Math.max(height(c.left),height(c.right))+1; }
b.height=Math.max(height(b.left),height(b.right))+1;
return b;
} private Node insert(Node node, int item) {
private Node leftRotate(Node c) { if (node == null) {
Node b=c.right; Node add = new Node(item);
Node T3=b.left; return add;
}
if (node.data > item) {
node.left = insert(node.left, item);
}
if (node.data < item) {
node.right = insert(node.right, item);
}
node.height = Math.max(height(node.left), height(node.right)) + 1;
int bf = bf(node);
//LL case
if (bf > 1 && item < node.left.data) return rightRotate(node);
//RR case
if (bf < -1 && item > node.right.data) return leftRotate(node);
//RL case
if (bf < -1 && item < node.right.data) {
node.right = rightRotate(node.right);
return leftRotate(node);
}
//LR case
if (bf > 1 && item > node.left.data) {
node.left = leftRotate(node.left);
return rightRotate(node);
}
b.left=c; return node;
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;
} public void display() {
this.display(this.root);
System.out.println(this.root.height);
}
private void display(Node node) {
String str = "";
if (node.left != null) str += node.left.data + "=>"; else str +=
"END=>";
str += node.data + "";
if (node.right != null) str += "<=" + node.right.data; else str +=
"<=END";
System.out.println(str);
if (node.left != null) display(node.left);
if (node.right != null) display(node.right);
}
private int height(Node node) {
if (node == null) {
return 0;
}
return node.height;
}
private int bf(Node node) {
if (node == null) return 0;
return height(node.left) - height(node.right);
}
private Node rightRotate(Node c) {
Node b = c.left;
Node T3 = b.right;
b.right = c;
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;
}
private Node leftRotate(Node c) {
Node b = c.right;
Node T3 = b.left;
b.left = c;
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;
}
} }

Some files were not shown because too many files have changed in this diff Show More