Format code with prettier (#3375)
This commit is contained in:
parent
32b9b11ed5
commit
e96f567bfc
@ -22,7 +22,9 @@ public class IIRFilter {
|
||||
*/
|
||||
public IIRFilter(int order) throws IllegalArgumentException {
|
||||
if (order < 1) {
|
||||
throw new IllegalArgumentException("order must be greater than zero");
|
||||
throw new IllegalArgumentException(
|
||||
"order must be greater than zero"
|
||||
);
|
||||
}
|
||||
|
||||
this.order = order;
|
||||
@ -45,17 +47,24 @@ public class IIRFilter {
|
||||
* @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is
|
||||
* not of size {@code order}, or if {@code aCoeffs[0]} is 0.0
|
||||
*/
|
||||
public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException {
|
||||
public void setCoeffs(double[] aCoeffs, double[] bCoeffs)
|
||||
throws IllegalArgumentException {
|
||||
if (aCoeffs.length != order) {
|
||||
throw new IllegalArgumentException("aCoeffs must be of size " + order + ", got " + aCoeffs.length);
|
||||
throw new IllegalArgumentException(
|
||||
"aCoeffs must be of size " + order + ", got " + aCoeffs.length
|
||||
);
|
||||
}
|
||||
|
||||
if (aCoeffs[0] == 0.0) {
|
||||
throw new IllegalArgumentException("aCoeffs.get(0) must not be zero");
|
||||
throw new IllegalArgumentException(
|
||||
"aCoeffs.get(0) must not be zero"
|
||||
);
|
||||
}
|
||||
|
||||
if (bCoeffs.length != order) {
|
||||
throw new IllegalArgumentException("bCoeffs must be of size " + order + ", got " + bCoeffs.length);
|
||||
throw new IllegalArgumentException(
|
||||
"bCoeffs must be of size " + order + ", got " + bCoeffs.length
|
||||
);
|
||||
}
|
||||
|
||||
for (int i = 0; i <= order; i++) {
|
||||
@ -75,7 +84,8 @@ public class IIRFilter {
|
||||
|
||||
// Process
|
||||
for (int i = 1; i <= order; i++) {
|
||||
result += (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]);
|
||||
result +=
|
||||
(coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]);
|
||||
}
|
||||
result = (result + coeffsB[0] * sample) / coeffsA[0];
|
||||
|
||||
|
@ -7,7 +7,9 @@ import java.util.*;
|
||||
* @author Alan Piao (https://github.com/cpiao3)
|
||||
*/
|
||||
public class Combination {
|
||||
|
||||
private static int length;
|
||||
|
||||
/**
|
||||
* Find all combinations of given array using backtracking
|
||||
* @param arr the array.
|
||||
@ -26,6 +28,7 @@ public class Combination {
|
||||
backtracking(array, 0, new TreeSet<T>(), result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backtrack all possible combinations of a given array
|
||||
* @param arr the array.
|
||||
@ -34,7 +37,12 @@ public class Combination {
|
||||
* @param result the list contains all combination.
|
||||
* @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 (length - 1 == currSet.size()) {
|
||||
for (int i = index; i < arr.length; i++) {
|
||||
|
@ -13,13 +13,11 @@ public class FloodFill {
|
||||
* @param x The x 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) {
|
||||
|
||||
return image[x][y];
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static int getPixel(int[][] image, int x, int y) {
|
||||
return image[x][y];
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the color at the given co-odrinates of a 2D image
|
||||
*
|
||||
@ -27,13 +25,10 @@ public class FloodFill {
|
||||
* @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
|
||||
*/
|
||||
public static void putPixel(int[][] image, int x, int y, int newColor) {
|
||||
|
||||
image[x][y] = newColor;
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static void putPixel(int[][] image, int x, int y, int newColor) {
|
||||
image[x][y] = newColor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @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;
|
||||
if(y < 0 || y >= image[x].length) return;
|
||||
if(getPixel(image, x, y) != oldColor) return;
|
||||
putPixel(image, x, y, newColor);
|
||||
|
||||
putPixel(image, x, y, newColor);
|
||||
/* 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, y - 1, 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, 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);
|
||||
}
|
||||
}
|
||||
|
@ -25,10 +25,19 @@ import java.util.*;
|
||||
*/
|
||||
public class KnightsTour {
|
||||
|
||||
private final static 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 int[][] grid; // chess grid
|
||||
private static int total; // total squares in chess
|
||||
private static final int base = 12;
|
||||
private static final int[][] moves = {
|
||||
{ 1, -2 },
|
||||
{ 2, -1 },
|
||||
{ 2, 1 },
|
||||
{ 1, 2 },
|
||||
{ -1, 2 },
|
||||
{ -2, 1 },
|
||||
{ -2, -1 },
|
||||
{ -1, -2 },
|
||||
}; // 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) {
|
||||
grid = new int[base][base];
|
||||
@ -52,7 +61,6 @@ public class KnightsTour {
|
||||
} else {
|
||||
System.out.println("no result");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Return True when solvable
|
||||
@ -67,17 +75,23 @@ public class KnightsTour {
|
||||
return false;
|
||||
}
|
||||
|
||||
Collections.sort(neighbor, new Comparator<int[]>() {
|
||||
public int compare(int[] a, int[] b) {
|
||||
return a[2] - b[2];
|
||||
Collections.sort(
|
||||
neighbor,
|
||||
new Comparator<int[]>() {
|
||||
public int compare(int[] a, int[] b) {
|
||||
return a[2] - b[2];
|
||||
}
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
for (int[] nb : neighbor) {
|
||||
row = nb[0];
|
||||
column = nb[1];
|
||||
grid[row][column] = count;
|
||||
if (!orphanDetected(count, row, column) && solve(row, column, count + 1)) {
|
||||
if (
|
||||
!orphanDetected(count, row, column) &&
|
||||
solve(row, column, count + 1)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
grid[row][column] = 0;
|
||||
@ -95,7 +109,7 @@ public class KnightsTour {
|
||||
int y = m[1];
|
||||
if (grid[row + y][column + x] == 0) {
|
||||
int num = countNeighbors(row + y, column + x);
|
||||
neighbour.add(new int[]{row + y, column + x, num});
|
||||
neighbour.add(new int[] { row + y, column + x, num });
|
||||
}
|
||||
}
|
||||
return neighbour;
|
||||
|
@ -2,157 +2,154 @@ package com.thealgorithms.backtracking;
|
||||
|
||||
public class MazeRecursion {
|
||||
|
||||
public static void mazeRecursion() {
|
||||
// First create a 2 dimensions array to mimic a maze map
|
||||
int[][] map = new int[8][7];
|
||||
int[][] map2 = new int[8][7];
|
||||
public static void mazeRecursion() {
|
||||
// First create a 2 dimensions array to mimic a maze map
|
||||
int[][] map = new int[8][7];
|
||||
int[][] map2 = new int[8][7];
|
||||
|
||||
// We use 1 to indicate wall
|
||||
// Set the ceiling and floor to 1
|
||||
for (int i = 0; i < 7; i++) {
|
||||
map[0][i] = 1;
|
||||
map[7][i] = 1;
|
||||
}
|
||||
// We use 1 to indicate wall
|
||||
// Set the ceiling and floor to 1
|
||||
for (int i = 0; i < 7; i++) {
|
||||
map[0][i] = 1;
|
||||
map[7][i] = 1;
|
||||
}
|
||||
|
||||
// Then we set the left and right wall to 1
|
||||
for (int i = 0; i < 8; i++) {
|
||||
map[i][0] = 1;
|
||||
map[i][6] = 1;
|
||||
}
|
||||
// Then we set the left and right wall to 1
|
||||
for (int i = 0; i < 8; i++) {
|
||||
map[i][0] = 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
|
||||
map[3][1] = 1;
|
||||
map[3][2] = 1;
|
||||
// Here we set the obstacle
|
||||
map[3][1] = 1;
|
||||
map[3][2] = 1;
|
||||
|
||||
// Print the current map
|
||||
System.out.println("The condition of the map: ");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
for (int j = 0; j < 7; j++) {
|
||||
System.out.print(map[i][j] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
// Print the current map
|
||||
System.out.println("The condition of the map: ");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
for (int j = 0; j < 7; j++) {
|
||||
System.out.print(map[i][j] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
// clone another map for setWay2 method
|
||||
for (int i = 0; i < map.length; i++) {
|
||||
for (int j = 0; j < map[i].length; j++) {
|
||||
map2[i][j] = map[i][j];
|
||||
}
|
||||
}
|
||||
// clone another map for setWay2 method
|
||||
for (int i = 0; i < map.length; i++) {
|
||||
for (int j = 0; j < map[i].length; j++) {
|
||||
map2[i][j] = map[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
// By using recursive backtracking to let your ball(target) find its way in the
|
||||
// maze
|
||||
// The first parameter is the map
|
||||
// Second parameter is x coordinate of your target
|
||||
// Thrid parameter is the y coordinate of your target
|
||||
setWay(map, 1, 1);
|
||||
setWay2(map2, 1, 1);
|
||||
// By using recursive backtracking to let your ball(target) find its way in the
|
||||
// maze
|
||||
// The first parameter is the map
|
||||
// Second parameter is x coordinate of your target
|
||||
// Thrid parameter is the y coordinate of your target
|
||||
setWay(map, 1, 1);
|
||||
setWay2(map2, 1, 1);
|
||||
|
||||
// Print out the new map1, with the ball footprint
|
||||
System.out.println("After the ball goes through the map1,show the current map1 condition");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
for (int j = 0; j < 7; j++) {
|
||||
System.out.print(map[i][j] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
// Print out the new map1, with the ball footprint
|
||||
System.out.println(
|
||||
"After the ball goes through the map1,show the current map1 condition"
|
||||
);
|
||||
for (int i = 0; i < 8; i++) {
|
||||
for (int j = 0; j < 7; j++) {
|
||||
System.out.print(map[i][j] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
// Print out the new map2, with the ball footprint
|
||||
System.out.println("After the ball goes through the map2,show the current map2 condition");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
for (int j = 0; j < 7; j++) {
|
||||
System.out.print(map2[i][j] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
// Print out the new map2, with the ball footprint
|
||||
System.out.println(
|
||||
"After the ball goes through the map2,show the current map2 condition"
|
||||
);
|
||||
for (int i = 0; i < 8; i++) {
|
||||
for (int j = 0; j < 7; j++) {
|
||||
System.out.print(map2[i][j] + " ");
|
||||
}
|
||||
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 ball,return true,else 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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 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 ball,return true,else 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
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -47,7 +47,14 @@ public class NQueens {
|
||||
List<List<String>> arrangements = new ArrayList<List<String>>();
|
||||
getSolution(queens, arrangements, new int[queens], 0);
|
||||
if (arrangements.isEmpty()) {
|
||||
System.out.println("There is no way to place " + queens + " queens on board of size " + queens + "x" + queens);
|
||||
System.out.println(
|
||||
"There is no way to place " +
|
||||
queens +
|
||||
" queens on board of size " +
|
||||
queens +
|
||||
"x" +
|
||||
queens
|
||||
);
|
||||
} else {
|
||||
System.out.println("Arrangement for placing " + queens + " queens");
|
||||
}
|
||||
@ -65,7 +72,12 @@ public class NQueens {
|
||||
* @param columns: columns[i] = rowId where queen is placed in ith column.
|
||||
* @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) {
|
||||
// this means that all queens have been placed
|
||||
List<String> sol = new ArrayList<String>();
|
||||
@ -99,7 +111,11 @@ public class NQueens {
|
||||
* @param columnIndex: column in which queen is being placed
|
||||
* @return true: if queen can be placed safely false: otherwise
|
||||
*/
|
||||
private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) {
|
||||
private static boolean isPlacedCorrectly(
|
||||
int[] columns,
|
||||
int rowIndex,
|
||||
int columnIndex
|
||||
) {
|
||||
for (int i = 0; i < columnIndex; i++) {
|
||||
int diff = Math.abs(columns[i] - rowIndex);
|
||||
if (diff == 0 || columnIndex - i == diff) {
|
||||
|
@ -8,6 +8,7 @@ import java.util.List;
|
||||
* @author Alan Piao (https://github.com/cpiao3)
|
||||
*/
|
||||
public class Permutation {
|
||||
|
||||
/**
|
||||
* Find all permutations of given array using backtracking
|
||||
* @param arr the array.
|
||||
@ -20,6 +21,7 @@ public class Permutation {
|
||||
backtracking(array, 0, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backtrack all possible orders of a given array
|
||||
* @param arr the array.
|
||||
@ -37,6 +39,7 @@ public class Permutation {
|
||||
swap(index, i, arr);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap two element for a given array
|
||||
* @param a first index
|
||||
|
@ -18,10 +18,17 @@ public class PowerSum {
|
||||
PowerSum ps = new PowerSum();
|
||||
int count = ps.powSum(N, X);
|
||||
//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);
|
||||
sc.close();
|
||||
}
|
||||
|
||||
private int count = 0, sum = 0;
|
||||
|
||||
public int powSum(int N, int X) {
|
||||
@ -48,7 +55,7 @@ public class PowerSum {
|
||||
}
|
||||
}
|
||||
|
||||
//creating a separate power function so that it can be used again and again when required.
|
||||
//creating a separate power function so that it can be used again and again when required.
|
||||
private int power(int a, int b) {
|
||||
return (int) Math.pow(a, b);
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,8 +1,8 @@
|
||||
package com.thealgorithms.ciphers;
|
||||
|
||||
import javax.crypto.*;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import javax.crypto.*;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
System.out.println("Original Text:" + plainText);
|
||||
System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded()));
|
||||
System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText));
|
||||
System.out.println(
|
||||
"AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())
|
||||
);
|
||||
System.out.println(
|
||||
"Encrypted Text (Hex Form):" + bytesToHex(cipherText)
|
||||
);
|
||||
System.out.println("Descrypted Text:" + decryptedText);
|
||||
}
|
||||
|
||||
@ -38,7 +42,8 @@ public class AESEncryption {
|
||||
* @return secKey (Secret key that we encrypt using it)
|
||||
* @throws NoSuchAlgorithmException (from KeyGenrator)
|
||||
*/
|
||||
public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException {
|
||||
public static SecretKey getSecretEncryptionKey()
|
||||
throws NoSuchAlgorithmException {
|
||||
KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES");
|
||||
aesKeyGenerator.init(128); // The AES key size in number of bits
|
||||
return aesKeyGenerator.generateKey();
|
||||
@ -55,8 +60,7 @@ public class AESEncryption {
|
||||
* @throws IllegalBlockSizeException (from Cipher)
|
||||
*/
|
||||
public static byte[] encryptText(String plainText, SecretKey secKey)
|
||||
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
|
||||
IllegalBlockSizeException, BadPaddingException {
|
||||
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
|
||||
// AES defaults to AES/ECB/PKCS5Padding in Java 7
|
||||
Cipher aesCipher = Cipher.getInstance("AES");
|
||||
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
|
||||
@ -69,8 +73,7 @@ public class AESEncryption {
|
||||
* @return plainText
|
||||
*/
|
||||
public static String decryptText(byte[] byteCipherText, SecretKey secKey)
|
||||
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
|
||||
IllegalBlockSizeException, BadPaddingException {
|
||||
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
|
||||
// AES defaults to AES/ECB/PKCS5Padding in Java 7
|
||||
Cipher aesCipher = Cipher.getInstance("AES");
|
||||
aesCipher.init(Cipher.DECRYPT_MODE, secKey);
|
||||
|
@ -15,10 +15,9 @@ class AffineCipher {
|
||||
{here x is msg[i] and m is 26} and added 'A' to
|
||||
bring it in range of ascii alphabet[ 65-90 | A-Z ] */
|
||||
if (msg[i] != ' ') {
|
||||
cipher = cipher
|
||||
+ (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
|
||||
} else // else simply append space character
|
||||
{
|
||||
cipher =
|
||||
cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
|
||||
} else { // else simply append space character
|
||||
cipher += msg[i];
|
||||
}
|
||||
}
|
||||
@ -46,10 +45,12 @@ class AffineCipher {
|
||||
{here x is cipher[i] and m is 26} and added 'A'
|
||||
to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
|
||||
if (cipher.charAt(i) != ' ') {
|
||||
msg = msg + (char) (((a_inv
|
||||
* ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
|
||||
} else //else simply append space character
|
||||
{
|
||||
msg =
|
||||
msg +
|
||||
(char) (
|
||||
((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'
|
||||
);
|
||||
} else { //else simply append space character
|
||||
msg += cipher.charAt(i);
|
||||
}
|
||||
}
|
||||
@ -66,7 +67,8 @@ class AffineCipher {
|
||||
System.out.println("Encrypted Message is : " + cipherText);
|
||||
|
||||
// Calling Decryption function
|
||||
System.out.println("Decrypted Message is: " + decryptCipher(cipherText));
|
||||
|
||||
System.out.println(
|
||||
"Decrypted Message is: " + decryptCipher(cipherText)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -25,21 +25,16 @@ public class Caesar {
|
||||
|
||||
final int length = message.length();
|
||||
for (int i = 0; i < length; i++) {
|
||||
|
||||
// int current = message.charAt(i); //using char to shift characters because ascii
|
||||
// is in-order latin alphabet
|
||||
char current = message.charAt(i); // Java law : char + int = char
|
||||
|
||||
if (IsCapitalLatinLetter(current)) {
|
||||
|
||||
current += shift;
|
||||
encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
|
||||
|
||||
} else if (IsSmallLatinLetter(current)) {
|
||||
|
||||
current += shift;
|
||||
encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
|
||||
|
||||
} else {
|
||||
encoded.append(current);
|
||||
}
|
||||
@ -62,15 +57,11 @@ public class Caesar {
|
||||
for (int i = 0; i < length; i++) {
|
||||
char current = encryptedMessage.charAt(i);
|
||||
if (IsCapitalLatinLetter(current)) {
|
||||
|
||||
current -= shift;
|
||||
decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
|
||||
|
||||
} else if (IsSmallLatinLetter(current)) {
|
||||
|
||||
current -= shift;
|
||||
decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
|
||||
|
||||
} else {
|
||||
decoded.append(current);
|
||||
}
|
||||
@ -91,12 +82,13 @@ public class Caesar {
|
||||
private static boolean IsSmallLatinLetter(char c) {
|
||||
return c >= 'a' && c <= 'z';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string array which contains all the possible decoded combination.
|
||||
*/
|
||||
public static String[] bruteforce(String encryptedMessage) {
|
||||
String[] listOfAllTheAnswers = new String[27];
|
||||
for (int i=0; i<=26; i++) {
|
||||
for (int i = 0; i <= 26; i++) {
|
||||
listOfAllTheAnswers[i] = decode(encryptedMessage, i);
|
||||
}
|
||||
|
||||
@ -117,24 +109,32 @@ public class Caesar {
|
||||
System.out.println("Please enter the shift number");
|
||||
shift = input.nextInt() % 26;
|
||||
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;
|
||||
case 'D':
|
||||
case 'd':
|
||||
System.out.println("Please enter the shift number");
|
||||
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;
|
||||
case 'B':
|
||||
case 'b':
|
||||
String[] listOfAllTheAnswers = bruteforce(message);
|
||||
for (int i =0; i<=26; i++) {
|
||||
System.out.println("FOR SHIFT " + String.valueOf(i) + " decoded message is " + listOfAllTheAnswers[i]);
|
||||
for (int i = 0; i <= 26; i++) {
|
||||
System.out.println(
|
||||
"FOR SHIFT " +
|
||||
String.valueOf(i) +
|
||||
" decoded message is " +
|
||||
listOfAllTheAnswers[i]
|
||||
);
|
||||
}
|
||||
default:
|
||||
System.out.println("default case");
|
||||
}
|
||||
|
||||
|
||||
input.close();
|
||||
}
|
||||
}
|
||||
|
@ -12,8 +12,9 @@ public class ColumnarTranspositionCipher {
|
||||
private static String keyword;
|
||||
private static Object[][] table;
|
||||
private static String abecedarium;
|
||||
public static final String ABECEDARIUM
|
||||
= "abcdefghijklmnopqrstuvwxyzABCDEFG" + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@";
|
||||
public static final String ABECEDARIUM =
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFG" +
|
||||
"HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@";
|
||||
private static final String ENCRYPTION_FIELD = "≈";
|
||||
private static final char ENCRYPTION_FIELD_CHAR = '≈';
|
||||
|
||||
@ -49,9 +50,14 @@ public class ColumnarTranspositionCipher {
|
||||
* @return a String with the word encrypted by the Columnar Transposition
|
||||
* Cipher Rule
|
||||
*/
|
||||
public static String encrpyter(String word, String keyword, String abecedarium) {
|
||||
public static String encrpyter(
|
||||
String word,
|
||||
String keyword,
|
||||
String abecedarium
|
||||
) {
|
||||
ColumnarTranspositionCipher.keyword = keyword;
|
||||
ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
|
||||
ColumnarTranspositionCipher.abecedarium =
|
||||
Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
|
||||
table = tableBuilder(word);
|
||||
Object[][] sortedTable = sortTable(table);
|
||||
StringBuilder wordEncrypted = new StringBuilder();
|
||||
@ -114,7 +120,9 @@ public class ColumnarTranspositionCipher {
|
||||
* order to respect the Columnar Transposition Cipher Rule.
|
||||
*/
|
||||
private static int numberOfRows(String word) {
|
||||
if (word.length() / keyword.length() > word.length() / keyword.length()) {
|
||||
if (
|
||||
word.length() / keyword.length() > word.length() / keyword.length()
|
||||
) {
|
||||
return (word.length() / keyword.length()) + 1;
|
||||
} else {
|
||||
return word.length() / keyword.length();
|
||||
@ -139,12 +147,22 @@ public class ColumnarTranspositionCipher {
|
||||
private static Object[][] sortTable(Object[][] table) {
|
||||
Object[][] tableSorted = new Object[table.length][table[0].length];
|
||||
for (int i = 0; i < tableSorted.length; i++) {
|
||||
System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length);
|
||||
System.arraycopy(
|
||||
table[i],
|
||||
0,
|
||||
tableSorted[i],
|
||||
0,
|
||||
tableSorted[i].length
|
||||
);
|
||||
}
|
||||
for (int i = 0; i < tableSorted[0].length; i++) {
|
||||
for (int j = i + 1; j < tableSorted[0].length; j++) {
|
||||
if ((int) tableSorted[0][i] > (int) table[0][j]) {
|
||||
Object[] column = getColumn(tableSorted, tableSorted.length, i);
|
||||
Object[] column = getColumn(
|
||||
tableSorted,
|
||||
tableSorted.length,
|
||||
i
|
||||
);
|
||||
switchColumns(tableSorted, j, i, column);
|
||||
}
|
||||
}
|
||||
@ -164,7 +182,11 @@ public class ColumnarTranspositionCipher {
|
||||
}
|
||||
|
||||
private static void switchColumns(
|
||||
Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) {
|
||||
Object[][] table,
|
||||
int firstColumnIndex,
|
||||
int secondColumnIndex,
|
||||
Object[] columnToSwitch
|
||||
) {
|
||||
for (int i = 0; i < table.length; i++) {
|
||||
table[i][secondColumnIndex] = table[i][firstColumnIndex];
|
||||
table[i][firstColumnIndex] = columnToSwitch[i];
|
||||
@ -195,13 +217,22 @@ public class ColumnarTranspositionCipher {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String keywordForExample = "asd215";
|
||||
String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher";
|
||||
System.out.println("### Example of Columnar Transposition Cipher ###\n");
|
||||
String wordBeingEncrypted =
|
||||
"This is a test of the Columnar Transposition Cipher";
|
||||
System.out.println(
|
||||
"### Example of Columnar Transposition Cipher ###\n"
|
||||
);
|
||||
System.out.println("Word being encryped ->>> " + wordBeingEncrypted);
|
||||
System.out.println(
|
||||
"Word encrypted ->>> "
|
||||
+ ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample));
|
||||
System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter());
|
||||
"Word encrypted ->>> " +
|
||||
ColumnarTranspositionCipher.encrpyter(
|
||||
wordBeingEncrypted,
|
||||
keywordForExample
|
||||
)
|
||||
);
|
||||
System.out.println(
|
||||
"Word decryped ->>> " + ColumnarTranspositionCipher.decrypter()
|
||||
);
|
||||
System.out.println("\n### Encrypted Table ###");
|
||||
showTable();
|
||||
}
|
||||
|
@ -29,7 +29,7 @@ public class HillCipher {
|
||||
}
|
||||
}
|
||||
//check if det = 0
|
||||
validateDeterminant(keyMatrix,matrixSize);
|
||||
validateDeterminant(keyMatrix, matrixSize);
|
||||
|
||||
int[][] messageVector = new int[matrixSize][1];
|
||||
String CipherText = "";
|
||||
@ -76,7 +76,7 @@ public class HillCipher {
|
||||
}
|
||||
}
|
||||
//check if det = 0
|
||||
validateDeterminant(keyMatrix,n);
|
||||
validateDeterminant(keyMatrix, n);
|
||||
|
||||
//solving for the required plaintext message
|
||||
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) {
|
||||
System.out.println("Invalid key, as determinant = 0. Program Terminated");
|
||||
System.out.println(
|
||||
"Invalid key, as determinant = 0. Program Terminated"
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@ -169,4 +171,4 @@ public class HillCipher {
|
||||
String message = userInput.nextLine();
|
||||
hillCipher(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -15,12 +15,12 @@ package com.thealgorithms.ciphers;
|
||||
public class Polybius {
|
||||
|
||||
private static final char[][] key = {
|
||||
// 0 1 2 3 4
|
||||
/* 0 */ {'A', 'B', 'C', 'D', 'E'},
|
||||
/* 1 */ {'F', 'G', 'H', 'I', 'J'},
|
||||
/* 2 */ {'K', 'L', 'M', 'N', 'O'},
|
||||
/* 3 */ {'P', 'Q', 'R', 'S', 'T'},
|
||||
/* 4 */ {'V', 'W', 'X', 'Y', 'Z'}
|
||||
// 0 1 2 3 4
|
||||
/* 0 */{ 'A', 'B', 'C', 'D', 'E' },
|
||||
/* 1 */{ 'F', 'G', 'H', 'I', 'J' },
|
||||
/* 2 */{ 'K', 'L', 'M', 'N', 'O' },
|
||||
/* 3 */{ 'P', 'Q', 'R', 'S', 'T' },
|
||||
/* 4 */{ 'V', 'W', 'X', 'Y', 'Z' },
|
||||
};
|
||||
|
||||
private static String findLocationByCharacter(final char character) {
|
||||
@ -49,11 +49,11 @@ public class Polybius {
|
||||
public static String decrypt(final String ciphertext) {
|
||||
final char[] chars = ciphertext.toCharArray();
|
||||
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 pozitionY = Character.getNumericValue(chars[i + 1]);
|
||||
plaintext.append(key[pozitionX][pozitionY]);
|
||||
}
|
||||
return plaintext.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -68,5 +68,4 @@ class ProductCipher {
|
||||
System.out.println(plaintext);
|
||||
sc.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
package com.thealgorithms.ciphers;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.math.BigInteger;
|
||||
import java.security.SecureRandom;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @author Nguyen Duy Tiep on 23-Oct-17.
|
||||
@ -10,14 +10,21 @@ import java.security.SecureRandom;
|
||||
public final class RSA {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
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);
|
||||
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;
|
||||
@ -30,7 +37,8 @@ public final class RSA {
|
||||
* @return encrypted message
|
||||
*/
|
||||
public synchronized String encrypt(String message) {
|
||||
return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString();
|
||||
return (new BigInteger(message.getBytes())).modPow(publicKey, modulus)
|
||||
.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
@ -44,7 +52,10 @@ public final class RSA {
|
||||
* @return plain message
|
||||
*/
|
||||
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);
|
||||
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");
|
||||
|
||||
|
@ -84,9 +84,11 @@ public class SimpleSubCipher {
|
||||
}
|
||||
|
||||
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");
|
||||
System.out.println(b);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -85,7 +85,10 @@ public class SimpleSubstitutionCipher {
|
||||
* TODO remove main and make JUnit Testing
|
||||
*/
|
||||
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");
|
||||
System.out.println(b);
|
||||
}
|
||||
|
@ -9,17 +9,27 @@ package com.thealgorithms.ciphers;
|
||||
public class Vigenere {
|
||||
|
||||
public static String encrypt(final String message, final String key) {
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (int i = 0, j = 0; i < message.length(); i++) {
|
||||
char c = message.charAt(i);
|
||||
if (Character.isLetter(c)) {
|
||||
if (Character.isUpperCase(c)) {
|
||||
result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A'));
|
||||
|
||||
result.append(
|
||||
(char) (
|
||||
(c + key.toUpperCase().charAt(j) - 2 * 'A') %
|
||||
26 +
|
||||
'A'
|
||||
)
|
||||
);
|
||||
} else {
|
||||
result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a'));
|
||||
result.append(
|
||||
(char) (
|
||||
(c + key.toLowerCase().charAt(j) - 2 * 'a') %
|
||||
26 +
|
||||
'a'
|
||||
)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
result.append(c);
|
||||
@ -33,14 +43,20 @@ public class Vigenere {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
for (int i = 0, j = 0; i < message.length(); i++) {
|
||||
|
||||
char c = message.charAt(i);
|
||||
if (Character.isLetter(c)) {
|
||||
if (Character.isUpperCase(c)) {
|
||||
result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26));
|
||||
|
||||
result.append(
|
||||
(char) (
|
||||
'Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26
|
||||
)
|
||||
);
|
||||
} else {
|
||||
result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26));
|
||||
result.append(
|
||||
(char) (
|
||||
'z' - (25 - (c - key.toLowerCase().charAt(j))) % 26
|
||||
)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
result.append(c);
|
||||
|
@ -4,21 +4,22 @@ import java.util.BitSet;
|
||||
|
||||
// https://en.wikipedia.org/wiki/A5/1
|
||||
public class A5Cipher {
|
||||
|
||||
private final A5KeyStreamGenerator keyStreamGenerator;
|
||||
private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
|
||||
|
||||
public A5Cipher( BitSet sessionKey, BitSet frameCounter ) {
|
||||
public A5Cipher(BitSet sessionKey, BitSet frameCounter) {
|
||||
keyStreamGenerator = new A5KeyStreamGenerator();
|
||||
keyStreamGenerator.initialize( sessionKey, frameCounter );
|
||||
keyStreamGenerator.initialize(sessionKey, frameCounter);
|
||||
}
|
||||
|
||||
public BitSet encrypt( BitSet plainTextBits ) {
|
||||
public BitSet encrypt(BitSet plainTextBits) {
|
||||
// create a copy
|
||||
var result = new BitSet( KEY_STREAM_LENGTH );
|
||||
result.xor( plainTextBits );
|
||||
var result = new BitSet(KEY_STREAM_LENGTH);
|
||||
result.xor(plainTextBits);
|
||||
|
||||
var key = keyStreamGenerator.getNextKeyStream();
|
||||
result.xor( key );
|
||||
result.xor(key);
|
||||
|
||||
return result;
|
||||
}
|
||||
@ -26,5 +27,4 @@ public class A5Cipher {
|
||||
public void resetCounter() {
|
||||
keyStreamGenerator.reInitialize();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -4,6 +4,7 @@ import java.util.BitSet;
|
||||
|
||||
// TODO: raise exceptions for improper use
|
||||
public class A5KeyStreamGenerator extends CompositeLFSR {
|
||||
|
||||
private BitSet initialFrameCounter;
|
||||
private BitSet frameCounter;
|
||||
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
|
||||
|
||||
@Override
|
||||
public void initialize( BitSet sessionKey, BitSet frameCounter ) {
|
||||
public void initialize(BitSet sessionKey, BitSet frameCounter) {
|
||||
this.sessionKey = sessionKey;
|
||||
this.frameCounter = (BitSet) frameCounter.clone();
|
||||
this.initialFrameCounter = (BitSet) frameCounter.clone();
|
||||
registers.clear();
|
||||
LFSR lfsr1 = new LFSR( 19, 8, new int[]{ 13, 16, 17, 18 } );
|
||||
LFSR lfsr2 = new LFSR( 22, 10, new int[]{ 20, 21 } );
|
||||
LFSR lfsr3 = new LFSR( 23, 10, new int[]{ 7, 20, 21, 22 } );
|
||||
registers.add( lfsr1 );
|
||||
registers.add( lfsr2 );
|
||||
registers.add( lfsr3 );
|
||||
registers.forEach( lfsr -> lfsr.initialize( sessionKey, frameCounter ) );
|
||||
LFSR lfsr1 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 });
|
||||
LFSR lfsr2 = new LFSR(22, 10, new int[] { 20, 21 });
|
||||
LFSR lfsr3 = new LFSR(23, 10, new int[] { 7, 20, 21, 22 });
|
||||
registers.add(lfsr1);
|
||||
registers.add(lfsr2);
|
||||
registers.add(lfsr3);
|
||||
registers.forEach(lfsr -> lfsr.initialize(sessionKey, frameCounter));
|
||||
}
|
||||
|
||||
public void reInitialize() {
|
||||
this.initialize( sessionKey, initialFrameCounter );
|
||||
this.initialize(sessionKey, initialFrameCounter);
|
||||
}
|
||||
|
||||
public BitSet getNextKeyStream() {
|
||||
for ( int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle )
|
||||
this.clock();
|
||||
for (
|
||||
int cycle = 1;
|
||||
cycle <= INITIAL_CLOCKING_CYCLES;
|
||||
++cycle
|
||||
) this.clock();
|
||||
|
||||
BitSet result = new BitSet( KEY_STREAM_LENGTH );
|
||||
for ( int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle ) {
|
||||
BitSet result = new BitSet(KEY_STREAM_LENGTH);
|
||||
for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) {
|
||||
boolean outputBit = this.clock();
|
||||
result.set( cycle - 1, outputBit );
|
||||
result.set(cycle - 1, outputBit);
|
||||
}
|
||||
|
||||
reInitializeRegisters();
|
||||
@ -45,10 +49,10 @@ public class A5KeyStreamGenerator extends CompositeLFSR {
|
||||
|
||||
private void reInitializeRegisters() {
|
||||
incrementFrameCounter();
|
||||
registers.forEach( lfsr -> lfsr.initialize( sessionKey, frameCounter ) );
|
||||
registers.forEach(lfsr -> lfsr.initialize(sessionKey, frameCounter));
|
||||
}
|
||||
|
||||
private void incrementFrameCounter() {
|
||||
Utils.increment( frameCounter, FRAME_COUNTER_LENGTH );
|
||||
Utils.increment(frameCounter, FRAME_COUNTER_LENGTH);
|
||||
}
|
||||
}
|
||||
|
@ -6,6 +6,7 @@ import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
public abstract class CompositeLFSR implements BaseLFSR {
|
||||
|
||||
protected final List<LFSR> registers = new ArrayList<>();
|
||||
|
||||
/**
|
||||
@ -16,20 +17,24 @@ public abstract class CompositeLFSR implements BaseLFSR {
|
||||
public boolean clock() {
|
||||
boolean majorityBit = getMajorityBit();
|
||||
boolean result = false;
|
||||
for ( var register : registers ) {
|
||||
for (var register : registers) {
|
||||
result ^= register.getLastBit();
|
||||
if ( register.getClockBit() == majorityBit )
|
||||
register.clock();
|
||||
if (register.getClockBit() == majorityBit) register.clock();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean getMajorityBit() {
|
||||
Map<Boolean, Integer> bitCount = new TreeMap<>();
|
||||
bitCount.put( false, 0 );
|
||||
bitCount.put( true, 0 );
|
||||
bitCount.put(false, 0);
|
||||
bitCount.put(true, 0);
|
||||
|
||||
registers.forEach( lfsr -> bitCount.put( lfsr.getClockBit(), bitCount.get( lfsr.getClockBit() ) + 1 ) );
|
||||
return bitCount.get( false ) <= bitCount.get( true );
|
||||
registers.forEach(lfsr ->
|
||||
bitCount.put(
|
||||
lfsr.getClockBit(),
|
||||
bitCount.get(lfsr.getClockBit()) + 1
|
||||
)
|
||||
);
|
||||
return bitCount.get(false) <= bitCount.get(true);
|
||||
}
|
||||
}
|
||||
|
@ -3,71 +3,72 @@ package com.thealgorithms.ciphers.a5;
|
||||
import java.util.BitSet;
|
||||
|
||||
public class LFSR implements BaseLFSR {
|
||||
|
||||
private final BitSet register;
|
||||
private final int length;
|
||||
private final int clockBitIndex;
|
||||
private final int[] tappingBitsIndices;
|
||||
|
||||
public LFSR( int length, int clockBitIndex, int[] tappingBitsIndices ) {
|
||||
public LFSR(int length, int clockBitIndex, int[] tappingBitsIndices) {
|
||||
this.length = length;
|
||||
this.clockBitIndex = clockBitIndex;
|
||||
this.tappingBitsIndices = tappingBitsIndices;
|
||||
register = new BitSet( length );
|
||||
register = new BitSet(length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initialize( BitSet sessionKey, BitSet frameCounter ) {
|
||||
public void initialize(BitSet sessionKey, BitSet frameCounter) {
|
||||
register.clear();
|
||||
clock( sessionKey, SESSION_KEY_LENGTH );
|
||||
clock( frameCounter, FRAME_COUNTER_LENGTH );
|
||||
clock(sessionKey, SESSION_KEY_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
|
||||
// while key 0 index is right most bit, so we reverse it
|
||||
for ( int i = keyLength - 1; i >= 0; --i ) {
|
||||
var newBit = key.get( i ) ^ xorTappingBits();
|
||||
pushBit( newBit );
|
||||
for (int i = keyLength - 1; i >= 0; --i) {
|
||||
var newBit = key.get(i) ^ xorTappingBits();
|
||||
pushBit(newBit);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clock() {
|
||||
return pushBit( xorTappingBits() );
|
||||
return pushBit(xorTappingBits());
|
||||
}
|
||||
|
||||
public boolean getClockBit() {
|
||||
return register.get( clockBitIndex );
|
||||
return register.get(clockBitIndex);
|
||||
}
|
||||
|
||||
public boolean get( int bitIndex ) {
|
||||
return register.get( bitIndex );
|
||||
public boolean get(int bitIndex) {
|
||||
return register.get(bitIndex);
|
||||
}
|
||||
|
||||
public boolean getLastBit() {
|
||||
return register.get( length - 1 );
|
||||
return register.get(length - 1);
|
||||
}
|
||||
|
||||
private boolean xorTappingBits() {
|
||||
boolean result = false;
|
||||
for ( int i : tappingBitsIndices ) {
|
||||
result ^= register.get( i );
|
||||
for (int i : tappingBitsIndices) {
|
||||
result ^= register.get(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean pushBit( boolean bit ) {
|
||||
private boolean pushBit(boolean bit) {
|
||||
boolean discardedBit = rightShift();
|
||||
register.set( 0, bit );
|
||||
register.set(0, bit);
|
||||
return discardedBit;
|
||||
}
|
||||
|
||||
private boolean rightShift() {
|
||||
boolean discardedBit = get( length - 1 );
|
||||
for ( int i = length - 1; i > 0; --i ) {
|
||||
register.set( i, get( i - 1 ) );
|
||||
boolean discardedBit = get(length - 1);
|
||||
for (int i = length - 1; i > 0; --i) {
|
||||
register.set(i, get(i - 1));
|
||||
}
|
||||
register.set( 0, false );
|
||||
register.set(0, false);
|
||||
return discardedBit;
|
||||
}
|
||||
|
||||
|
@ -7,15 +7,16 @@ package com.thealgorithms.ciphers.a5;
|
||||
import java.util.BitSet;
|
||||
|
||||
public class Utils {
|
||||
public static boolean increment( BitSet bits, int size ) {
|
||||
|
||||
public static boolean increment(BitSet bits, int size) {
|
||||
int i = size - 1;
|
||||
while ( i >= 0 && bits.get( i ) ) {
|
||||
bits.set( i--, false );/*from w w w . j a v a 2s .c o m*/
|
||||
while (i >= 0 && bits.get(i)) {
|
||||
bits.set(i--, false);/*from w w w . j a v a 2s .c o m*/
|
||||
}
|
||||
if ( i < 0 ) {
|
||||
if (i < 0) {
|
||||
return false;
|
||||
}
|
||||
bits.set( i, true );
|
||||
bits.set(i, true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
@ -31,7 +31,12 @@ public class AnyBaseToAnyBase {
|
||||
System.out.print("Enter number: ");
|
||||
n = in.next();
|
||||
System.out.print(
|
||||
"Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
|
||||
"Enter beginning base (between " +
|
||||
MINIMUM_BASE +
|
||||
" and " +
|
||||
MAXIMUM_BASE +
|
||||
"): "
|
||||
);
|
||||
b1 = in.nextInt();
|
||||
if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) {
|
||||
System.out.println("Invalid base!");
|
||||
@ -42,7 +47,12 @@ public class AnyBaseToAnyBase {
|
||||
continue;
|
||||
}
|
||||
System.out.print(
|
||||
"Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
|
||||
"Enter end base (between " +
|
||||
MINIMUM_BASE +
|
||||
" and " +
|
||||
MAXIMUM_BASE +
|
||||
"): "
|
||||
);
|
||||
b2 = in.nextInt();
|
||||
if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) {
|
||||
System.out.println("Invalid base!");
|
||||
@ -63,8 +73,42 @@ public class AnyBaseToAnyBase {
|
||||
*/
|
||||
public static boolean validForBase(String n, int base) {
|
||||
char[] validDigits = {
|
||||
'0', '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'
|
||||
'0',
|
||||
'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
|
||||
char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base);
|
||||
|
@ -1,6 +1,7 @@
|
||||
package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
// given a source number , source base, destination base, this code can give you the destination
|
||||
// number.
|
||||
// sn ,sb,db ---> ()dn . this is what we have to do .
|
||||
|
@ -11,7 +11,9 @@ import java.util.ArrayList;
|
||||
public class DecimalToAnyBase {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
||||
BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(System.in)
|
||||
);
|
||||
System.out.println("Enter the decimal input below: ");
|
||||
int decInput = Integer.parseInt(br.readLine());
|
||||
System.out.println();
|
||||
@ -22,7 +24,13 @@ public class DecimalToAnyBase {
|
||||
|
||||
System.out.println("Decimal Input" + " is: " + decInput);
|
||||
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();
|
||||
}
|
||||
|
@ -24,7 +24,9 @@ class DecimalToBinary {
|
||||
public static void conventionalConversion() {
|
||||
int n, b = 0, c = 0, d;
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.printf("Conventional conversion.%n Enter the decimal number: ");
|
||||
System.out.printf(
|
||||
"Conventional conversion.%n Enter the decimal number: "
|
||||
);
|
||||
n = input.nextInt();
|
||||
while (n != 0) {
|
||||
d = n % 2;
|
||||
|
@ -7,7 +7,22 @@ class DecimalToHexaDecimal {
|
||||
private static final int numberOfBitsInAHalfByte = 4;
|
||||
private static final int halfByte = 0x0F;
|
||||
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.
|
||||
|
@ -61,9 +61,7 @@ public class HexToOct {
|
||||
hexadecnum = scan.nextLine();
|
||||
|
||||
// first convert hexadecimal to decimal
|
||||
decnum
|
||||
= hex2decimal(
|
||||
hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
|
||||
decnum = hex2decimal(hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
|
||||
// variable decnum
|
||||
|
||||
// convert decimal to octal
|
||||
|
@ -22,9 +22,20 @@ public class HexaDecimalToBinary {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// 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();
|
||||
|
||||
for (String num : hexNums) {
|
||||
|
@ -9,10 +9,36 @@ package com.thealgorithms.conversions;
|
||||
*/
|
||||
public class IntegerToRoman {
|
||||
|
||||
private static int[] allArabianRomanNumbers
|
||||
= new int[]{1000, 900, 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"};
|
||||
private static int[] allArabianRomanNumbers = new int[] {
|
||||
1000,
|
||||
900,
|
||||
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
|
||||
public static String integerToRoman(int num) {
|
||||
|
@ -32,7 +32,6 @@ public class OctalToDecimal {
|
||||
* @return The decimal number
|
||||
*/
|
||||
public static int convertOctalToDecimal(String inputOctal) {
|
||||
|
||||
try {
|
||||
// Actual conversion of Octal to Decimal:
|
||||
Integer outputDecimal = Integer.parseInt(inputOctal, 8);
|
||||
|
@ -47,7 +47,6 @@ public class OctalToHexadecimal {
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
|
||||
Scanner input = new Scanner(System.in);
|
||||
System.out.print("Enter the Octal number: ");
|
||||
// Take octal number as input from user in a string
|
||||
|
@ -19,30 +19,69 @@ public class RgbHsvConversion {
|
||||
// Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html
|
||||
|
||||
// Test hsvToRgb-method
|
||||
assert Arrays.equals(hsvToRgb(0, 0, 0), new int[]{0, 0, 0});
|
||||
assert Arrays.equals(hsvToRgb(0, 0, 1), new int[]{255, 255, 255});
|
||||
assert Arrays.equals(hsvToRgb(0, 1, 1), new int[]{255, 0, 0});
|
||||
assert Arrays.equals(hsvToRgb(60, 1, 1), new int[]{255, 255, 0});
|
||||
assert Arrays.equals(hsvToRgb(120, 1, 1), new int[]{0, 255, 0});
|
||||
assert Arrays.equals(hsvToRgb(240, 1, 1), new int[]{0, 0, 255});
|
||||
assert Arrays.equals(hsvToRgb(300, 1, 1), new int[]{255, 0, 255});
|
||||
assert Arrays.equals(hsvToRgb(180, 0.5, 0.5), new int[]{64, 128, 128});
|
||||
assert Arrays.equals(hsvToRgb(234, 0.14, 0.88), new int[]{193, 196, 224});
|
||||
assert Arrays.equals(hsvToRgb(330, 0.75, 0.5), new int[]{128, 32, 80});
|
||||
assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] { 0, 0, 0 });
|
||||
assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] { 255, 255, 255 });
|
||||
assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] { 255, 0, 0 });
|
||||
assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] { 255, 255, 0 });
|
||||
assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] { 0, 255, 0 });
|
||||
assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] { 0, 0, 255 });
|
||||
assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] { 255, 0, 255 });
|
||||
assert Arrays.equals(
|
||||
hsvToRgb(180, 0.5, 0.5),
|
||||
new int[] { 64, 128, 128 }
|
||||
);
|
||||
assert Arrays.equals(
|
||||
hsvToRgb(234, 0.14, 0.88),
|
||||
new int[] { 193, 196, 224 }
|
||||
);
|
||||
assert Arrays.equals(
|
||||
hsvToRgb(330, 0.75, 0.5),
|
||||
new int[] { 128, 32, 80 }
|
||||
);
|
||||
|
||||
// Test rgbToHsv-method
|
||||
// approximate-assertions needed because of small deviations due to converting between
|
||||
// int-values and double-values.
|
||||
assert approximatelyEqualHsv(rgbToHsv(0, 0, 0), new double[]{0, 0, 0});
|
||||
assert approximatelyEqualHsv(rgbToHsv(255, 255, 255), new double[]{0, 0, 1});
|
||||
assert approximatelyEqualHsv(rgbToHsv(255, 0, 0), new double[]{0, 1, 1});
|
||||
assert approximatelyEqualHsv(rgbToHsv(255, 255, 0), new double[]{60, 1, 1});
|
||||
assert approximatelyEqualHsv(rgbToHsv(0, 255, 0), new double[]{120, 1, 1});
|
||||
assert approximatelyEqualHsv(rgbToHsv(0, 0, 255), new double[]{240, 1, 1});
|
||||
assert approximatelyEqualHsv(rgbToHsv(255, 0, 255), new double[]{300, 1, 1});
|
||||
assert approximatelyEqualHsv(rgbToHsv(64, 128, 128), new double[]{180, 0.5, 0.5});
|
||||
assert approximatelyEqualHsv(rgbToHsv(193, 196, 224), new double[]{234, 0.14, 0.88});
|
||||
assert approximatelyEqualHsv(rgbToHsv(128, 32, 80), new double[]{330, 0.75, 0.5});
|
||||
assert approximatelyEqualHsv(
|
||||
rgbToHsv(0, 0, 0),
|
||||
new double[] { 0, 0, 0 }
|
||||
);
|
||||
assert approximatelyEqualHsv(
|
||||
rgbToHsv(255, 255, 255),
|
||||
new double[] { 0, 0, 1 }
|
||||
);
|
||||
assert approximatelyEqualHsv(
|
||||
rgbToHsv(255, 0, 0),
|
||||
new double[] { 0, 1, 1 }
|
||||
);
|
||||
assert approximatelyEqualHsv(
|
||||
rgbToHsv(255, 255, 0),
|
||||
new double[] { 60, 1, 1 }
|
||||
);
|
||||
assert approximatelyEqualHsv(
|
||||
rgbToHsv(0, 255, 0),
|
||||
new double[] { 120, 1, 1 }
|
||||
);
|
||||
assert approximatelyEqualHsv(
|
||||
rgbToHsv(0, 0, 255),
|
||||
new double[] { 240, 1, 1 }
|
||||
);
|
||||
assert approximatelyEqualHsv(
|
||||
rgbToHsv(255, 0, 255),
|
||||
new double[] { 300, 1, 1 }
|
||||
);
|
||||
assert approximatelyEqualHsv(
|
||||
rgbToHsv(64, 128, 128),
|
||||
new double[] { 180, 0.5, 0.5 }
|
||||
);
|
||||
assert approximatelyEqualHsv(
|
||||
rgbToHsv(193, 196, 224),
|
||||
new double[] { 234, 0.14, 0.88 }
|
||||
);
|
||||
assert approximatelyEqualHsv(
|
||||
rgbToHsv(128, 32, 80),
|
||||
new double[] { 330, 0.75, 0.5 }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -55,23 +94,35 @@ public class RgbHsvConversion {
|
||||
*/
|
||||
public static int[] hsvToRgb(double hue, double saturation, double value) {
|
||||
if (hue < 0 || hue > 360) {
|
||||
throw new IllegalArgumentException("hue should be between 0 and 360");
|
||||
throw new IllegalArgumentException(
|
||||
"hue should be between 0 and 360"
|
||||
);
|
||||
}
|
||||
|
||||
if (saturation < 0 || saturation > 1) {
|
||||
throw new IllegalArgumentException("saturation should be between 0 and 1");
|
||||
throw new IllegalArgumentException(
|
||||
"saturation should be between 0 and 1"
|
||||
);
|
||||
}
|
||||
|
||||
if (value < 0 || value > 1) {
|
||||
throw new IllegalArgumentException("value should be between 0 and 1");
|
||||
throw new IllegalArgumentException(
|
||||
"value should be between 0 and 1"
|
||||
);
|
||||
}
|
||||
|
||||
double chroma = value * saturation;
|
||||
double hueSection = hue / 60;
|
||||
double secondLargestComponent = chroma * (1 - Math.abs(hueSection % 2 - 1));
|
||||
double secondLargestComponent =
|
||||
chroma * (1 - Math.abs(hueSection % 2 - 1));
|
||||
double matchValue = value - chroma;
|
||||
|
||||
return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent);
|
||||
return getRgbBySection(
|
||||
hueSection,
|
||||
chroma,
|
||||
matchValue,
|
||||
secondLargestComponent
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -84,15 +135,21 @@ public class RgbHsvConversion {
|
||||
*/
|
||||
public static double[] rgbToHsv(int red, int green, int blue) {
|
||||
if (red < 0 || red > 255) {
|
||||
throw new IllegalArgumentException("red should be between 0 and 255");
|
||||
throw new IllegalArgumentException(
|
||||
"red should be between 0 and 255"
|
||||
);
|
||||
}
|
||||
|
||||
if (green < 0 || green > 255) {
|
||||
throw new IllegalArgumentException("green should be between 0 and 255");
|
||||
throw new IllegalArgumentException(
|
||||
"green should be between 0 and 255"
|
||||
);
|
||||
}
|
||||
|
||||
if (blue < 0 || blue > 255) {
|
||||
throw new IllegalArgumentException("blue should be between 0 and 255");
|
||||
throw new IllegalArgumentException(
|
||||
"blue should be between 0 and 255"
|
||||
);
|
||||
}
|
||||
|
||||
double dRed = (double) red / 255;
|
||||
@ -115,7 +172,7 @@ public class RgbHsvConversion {
|
||||
|
||||
hue = (hue + 360) % 360;
|
||||
|
||||
return new double[]{hue, saturation, value};
|
||||
return new double[] { hue, saturation, value };
|
||||
}
|
||||
|
||||
private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) {
|
||||
@ -127,7 +184,11 @@ public class RgbHsvConversion {
|
||||
}
|
||||
|
||||
private static int[] getRgbBySection(
|
||||
double hueSection, double chroma, double matchValue, double secondLargestComponent) {
|
||||
double hueSection,
|
||||
double chroma,
|
||||
double matchValue,
|
||||
double secondLargestComponent
|
||||
) {
|
||||
int red;
|
||||
int green;
|
||||
int blue;
|
||||
@ -158,7 +219,7 @@ public class RgbHsvConversion {
|
||||
blue = convertToInt(secondLargestComponent + matchValue);
|
||||
}
|
||||
|
||||
return new int[]{red, green, blue};
|
||||
return new int[] { red, green, blue };
|
||||
}
|
||||
|
||||
private static int convertToInt(double input) {
|
||||
|
@ -4,8 +4,7 @@ import java.util.*;
|
||||
|
||||
public class RomanToInteger {
|
||||
|
||||
private static Map<Character, Integer> map
|
||||
= new HashMap<Character, Integer>() {
|
||||
private static Map<Character, Integer> map = new HashMap<Character, Integer>() {
|
||||
/**
|
||||
* */
|
||||
private static final long serialVersionUID = 87605733047260530L;
|
||||
@ -20,6 +19,7 @@ public class RomanToInteger {
|
||||
put('M', 1000);
|
||||
}
|
||||
};
|
||||
|
||||
// Roman Number = Roman Numerals
|
||||
|
||||
/**
|
||||
@ -29,7 +29,6 @@ public class RomanToInteger {
|
||||
* @return integer
|
||||
*/
|
||||
public static int romanToInt(String A) {
|
||||
|
||||
A = A.toUpperCase();
|
||||
char prev = ' ';
|
||||
|
||||
|
@ -29,13 +29,40 @@ public class TurkishToLatinConversion {
|
||||
* @return String
|
||||
*/
|
||||
public static String convertTurkishToLatin(String param) {
|
||||
char[] turkishChars
|
||||
= new char[]{0x131, 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'};
|
||||
char[] turkishChars = new char[] {
|
||||
0x131,
|
||||
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++) {
|
||||
param
|
||||
= param.replaceAll(
|
||||
new String(new char[]{turkishChars[i]}), new String(new char[]{latinChars[i]}));
|
||||
param =
|
||||
param.replaceAll(
|
||||
new String(new char[] { turkishChars[i] }),
|
||||
new String(new char[] { latinChars[i] })
|
||||
);
|
||||
}
|
||||
return param;
|
||||
}
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.thealgorithms.datastructures.bloomfilter;
|
||||
|
||||
|
||||
import java.util.BitSet;
|
||||
|
||||
public class BloomFilter<T> {
|
||||
@ -23,14 +22,14 @@ public class BloomFilter<T> {
|
||||
}
|
||||
|
||||
public void insert(T key) {
|
||||
for (Hash<T> hash : hashFunctions){
|
||||
for (Hash<T> hash : hashFunctions) {
|
||||
int position = hash.compute(key) % bitArray.size();
|
||||
bitArray.set(position);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean contains(T key) {
|
||||
for (Hash<T> hash : hashFunctions){
|
||||
for (Hash<T> hash : hashFunctions) {
|
||||
int position = hash.compute(key) % bitArray.size();
|
||||
if (!bitArray.get(position)) {
|
||||
return false;
|
||||
@ -43,21 +42,20 @@ public class BloomFilter<T> {
|
||||
|
||||
int index;
|
||||
|
||||
public Hash(int index){
|
||||
public Hash(int index) {
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
public int compute(T key){
|
||||
public int compute(T key) {
|
||||
return index * asciiString(String.valueOf(key));
|
||||
}
|
||||
|
||||
private int asciiString(String word){
|
||||
private int asciiString(String word) {
|
||||
int number = 0;
|
||||
for (int i=0;i<word.length();i++){
|
||||
for (int i = 0; i < word.length(); i++) {
|
||||
number += word.charAt(i);
|
||||
}
|
||||
return number;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -32,7 +32,6 @@ public class CircularBuffer {
|
||||
|
||||
// if we have data to read
|
||||
if (_readable_data.get() > 0) {
|
||||
|
||||
result = Character.valueOf(_buffer[getTrueIndex(_read_index)]);
|
||||
_readable_data.decrementAndGet();
|
||||
_read_index++;
|
||||
|
@ -7,141 +7,136 @@ import java.util.Map;
|
||||
* Java program for LFU Cache (https://en.wikipedia.org/wiki/Least_frequently_used)
|
||||
* @author Akshay Dubey (https://github.com/itsAkshayDubey)
|
||||
*/
|
||||
public class LFUCache<K,V> {
|
||||
public class LFUCache<K, V> {
|
||||
|
||||
private class Node {
|
||||
private K key;
|
||||
private V value;
|
||||
private int frequency;
|
||||
private Node previous;
|
||||
private Node next;
|
||||
private class Node {
|
||||
|
||||
public Node(K key, V value, int frequency) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
this.frequency = frequency;
|
||||
}
|
||||
}
|
||||
private K key;
|
||||
private V value;
|
||||
private int frequency;
|
||||
private Node previous;
|
||||
private Node next;
|
||||
|
||||
private Node head;
|
||||
private Node tail;
|
||||
private Map<K,Node> map = null;
|
||||
private Integer capacity;
|
||||
private static final int DEFAULT_CAPACITY = 100;
|
||||
|
||||
public LFUCache() {
|
||||
this.capacity = DEFAULT_CAPACITY;
|
||||
}
|
||||
public Node(K key, V value, int frequency) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
this.frequency = frequency;
|
||||
}
|
||||
}
|
||||
|
||||
private Node head;
|
||||
private Node tail;
|
||||
private Map<K, Node> map = null;
|
||||
private Integer capacity;
|
||||
private static final int DEFAULT_CAPACITY = 100;
|
||||
|
||||
public LFUCache() {
|
||||
this.capacity = DEFAULT_CAPACITY;
|
||||
}
|
||||
|
||||
public LFUCache(Integer capacity) {
|
||||
this.capacity = 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
|
||||
*
|
||||
* @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
|
||||
*/
|
||||
public V get(K key) {
|
||||
if(this.map.get(key) == null) {
|
||||
return null;
|
||||
}
|
||||
public V get(K key) {
|
||||
if (this.map.get(key) == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Node node = map.get(key);
|
||||
removeNode(node);
|
||||
node.frequency += 1;
|
||||
addNodeWithUpdatedFrequency(node);
|
||||
Node node = map.get(key);
|
||||
removeNode(node);
|
||||
node.frequency += 1;
|
||||
addNodeWithUpdatedFrequency(node);
|
||||
|
||||
return node.value;
|
||||
}
|
||||
return node.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method stores <K> key and <V> value 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) {
|
||||
if(map.containsKey(key)) {
|
||||
Node node = map.get(key);
|
||||
node.value = value;
|
||||
node.frequency += 1;
|
||||
removeNode(node);
|
||||
addNodeWithUpdatedFrequency(node);
|
||||
}
|
||||
else {
|
||||
if(map.size() >= capacity) {
|
||||
map.remove(this.head.key);
|
||||
removeNode(head);
|
||||
}
|
||||
Node node = new Node(key,value,1);
|
||||
addNodeWithUpdatedFrequency(node);
|
||||
map.put(key, node);
|
||||
}
|
||||
}
|
||||
public void put(K key, V value) {
|
||||
if (map.containsKey(key)) {
|
||||
Node node = map.get(key);
|
||||
node.value = value;
|
||||
node.frequency += 1;
|
||||
removeNode(node);
|
||||
addNodeWithUpdatedFrequency(node);
|
||||
} else {
|
||||
if (map.size() >= capacity) {
|
||||
map.remove(this.head.key);
|
||||
removeNode(head);
|
||||
}
|
||||
Node node = new Node(key, value, 1);
|
||||
addNodeWithUpdatedFrequency(node);
|
||||
map.put(key, node);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
if(tail != null && head != null) {
|
||||
Node temp = this.head;
|
||||
while(temp != null) {
|
||||
if(temp.frequency > node.frequency) {
|
||||
if(temp==head) {
|
||||
node.next = temp;
|
||||
temp.previous = node;
|
||||
this.head = node;
|
||||
break;
|
||||
}
|
||||
else {
|
||||
node.next = temp;
|
||||
node.previous = temp.previous;
|
||||
temp.previous.next = node;
|
||||
node.previous = temp.previous;
|
||||
break;
|
||||
}
|
||||
}
|
||||
else {
|
||||
temp = temp.next;
|
||||
if(temp == null) {
|
||||
tail.next = node;
|
||||
node.previous = tail;
|
||||
node.next = null;
|
||||
tail = node;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
tail = node;
|
||||
head = tail;
|
||||
}
|
||||
}
|
||||
private void addNodeWithUpdatedFrequency(Node node) {
|
||||
if (tail != null && head != null) {
|
||||
Node temp = this.head;
|
||||
while (temp != null) {
|
||||
if (temp.frequency > node.frequency) {
|
||||
if (temp == head) {
|
||||
node.next = temp;
|
||||
temp.previous = node;
|
||||
this.head = node;
|
||||
break;
|
||||
} else {
|
||||
node.next = temp;
|
||||
node.previous = temp.previous;
|
||||
temp.previous.next = node;
|
||||
node.previous = temp.previous;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
temp = temp.next;
|
||||
if (temp == null) {
|
||||
tail.next = node;
|
||||
node.previous = tail;
|
||||
node.next = null;
|
||||
tail = node;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tail = node;
|
||||
head = tail;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method removes node from the cache
|
||||
*
|
||||
* @param Node node which is to be removed in the cache
|
||||
* This method removes node from the cache
|
||||
*
|
||||
* @param Node node which is to be removed in the cache
|
||||
*/
|
||||
private void removeNode(Node node) {
|
||||
if(node.previous != null) {
|
||||
node.previous.next = node.next;
|
||||
}
|
||||
else {
|
||||
this.head = node.next;
|
||||
}
|
||||
private void removeNode(Node node) {
|
||||
if (node.previous != null) {
|
||||
node.previous.next = node.next;
|
||||
} else {
|
||||
this.head = node.next;
|
||||
}
|
||||
|
||||
if(node.next != null) {
|
||||
node.next.previous = node.previous;
|
||||
}
|
||||
else {
|
||||
this.tail = node.previous;
|
||||
}
|
||||
}
|
||||
if (node.next != null) {
|
||||
node.next.previous = node.previous;
|
||||
} else {
|
||||
this.tail = node.previous;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -126,10 +126,14 @@ public class LRUCache<K, V> {
|
||||
private I key;
|
||||
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.nextEntry = nextEntry;
|
||||
this.key = key;
|
||||
|
@ -124,10 +124,14 @@ public class MRUCache<K, V> {
|
||||
private I key;
|
||||
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.nextEntry = nextEntry;
|
||||
this.key = key;
|
||||
|
@ -6,8 +6,6 @@ public class DisjointSets<T> {
|
||||
return new Node<T>(x);
|
||||
}
|
||||
|
||||
;
|
||||
|
||||
public Node<T> FindSet(Node<T> node) {
|
||||
if (node != node.parent) {
|
||||
node.parent = FindSet(node.parent);
|
||||
|
@ -44,7 +44,8 @@ public class DynamicArray<E> implements Iterable<E> {
|
||||
*/
|
||||
public void add(final E element) {
|
||||
if (this.size == this.elements.length) {
|
||||
this.elements = Arrays.copyOf(this.elements, newCapacity(2 * this.capacity));
|
||||
this.elements =
|
||||
Arrays.copyOf(this.elements, newCapacity(2 * this.capacity));
|
||||
}
|
||||
|
||||
this.elements[this.size] = element;
|
||||
@ -83,7 +84,8 @@ public class DynamicArray<E> implements Iterable<E> {
|
||||
fastRemove(this.elements, index);
|
||||
|
||||
if (this.capacity > DEFAULT_CAPACITY && size * 4 <= this.capacity) {
|
||||
this.elements = Arrays.copyOf(this.elements, newCapacity(this.capacity / 2));
|
||||
this.elements =
|
||||
Arrays.copyOf(this.elements, newCapacity(this.capacity / 2));
|
||||
}
|
||||
return oldElement;
|
||||
}
|
||||
@ -114,7 +116,13 @@ public class DynamicArray<E> implements Iterable<E> {
|
||||
final int newSize = this.size - 1;
|
||||
|
||||
if (newSize > index) {
|
||||
System.arraycopy(elements, index + 1, elements, index, newSize - index);
|
||||
System.arraycopy(
|
||||
elements,
|
||||
index + 1,
|
||||
elements,
|
||||
index,
|
||||
newSize - index
|
||||
);
|
||||
}
|
||||
|
||||
elements[this.size = newSize] = null;
|
||||
@ -136,7 +144,9 @@ public class DynamicArray<E> implements Iterable<E> {
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray());
|
||||
return Arrays.toString(
|
||||
Arrays.stream(this.elements).filter(Objects::nonNull).toArray()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -8,6 +8,7 @@ import java.util.*;
|
||||
public class A_Star {
|
||||
|
||||
private static class Graph {
|
||||
|
||||
// Graph's structure can be changed only applying changes to this class.
|
||||
|
||||
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.
|
||||
private void addEdge(Edge edge) {
|
||||
this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight()));
|
||||
this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
|
||||
this.graph.get(edge.getFrom())
|
||||
.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 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.path = path;
|
||||
this.estimated = estimated;
|
||||
@ -84,16 +91,24 @@ public class A_Star {
|
||||
private void printSolution() {
|
||||
if (this.path != null) {
|
||||
System.out.println(
|
||||
"Optimal path: " + this.path + ", distance: " + this.distance);
|
||||
"Optimal path: " +
|
||||
this.path +
|
||||
", distance: " +
|
||||
this.distance
|
||||
);
|
||||
} else {
|
||||
System.out.println("There is no path available to connect the points");
|
||||
System.out.println(
|
||||
"There is no path available to connect the points"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void initializeGraph(Graph graph, ArrayList<Integer> data) {
|
||||
for (int i = 0; i < data.size(); i += 4) {
|
||||
graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2)));
|
||||
graph.addEdge(
|
||||
new Edge(data.get(i), data.get(i + 1), data.get(i + 2))
|
||||
);
|
||||
}
|
||||
/*
|
||||
.x. node
|
||||
@ -127,30 +142,146 @@ public class A_Star {
|
||||
public static void main(String[] args) {
|
||||
// heuristic function optimistic values
|
||||
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);
|
||||
ArrayList<Integer> graphData
|
||||
= new ArrayList<>(
|
||||
Arrays.asList(
|
||||
0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151,
|
||||
null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14,
|
||||
146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, 15, 5, 99, null, 14,
|
||||
13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null,
|
||||
17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87));
|
||||
ArrayList<Integer> graphData = new ArrayList<>(
|
||||
Arrays.asList(
|
||||
0,
|
||||
19,
|
||||
75,
|
||||
null,
|
||||
0,
|
||||
15,
|
||||
140,
|
||||
null,
|
||||
0,
|
||||
16,
|
||||
118,
|
||||
null,
|
||||
19,
|
||||
12,
|
||||
71,
|
||||
null,
|
||||
12,
|
||||
15,
|
||||
151,
|
||||
null,
|
||||
16,
|
||||
9,
|
||||
111,
|
||||
null,
|
||||
9,
|
||||
10,
|
||||
70,
|
||||
null,
|
||||
10,
|
||||
3,
|
||||
75,
|
||||
null,
|
||||
3,
|
||||
2,
|
||||
120,
|
||||
null,
|
||||
2,
|
||||
14,
|
||||
146,
|
||||
null,
|
||||
2,
|
||||
13,
|
||||
138,
|
||||
null,
|
||||
2,
|
||||
6,
|
||||
115,
|
||||
null,
|
||||
15,
|
||||
14,
|
||||
80,
|
||||
null,
|
||||
15,
|
||||
5,
|
||||
99,
|
||||
null,
|
||||
14,
|
||||
13,
|
||||
97,
|
||||
null,
|
||||
5,
|
||||
1,
|
||||
211,
|
||||
null,
|
||||
13,
|
||||
1,
|
||||
101,
|
||||
null,
|
||||
6,
|
||||
1,
|
||||
160,
|
||||
null,
|
||||
1,
|
||||
17,
|
||||
85,
|
||||
null,
|
||||
17,
|
||||
7,
|
||||
98,
|
||||
null,
|
||||
7,
|
||||
4,
|
||||
86,
|
||||
null,
|
||||
17,
|
||||
18,
|
||||
142,
|
||||
null,
|
||||
18,
|
||||
8,
|
||||
92,
|
||||
null,
|
||||
8,
|
||||
11,
|
||||
87
|
||||
)
|
||||
);
|
||||
initializeGraph(graph, graphData);
|
||||
|
||||
PathAndDistance solution = aStar(3, 1, graph, heuristic);
|
||||
solution.printSolution();
|
||||
}
|
||||
|
||||
public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) {
|
||||
public static PathAndDistance aStar(
|
||||
int from,
|
||||
int to,
|
||||
Graph graph,
|
||||
int[] heuristic
|
||||
) {
|
||||
// nodes are prioritised by the less value of the current distance of their paths, and the
|
||||
// estimated value
|
||||
// given by the heuristic function to reach the destination point from the current point.
|
||||
PriorityQueue<PathAndDistance> queue
|
||||
= new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
|
||||
PriorityQueue<PathAndDistance> queue = new PriorityQueue<>(
|
||||
Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))
|
||||
);
|
||||
|
||||
// dummy data to start the algorithm from the beginning point
|
||||
queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0));
|
||||
@ -159,26 +290,33 @@ public class A_Star {
|
||||
PathAndDistance currentData = new PathAndDistance(-1, null, -1);
|
||||
while (!queue.isEmpty() && !solutionFound) {
|
||||
currentData = queue.poll(); // first in the queue, best node so keep exploring.
|
||||
int currentPosition
|
||||
= currentData.getPath().get(currentData.getPath().size() - 1); // current node.
|
||||
int currentPosition = currentData
|
||||
.getPath()
|
||||
.get(currentData.getPath().size() - 1); // current node.
|
||||
if (currentPosition == to) {
|
||||
solutionFound = true;
|
||||
} else {
|
||||
for (Edge edge : graph.getNeighbours(currentPosition)) {
|
||||
if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles
|
||||
ArrayList<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,
|
||||
// and the heuristic function value associated to that path.
|
||||
queue.add(
|
||||
new PathAndDistance(
|
||||
currentData.getDistance() + edge.getWeight(),
|
||||
updatedPath,
|
||||
heuristic[edge.getTo()]));
|
||||
new PathAndDistance(
|
||||
currentData.getDistance() + edge.getWeight(),
|
||||
updatedPath,
|
||||
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
|
||||
// distance
|
||||
}
|
||||
|
@ -3,7 +3,7 @@ package com.thealgorithms.datastructures.graphs;
|
||||
import java.util.*;
|
||||
|
||||
class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have
|
||||
start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/ {
|
||||
start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{
|
||||
|
||||
int vertex, edge;
|
||||
private Edge edges[];
|
||||
@ -37,8 +37,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
* @param i Current vertex under consideration
|
||||
*/
|
||||
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;
|
||||
}
|
||||
printPath(p, p[i]);
|
||||
@ -50,10 +49,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
obj.go();
|
||||
}
|
||||
|
||||
public void
|
||||
go() // Interactive run for understanding the class first time. Assumes source vertex is 0 and
|
||||
// shows distance to all vertices
|
||||
{
|
||||
public void go() { // shows distance to all vertices // Interactive run for understanding the class first time. Assumes source vertex is 0 and
|
||||
Scanner sc = new Scanner(System.in); // Grab scanner object for user input
|
||||
int i, v, e, u, ve, w, j, neg = 0;
|
||||
System.out.println("Enter no. of vertices and edges please");
|
||||
@ -67,8 +63,7 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
w = sc.nextInt();
|
||||
arr[i] = new Edge(u, ve, w);
|
||||
}
|
||||
int dist[]
|
||||
= new int[v]; // Distance array for holding the finalized shortest path distance between source
|
||||
int dist[] = new int[v]; // Distance array for holding the finalized shortest path distance between source
|
||||
// and all vertices
|
||||
int p[] = new int[v]; // Parent array for holding the paths
|
||||
for (i = 0; i < v; i++) {
|
||||
@ -78,8 +73,10 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
p[0] = -1;
|
||||
for (i = 0; i < v - 1; i++) {
|
||||
for (j = 0; j < e; j++) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
|
||||
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
if (
|
||||
(int) dist[arr[j].u] != Integer.MAX_VALUE &&
|
||||
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
|
||||
) {
|
||||
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
|
||||
p[arr[j].v] = arr[j].u;
|
||||
}
|
||||
@ -87,14 +84,16 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
}
|
||||
// Final cycle for negative checking
|
||||
for (j = 0; j < e; j++) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
if (
|
||||
(int) dist[arr[j].u] != Integer.MAX_VALUE &&
|
||||
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
|
||||
) {
|
||||
neg = 1;
|
||||
System.out.println("Negative cycle");
|
||||
break;
|
||||
}
|
||||
}
|
||||
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: ");
|
||||
for (i = 0; i < v; 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 Edge Array of edges
|
||||
*/
|
||||
public void show(
|
||||
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
|
||||
{
|
||||
public void show(int source, int end, Edge arr[]) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should
|
||||
int i, j, v = vertex, e = edge, neg = 0;
|
||||
double dist[]
|
||||
= new double[v]; // Distance array for holding the finalized shortest path distance between source
|
||||
double dist[] = new double[v]; // Distance array for holding the finalized shortest path distance between source
|
||||
// and all vertices
|
||||
int p[] = new int[v]; // Parent array for holding the paths
|
||||
for (i = 0; i < v; i++) {
|
||||
@ -132,8 +125,10 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
p[source] = -1;
|
||||
for (i = 0; i < v - 1; i++) {
|
||||
for (j = 0; j < e; j++) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
|
||||
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
if (
|
||||
(int) dist[arr[j].u] != Integer.MAX_VALUE &&
|
||||
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
|
||||
) {
|
||||
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
|
||||
p[arr[j].v] = arr[j].u;
|
||||
}
|
||||
@ -141,14 +136,16 @@ start vertex, end vertex and weights. Vertices should be labelled with a number
|
||||
}
|
||||
// Final cycle for negative checking
|
||||
for (j = 0; j < e; j++) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
if (
|
||||
(int) dist[arr[j].u] != Integer.MAX_VALUE &&
|
||||
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
|
||||
) {
|
||||
neg = 1;
|
||||
System.out.println("Negative cycle");
|
||||
break;
|
||||
}
|
||||
}
|
||||
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("Path followed:");
|
||||
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 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);
|
||||
}
|
||||
|
||||
|
@ -16,7 +16,12 @@ import java.util.Arrays;
|
||||
*/
|
||||
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) {
|
||||
color[node] = 1;
|
||||
}
|
||||
@ -33,7 +38,10 @@ public class BipartiteGrapfDFS {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isBipartite(int V, ArrayList<ArrayList<Integer>> adj) {
|
||||
public static boolean isBipartite(
|
||||
int V,
|
||||
ArrayList<ArrayList<Integer>> adj
|
||||
) {
|
||||
// Code here
|
||||
int[] color = new int[V + 1];
|
||||
Arrays.fill(color, -1);
|
||||
@ -49,7 +57,9 @@ public class BipartiteGrapfDFS {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
|
||||
BufferedReader read = new BufferedReader(
|
||||
new InputStreamReader(System.in)
|
||||
);
|
||||
int t = Integer.parseInt(read.readLine().trim());
|
||||
while (t-- > 0) {
|
||||
String[] S = read.readLine().trim().split(" ");
|
||||
|
@ -137,7 +137,11 @@ public class ConnectedComponent {
|
||||
graphInts.addEdge(8, 10);
|
||||
graphInts.addEdge(10, 8);
|
||||
|
||||
System.out.println("Amount of different char-graphs: " + graphChars.countGraphs());
|
||||
System.out.println("Amount of different int-graphs: " + graphInts.countGraphs());
|
||||
System.out.println(
|
||||
"Amount of different char-graphs: " + graphChars.countGraphs()
|
||||
);
|
||||
System.out.println(
|
||||
"Amount of different int-graphs: " + graphInts.countGraphs()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -24,7 +24,9 @@ class Cycle {
|
||||
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++) {
|
||||
int start, end;
|
||||
|
@ -40,13 +40,17 @@ class dijkstras {
|
||||
dist[src] = 0;
|
||||
|
||||
for (int c = 0; c < k - 1; c++) {
|
||||
|
||||
int u = minDist(dist, Set);
|
||||
|
||||
Set[u] = true;
|
||||
|
||||
for (int v = 0; v < k; v++) {
|
||||
if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
|
||||
if (
|
||||
!Set[v] &&
|
||||
graph[u][v] != 0 &&
|
||||
dist[u] != Integer.MAX_VALUE &&
|
||||
dist[u] + graph[u][v] < dist[v]
|
||||
) {
|
||||
dist[v] = dist[u] + graph[u][v];
|
||||
}
|
||||
}
|
||||
@ -56,21 +60,21 @@ class dijkstras {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int graph[][] = new int[][]{{0, 4, 0, 0, 0, 0, 0, 8, 0},
|
||||
{4, 0, 8, 0, 0, 0, 0, 11, 0},
|
||||
{0, 8, 0, 7, 0, 4, 0, 0, 2},
|
||||
{0, 0, 7, 0, 9, 14, 0, 0, 0},
|
||||
{0, 0, 0, 9, 0, 10, 0, 0, 0},
|
||||
{0, 0, 4, 14, 10, 0, 2, 0, 0},
|
||||
{0, 0, 0, 0, 0, 2, 0, 1, 6},
|
||||
{8, 11, 0, 0, 0, 0, 1, 0, 7},
|
||||
{0, 0, 2, 0, 0, 0, 6, 7, 0}};
|
||||
int graph[][] = new int[][] {
|
||||
{ 0, 4, 0, 0, 0, 0, 0, 8, 0 },
|
||||
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
|
||||
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
|
||||
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
|
||||
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
|
||||
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
|
||||
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
|
||||
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
|
||||
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 },
|
||||
};
|
||||
dijkstras t = new dijkstras();
|
||||
t.dijkstra(graph, 0);
|
||||
}//main
|
||||
|
||||
}//djikstras
|
||||
|
||||
} //main
|
||||
} //djikstras
|
||||
/*
|
||||
OUTPUT :
|
||||
Vertex Distance
|
||||
|
@ -9,31 +9,42 @@ public class FloydWarshall {
|
||||
public static final int INFINITY = 999;
|
||||
|
||||
public FloydWarshall(int numberofvertices) {
|
||||
DistanceMatrix
|
||||
= new int[numberofvertices + 1][numberofvertices
|
||||
+ 1]; // stores the value of distance from all the possible path form the source
|
||||
DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source
|
||||
// vertex to destination vertex
|
||||
// The matrix is initialized with 0's by default
|
||||
this.numberofvertices = numberofvertices;
|
||||
}
|
||||
|
||||
public void floydwarshall(
|
||||
int AdjacencyMatrix[][]) // calculates all the distances from source to destination vertex
|
||||
{
|
||||
public void floydwarshall(int AdjacencyMatrix[][]) { // calculates all the distances from source to destination vertex
|
||||
for (int source = 1; source <= numberofvertices; source++) {
|
||||
for (int destination = 1; destination <= numberofvertices; destination++) {
|
||||
DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination];
|
||||
for (
|
||||
int destination = 1;
|
||||
destination <= numberofvertices;
|
||||
destination++
|
||||
) {
|
||||
DistanceMatrix[source][destination] =
|
||||
AdjacencyMatrix[source][destination];
|
||||
}
|
||||
}
|
||||
for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) {
|
||||
for (
|
||||
int intermediate = 1;
|
||||
intermediate <= numberofvertices;
|
||||
intermediate++
|
||||
) {
|
||||
for (int source = 1; source <= numberofvertices; source++) {
|
||||
for (int destination = 1; destination <= numberofvertices; destination++) {
|
||||
if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination]
|
||||
< DistanceMatrix[source][destination]) // if the new distance calculated is less then the earlier shortest
|
||||
// calculated distance it get replaced as new shortest distance
|
||||
{
|
||||
for (
|
||||
int destination = 1;
|
||||
destination <= numberofvertices;
|
||||
destination++
|
||||
) {
|
||||
if (
|
||||
DistanceMatrix[source][intermediate] +
|
||||
DistanceMatrix[intermediate][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();
|
||||
for (int source = 1; source <= numberofvertices; source++) {
|
||||
System.out.print(source + "\t");
|
||||
for (int destination = 1; destination <= numberofvertices; destination++) {
|
||||
for (
|
||||
int destination = 1;
|
||||
destination <= numberofvertices;
|
||||
destination++
|
||||
) {
|
||||
System.out.print(DistanceMatrix[source][destination] + "\t");
|
||||
}
|
||||
System.out.println();
|
||||
@ -55,10 +70,15 @@ public class FloydWarshall {
|
||||
Scanner scan = new Scanner(System.in);
|
||||
System.out.println("Enter the number of vertices");
|
||||
int numberOfVertices = scan.nextInt();
|
||||
int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1];
|
||||
int[][] adjacencyMatrix = new int[numberOfVertices +
|
||||
1][numberOfVertices + 1];
|
||||
System.out.println("Enter the Weighted Matrix for the graph");
|
||||
for (int source = 1; source <= numberOfVertices; source++) {
|
||||
for (int destination = 1; destination <= numberOfVertices; destination++) {
|
||||
for (
|
||||
int destination = 1;
|
||||
destination <= numberOfVertices;
|
||||
destination++
|
||||
) {
|
||||
adjacencyMatrix[source][destination] = scan.nextInt();
|
||||
if (source == destination) {
|
||||
adjacencyMatrix[source][destination] = 0;
|
||||
|
@ -12,33 +12,32 @@ public class HamiltonianCycle {
|
||||
|
||||
/**
|
||||
* Find hamiltonian cycle for given graph G(V,E)
|
||||
* @param graph Adjacency matrix of a graph G(V, E)
|
||||
* @param graph Adjacency matrix of a graph G(V, E)
|
||||
* for which hamiltonian path is to be found
|
||||
* @return Array containing hamiltonian cycle
|
||||
* @return Array containing hamiltonian cycle
|
||||
* else returns 1D array with value -1.
|
||||
*/
|
||||
public int[] findHamiltonianCycle(int[][] graph){
|
||||
public int[] findHamiltonianCycle(int[][] graph) {
|
||||
this.V = graph.length;
|
||||
this.cycle = new int[this.V+1];
|
||||
this.cycle = new int[this.V + 1];
|
||||
|
||||
//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.graph = graph;
|
||||
this.graph = graph;
|
||||
|
||||
this.cycle[0] = 0;
|
||||
this.pathCount = 1;
|
||||
if(!isPathFound(0)) {
|
||||
for(int i=0 ; i<this.cycle.length ; i++) {
|
||||
this.pathCount = 1;
|
||||
if (!isPathFound(0)) {
|
||||
for (int i = 0; i < this.cycle.length; i++) {
|
||||
this.cycle[i] = -1;
|
||||
}
|
||||
} else {
|
||||
this.cycle[this.cycle.length - 1] = this.cycle[0];
|
||||
}
|
||||
else {
|
||||
this.cycle[this.cycle.length-1] = this.cycle[0];
|
||||
}
|
||||
|
||||
|
||||
return cycle;
|
||||
}
|
||||
|
||||
@ -57,13 +56,13 @@ public class HamiltonianCycle {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int v = 0; v < this.V; v++){
|
||||
for (int v = 0; v < this.V; v++) {
|
||||
/** if connected **/
|
||||
if (this.graph[vertex][v] == 1 ){
|
||||
/** add to path **/
|
||||
this.cycle[this.pathCount++] = v;
|
||||
if (this.graph[vertex][v] == 1) {
|
||||
/** add to path **/
|
||||
this.cycle[this.pathCount++] = v;
|
||||
|
||||
/** remove connection **/
|
||||
/** remove connection **/
|
||||
this.graph[vertex][v] = 0;
|
||||
this.graph[v][vertex] = 0;
|
||||
|
||||
@ -81,14 +80,13 @@ public class HamiltonianCycle {
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** function to 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++) {
|
||||
if (cycle[i] == vertex) {
|
||||
return true;
|
||||
|
@ -1,12 +1,12 @@
|
||||
package com.thealgorithms.datastructures.graphs;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.Set;
|
||||
import java.util.Queue;
|
||||
import java.util.LinkedHashMap;
|
||||
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.
|
||||
@ -124,7 +124,6 @@ class TopologicalSort<E extends Comparable<E>> {
|
||||
}
|
||||
|
||||
return answer;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -134,7 +133,6 @@ class TopologicalSort<E extends Comparable<E>> {
|
||||
public class KahnsAlgorithm {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//Graph definition and initialization
|
||||
AdjacencyList<String> graph = new AdjacencyList<>();
|
||||
graph.addEdge("a", "b");
|
||||
|
@ -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));
|
||||
}
|
||||
|
||||
@ -53,7 +58,9 @@ public class Kruskal {
|
||||
System.out.println("Initial Graph: ");
|
||||
for (int i = 0; i < graph.length; i++) {
|
||||
for (Edge edge : graph[i]) {
|
||||
System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to);
|
||||
System.out.println(
|
||||
i + " <-- weight " + edge.weight + " --> " + edge.to
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -63,7 +70,9 @@ public class Kruskal {
|
||||
System.out.println("\nMinimal Graph: ");
|
||||
for (int i = 0; i < solGraph.length; i++) {
|
||||
for (Edge edge : solGraph[i]) {
|
||||
System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to);
|
||||
System.out.println(
|
||||
i + " <-- weight " + edge.weight + " --> " + edge.to
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -74,7 +83,9 @@ public class Kruskal {
|
||||
// captain of i, stores the set with all the connected nodes to i
|
||||
HashSet<Integer>[] connectedGroups = 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++) {
|
||||
minGraph[i] = new HashSet<>();
|
||||
connectedGroups[i] = new HashSet<>();
|
||||
@ -87,12 +98,18 @@ public class Kruskal {
|
||||
while (connectedElements != nodes && !edges.isEmpty()) {
|
||||
Edge edge = edges.poll();
|
||||
// This if avoids cycles
|
||||
if (!connectedGroups[captain[edge.from]].contains(edge.to)
|
||||
&& !connectedGroups[captain[edge.to]].contains(edge.from)) {
|
||||
if (
|
||||
!connectedGroups[captain[edge.from]].contains(edge.to) &&
|
||||
!connectedGroups[captain[edge.to]].contains(edge.from)
|
||||
) {
|
||||
// merge sets of the captains of each point connected by the edge
|
||||
connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]);
|
||||
connectedGroups[captain[edge.from]].addAll(
|
||||
connectedGroups[captain[edge.to]]
|
||||
);
|
||||
// update captains of the elements merged
|
||||
connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]);
|
||||
connectedGroups[captain[edge.from]].forEach(i ->
|
||||
captain[i] = captain[edge.from]
|
||||
);
|
||||
// add Edge to minimal graph
|
||||
addEdge(minGraph, edge.from, edge.to, edge.weight);
|
||||
// count how many elements have been merged
|
||||
|
@ -1,9 +1,9 @@
|
||||
package com.thealgorithms.datastructures.graphs;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.ArrayList;
|
||||
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
|
||||
@ -71,7 +71,9 @@ class AdjacencyMatrixGraph {
|
||||
public AdjacencyMatrixGraph(int givenNumberOfVertices) {
|
||||
this.setNumberOfVertices(givenNumberOfVertices);
|
||||
this.setNumberOfEdges(0);
|
||||
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
|
||||
this.setAdjacency(
|
||||
new int[givenNumberOfVertices][givenNumberOfVertices]
|
||||
);
|
||||
for (int i = 0; i < givenNumberOfVertices; i++) {
|
||||
for (int j = 0; j < givenNumberOfVertices; j++) {
|
||||
this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
|
||||
@ -101,7 +103,7 @@ class AdjacencyMatrixGraph {
|
||||
* Updates the number of edges in the graph
|
||||
*
|
||||
* @param newNumberOfEdges
|
||||
*
|
||||
*
|
||||
*/
|
||||
private void setNumberOfEdges(int newNumberOfEdges) {
|
||||
this._numberOfEdges = newNumberOfEdges;
|
||||
@ -249,7 +251,11 @@ class AdjacencyMatrixGraph {
|
||||
* has been 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 (visited[currentVertex]) {
|
||||
return;
|
||||
@ -262,9 +268,11 @@ class AdjacencyMatrixGraph {
|
||||
|
||||
// Get the adjacency array for this vertex
|
||||
int[] adjacent = _adjacency[currentVertex];
|
||||
for (int i = 0; i < adjacent.length; i++) // If an edge exists between the currentVertex and the vertex
|
||||
// we are considering exploring, recurse on it
|
||||
{
|
||||
for (
|
||||
int i = 0;
|
||||
i < adjacent.length;
|
||||
i++
|
||||
) { // we are considering exploring, recurse on it // If an edge exists between the currentVertex and the vertex
|
||||
if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) {
|
||||
depthFirstOrder(i, visited, orderList);
|
||||
}
|
||||
@ -310,12 +318,14 @@ class AdjacencyMatrixGraph {
|
||||
orderList.add(currentVertex);
|
||||
visited[currentVertex] = true;
|
||||
|
||||
// Get the adjacency array for the currentVertex and
|
||||
// Get the adjacency array for the currentVertex and
|
||||
// check each node
|
||||
int[] adjacent = _adjacency[currentVertex];
|
||||
for (int vertex = 0; vertex < adjacent.length; vertex++) // If an edge exists between the current vertex and the
|
||||
// vertex we are considering exploring, we add it to the queue
|
||||
{
|
||||
for (
|
||||
int vertex = 0;
|
||||
vertex < adjacent.length;
|
||||
vertex++
|
||||
) { // vertex we are considering exploring, we add it to the queue // If an edge exists between the current vertex and the
|
||||
if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) {
|
||||
queue.add(vertex);
|
||||
}
|
||||
|
@ -5,6 +5,7 @@ package com.thealgorithms.datastructures.graphs;
|
||||
* matrix representation of the graph
|
||||
*/
|
||||
class PrimMST {
|
||||
|
||||
// Number of vertices in the graph
|
||||
|
||||
private static final int V = 5;
|
||||
@ -30,7 +31,9 @@ class PrimMST {
|
||||
void printMST(int parent[], int n, int graph[][]) {
|
||||
System.out.println("Edge Weight");
|
||||
for (int i = 1; i < V; i++) {
|
||||
System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]);
|
||||
System.out.println(
|
||||
parent[i] + " - " + i + " " + graph[i][parent[i]]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -69,11 +72,17 @@ class PrimMST {
|
||||
// Update key value and parent index of the adjacent
|
||||
// vertices of the picked vertex. Consider only those
|
||||
// vertices which are not yet included in MST
|
||||
for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent vertices of m
|
||||
// mstSet[v] is false for vertices not yet included in MST
|
||||
// Update the key only if graph[u][v] is smaller than key[v]
|
||||
for (
|
||||
int v = 0;
|
||||
v < V;
|
||||
v++
|
||||
) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is false for vertices not yet included in MST // graph[u][v] is non zero only for adjacent vertices of m
|
||||
{
|
||||
if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) {
|
||||
if (
|
||||
graph[u][v] != 0 &&
|
||||
mstSet[v] == false &&
|
||||
graph[u][v] < key[v]
|
||||
) {
|
||||
parent[v] = u;
|
||||
key[v] = graph[u][v];
|
||||
}
|
||||
@ -94,9 +103,13 @@ class PrimMST {
|
||||
(3)-------(4)
|
||||
9 */
|
||||
PrimMST t = new PrimMST();
|
||||
int graph[][]
|
||||
= new int[][]{
|
||||
{0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0},};
|
||||
int graph[][] = new int[][] {
|
||||
{ 0, 2, 0, 6, 0 },
|
||||
{ 2, 0, 3, 8, 5 },
|
||||
{ 0, 3, 0, 0, 7 },
|
||||
{ 6, 8, 0, 0, 9 },
|
||||
{ 0, 5, 7, 9, 0 },
|
||||
};
|
||||
|
||||
// Print the solution
|
||||
t.primMST(graph);
|
||||
|
@ -5,6 +5,7 @@ import java.util.LinkedList;
|
||||
// implementation of generic hashmaps using array of Linked Lists
|
||||
|
||||
public class GenericHashMapUsingArray<K, V> {
|
||||
|
||||
private int size; // n (total number of key-value pairs)
|
||||
private LinkedList<Node>[] buckets; // N = buckets.length
|
||||
private float lf = 0.75f;
|
||||
@ -13,6 +14,7 @@ public class GenericHashMapUsingArray<K, V> {
|
||||
initBuckets(16);
|
||||
size = 0;
|
||||
}
|
||||
|
||||
// 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
|
||||
// & then add 76th item.
|
||||
@ -114,6 +116,7 @@ public class GenericHashMapUsingArray<K, V> {
|
||||
}
|
||||
|
||||
public class Node {
|
||||
|
||||
K key;
|
||||
V value;
|
||||
|
||||
|
@ -4,6 +4,7 @@ import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class GenericHashMapUsingArrayList<K, V> {
|
||||
|
||||
ArrayList<LinkedList<Node>> buckets;
|
||||
private float lf = 0.5f;
|
||||
private int size;
|
||||
@ -100,6 +101,7 @@ public class GenericHashMapUsingArrayList<K, V> {
|
||||
}
|
||||
|
||||
private class Node {
|
||||
|
||||
K key;
|
||||
V val;
|
||||
|
||||
@ -108,5 +110,4 @@ public class GenericHashMapUsingArrayList<K, V> {
|
||||
this.val = val;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.thealgorithms.datastructures.hashmap.hashing;
|
||||
|
||||
|
||||
import java.lang.Math;
|
||||
import java.util.Objects;
|
||||
|
||||
@ -71,19 +70,26 @@ public class HashMapCuckooHashing {
|
||||
int hash, loopCounter = 0;
|
||||
|
||||
if (isFull()) {
|
||||
System.out.println("Hash table is full, lengthening & rehashing table");
|
||||
System.out.println(
|
||||
"Hash table is full, lengthening & rehashing table"
|
||||
);
|
||||
reHashTableIncreasesTableSize();
|
||||
}
|
||||
|
||||
if (checkTableContainsKey(key)) {
|
||||
throw new IllegalArgumentException("Key already inside, no duplicates allowed");
|
||||
throw new IllegalArgumentException(
|
||||
"Key already inside, no duplicates allowed"
|
||||
);
|
||||
}
|
||||
|
||||
while (loopCounter <= thresh) {
|
||||
loopCounter++;
|
||||
hash = hashFunction1(key);
|
||||
|
||||
if ((buckets[hash] == null) || Objects.equals(buckets[hash], AVAILABLE)) {
|
||||
if (
|
||||
(buckets[hash] == null) ||
|
||||
Objects.equals(buckets[hash], AVAILABLE)
|
||||
) {
|
||||
buckets[hash] = wrappedInt;
|
||||
size++;
|
||||
checkLoadFactor();
|
||||
@ -110,7 +116,9 @@ public class HashMapCuckooHashing {
|
||||
buckets[hash] = wrappedInt;
|
||||
wrappedInt = temp;
|
||||
}
|
||||
System.out.println("Infinite loop occurred, lengthening & rehashing table");
|
||||
System.out.println(
|
||||
"Infinite loop occurred, lengthening & rehashing table"
|
||||
);
|
||||
reHashTableIncreasesTableSize();
|
||||
insertKey2HashTable(key);
|
||||
}
|
||||
@ -132,7 +140,6 @@ public class HashMapCuckooHashing {
|
||||
this.thresh = (int) (Math.log(tableSize) / Math.log(2)) + 2;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* deletes a key from the hash map and adds an available placeholder
|
||||
*
|
||||
@ -157,7 +164,9 @@ public class HashMapCuckooHashing {
|
||||
size--;
|
||||
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)) {
|
||||
System.out.println("Bucket " + i + ": Empty");
|
||||
} else {
|
||||
System.out.println("Bucket " + i + ": " + buckets[i].toString());
|
||||
System.out.println(
|
||||
"Bucket " + i + ": " + buckets[i].toString()
|
||||
);
|
||||
}
|
||||
}
|
||||
System.out.println();
|
||||
@ -191,20 +202,32 @@ public class HashMapCuckooHashing {
|
||||
if (Objects.equals(buckets[hash], wrappedInt)) return hash;
|
||||
|
||||
hash = hashFunction2(key);
|
||||
if (!Objects.equals(buckets[hash], wrappedInt))
|
||||
throw new IllegalArgumentException("Key " + key + " not found in table");
|
||||
else {
|
||||
if (
|
||||
!Objects.equals(buckets[hash], wrappedInt)
|
||||
) throw new IllegalArgumentException(
|
||||
"Key " + key + " not found in table"
|
||||
); else {
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if key is inside without any output other than returned boolean.
|
||||
*
|
||||
* @param key the desired key to be found
|
||||
* @return int the index where the key is located
|
||||
*/
|
||||
public boolean checkTableContainsKey(int key){
|
||||
return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key)) || (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key));
|
||||
public boolean checkTableContainsKey(int 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() {
|
||||
double factor = (double) size / tableSize;
|
||||
if (factor > .7) {
|
||||
System.out.printf("Load factor is %.2f , rehashing table\n", factor);
|
||||
System.out.printf(
|
||||
"Load factor is %.2f , rehashing table\n",
|
||||
factor
|
||||
);
|
||||
reHashTableIncreasesTableSize();
|
||||
}
|
||||
return factor;
|
||||
@ -250,5 +276,8 @@ public class HashMapCuckooHashing {
|
||||
}
|
||||
return response;
|
||||
}
|
||||
public int getNumberOfKeysInTable(){return size;}
|
||||
|
||||
public int getNumberOfKeysInTable() {
|
||||
return size;
|
||||
}
|
||||
}
|
||||
|
@ -107,7 +107,9 @@ public class HashMapLinearProbing {
|
||||
if (buckets[i] == null || buckets[i] == AVAILABLE) {
|
||||
System.out.println("Bucket " + i + ": Empty");
|
||||
} else {
|
||||
System.out.println("Bucket " + i + ": " + buckets[i].toString());
|
||||
System.out.println(
|
||||
"Bucket " + i + ": " + buckets[i].toString()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -133,8 +135,7 @@ public class HashMapLinearProbing {
|
||||
buckets[hash] = AVAILABLE;
|
||||
return hash;
|
||||
}
|
||||
} catch (Exception E) {
|
||||
}
|
||||
} catch (Exception E) {}
|
||||
|
||||
if (hash + 1 < hsize) {
|
||||
hash++;
|
||||
@ -159,7 +160,9 @@ public class HashMapLinearProbing {
|
||||
public void checkLoadFactor() {
|
||||
double factor = (double) size / hsize;
|
||||
if (factor > .7) {
|
||||
System.out.println("Load factor is " + factor + ", lengthening table");
|
||||
System.out.println(
|
||||
"Load factor is " + factor + ", lengthening table"
|
||||
);
|
||||
lengthenTable();
|
||||
} else {
|
||||
System.out.println("Load factor is " + factor);
|
||||
|
@ -15,7 +15,9 @@ import java.util.Map;
|
||||
public class Intersection {
|
||||
|
||||
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();
|
||||
}
|
||||
Map<Integer, Integer> cnt = new HashMap<>(16);
|
||||
@ -32,7 +34,5 @@ public class Intersection {
|
||||
return res;
|
||||
}
|
||||
|
||||
private Intersection() {
|
||||
|
||||
}
|
||||
private Intersection() {}
|
||||
}
|
||||
|
@ -5,7 +5,6 @@ import java.util.Scanner;
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
int choice, key;
|
||||
|
||||
HashMap h = new HashMap(7);
|
||||
@ -21,27 +20,31 @@ public class Main {
|
||||
choice = In.nextInt();
|
||||
|
||||
switch (choice) {
|
||||
case 1: {
|
||||
System.out.println("Enter the Key: ");
|
||||
key = In.nextInt();
|
||||
h.insertHash(key);
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
System.out.println("Enter the Key delete: ");
|
||||
key = In.nextInt();
|
||||
h.deleteHash(key);
|
||||
break;
|
||||
}
|
||||
case 3: {
|
||||
System.out.println("Print table");
|
||||
h.displayHashtable();
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
In.close();
|
||||
return;
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
System.out.println("Enter the Key: ");
|
||||
key = In.nextInt();
|
||||
h.insertHash(key);
|
||||
break;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
System.out.println("Enter the Key delete: ");
|
||||
key = In.nextInt();
|
||||
h.deleteHash(key);
|
||||
break;
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
System.out.println("Print table");
|
||||
h.displayHashtable();
|
||||
break;
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
In.close();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,8 +3,8 @@ package com.thealgorithms.datastructures.hashmap.hashing;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class MainCuckooHashing {
|
||||
public static void main(String[] args) {
|
||||
|
||||
public static void main(String[] args) {
|
||||
int choice, key;
|
||||
|
||||
HashMapCuckooHashing h = new HashMapCuckooHashing(7);
|
||||
@ -24,41 +24,59 @@ public class MainCuckooHashing {
|
||||
choice = In.nextInt();
|
||||
|
||||
switch (choice) {
|
||||
case 1: {
|
||||
System.out.println("Enter the Key: ");
|
||||
key = In.nextInt();
|
||||
h.insertKey2HashTable(key);
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
System.out.println("Enter the Key delete: ");
|
||||
key = In.nextInt();
|
||||
h.deleteKeyFromHashTable(key);
|
||||
break;
|
||||
}
|
||||
case 3: {
|
||||
System.out.println("Print table:\n");
|
||||
h.displayHashtable();
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
In.close();
|
||||
return;
|
||||
}
|
||||
case 5: {
|
||||
System.out.println("Enter the Key to find and print: ");
|
||||
key = In.nextInt();
|
||||
System.out.println("Key: " + key + " is at index: " + h.findKeyInTable(key) + "\n");
|
||||
break;
|
||||
}
|
||||
case 6: {
|
||||
System.out.printf("Load factor is: %.2f\n", h.checkLoadFactor());
|
||||
break;
|
||||
}
|
||||
case 7: {
|
||||
h.reHashTableIncreasesTableSize();
|
||||
break;
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
System.out.println("Enter the Key: ");
|
||||
key = In.nextInt();
|
||||
h.insertKey2HashTable(key);
|
||||
break;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
System.out.println("Enter the Key delete: ");
|
||||
key = In.nextInt();
|
||||
h.deleteKeyFromHashTable(key);
|
||||
break;
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
System.out.println("Print table:\n");
|
||||
h.displayHashtable();
|
||||
break;
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
In.close();
|
||||
return;
|
||||
}
|
||||
case 5:
|
||||
{
|
||||
System.out.println(
|
||||
"Enter the Key to find and print: "
|
||||
);
|
||||
key = In.nextInt();
|
||||
System.out.println(
|
||||
"Key: " +
|
||||
key +
|
||||
" is at index: " +
|
||||
h.findKeyInTable(key) +
|
||||
"\n"
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 6:
|
||||
{
|
||||
System.out.printf(
|
||||
"Load factor is: %.2f\n",
|
||||
h.checkLoadFactor()
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 7:
|
||||
{
|
||||
h.reHashTableIncreasesTableSize();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,7 +5,6 @@ import java.util.Scanner;
|
||||
public class MainLinearProbing {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
int choice, key;
|
||||
|
||||
HashMapLinearProbing h = new HashMapLinearProbing(7);
|
||||
@ -23,37 +22,47 @@ public class MainLinearProbing {
|
||||
choice = In.nextInt();
|
||||
|
||||
switch (choice) {
|
||||
case 1: {
|
||||
System.out.println("Enter the Key: ");
|
||||
key = In.nextInt();
|
||||
h.insertHash(key);
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
System.out.println("Enter the Key delete: ");
|
||||
key = In.nextInt();
|
||||
h.deleteHash(key);
|
||||
break;
|
||||
}
|
||||
case 3: {
|
||||
System.out.println("Print table");
|
||||
h.displayHashtable();
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
In.close();
|
||||
return;
|
||||
}
|
||||
case 5: {
|
||||
System.out.println("Enter the Key to find and print: ");
|
||||
key = In.nextInt();
|
||||
System.out.println("Key: " + key + " is at index: " + h.findHash(key));
|
||||
break;
|
||||
}
|
||||
case 6: {
|
||||
h.checkLoadFactor();
|
||||
break;
|
||||
}
|
||||
case 1:
|
||||
{
|
||||
System.out.println("Enter the Key: ");
|
||||
key = In.nextInt();
|
||||
h.insertHash(key);
|
||||
break;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
System.out.println("Enter the Key delete: ");
|
||||
key = In.nextInt();
|
||||
h.deleteHash(key);
|
||||
break;
|
||||
}
|
||||
case 3:
|
||||
{
|
||||
System.out.println("Print table");
|
||||
h.displayHashtable();
|
||||
break;
|
||||
}
|
||||
case 4:
|
||||
{
|
||||
In.close();
|
||||
return;
|
||||
}
|
||||
case 5:
|
||||
{
|
||||
System.out.println(
|
||||
"Enter the Key to find and print: "
|
||||
);
|
||||
key = In.nextInt();
|
||||
System.out.println(
|
||||
"Key: " + key + " is at index: " + h.findHash(key)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 6:
|
||||
{
|
||||
h.checkLoadFactor();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.thealgorithms.datastructures.heaps;
|
||||
|
||||
|
||||
public class FibonacciHeap {
|
||||
|
||||
private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;
|
||||
@ -48,7 +47,7 @@ public class FibonacciHeap {
|
||||
* $ret = the HeapNode we inserted
|
||||
*/
|
||||
public HeapNode insert(int key) {
|
||||
HeapNode toInsert = new HeapNode(key); //creates the node
|
||||
HeapNode toInsert = new HeapNode(key); //creates the node
|
||||
if (this.empty()) {
|
||||
this.min = toInsert;
|
||||
} else { //tree is not empty
|
||||
@ -142,9 +141,12 @@ public class FibonacciHeap {
|
||||
*/
|
||||
public int[] countersRep() {
|
||||
if (this.empty()) {
|
||||
return new int[0]; ///return an empty array
|
||||
return new int[0]; ///return an empty array
|
||||
}
|
||||
int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; //creates the array
|
||||
int[] rankArray = new int[(int) Math.floor(
|
||||
Math.log(this.size()) / Math.log(GOLDEN_RATIO)
|
||||
) +
|
||||
1]; //creates the array
|
||||
rankArray[this.min.rank]++;
|
||||
HeapNode curr = this.min.next;
|
||||
while (curr != this.min) {
|
||||
@ -161,8 +163,8 @@ public class FibonacciHeap {
|
||||
* @post (numOfnodes = = $prev numOfnodes - 1)
|
||||
*/
|
||||
public void delete(HeapNode x) {
|
||||
this.decreaseKey(x, x.getKey() + 1); //change key to be the minimal (-1)
|
||||
this.deleteMin(); //delete it
|
||||
this.decreaseKey(x, x.getKey() + 1); //change key to be the minimal (-1)
|
||||
this.deleteMin(); //delete it
|
||||
}
|
||||
|
||||
/**
|
||||
@ -174,7 +176,7 @@ public class FibonacciHeap {
|
||||
private void decreaseKey(HeapNode x, int delta) {
|
||||
int newKey = x.getKey() - delta;
|
||||
x.key = newKey;
|
||||
if (x.isRoot()) {//no parent to x
|
||||
if (x.isRoot()) { //no parent to x
|
||||
this.updateMin(x);
|
||||
return;
|
||||
}
|
||||
@ -229,7 +231,7 @@ public class FibonacciHeap {
|
||||
* @post (numOfnodes == $prev numOfnodes)
|
||||
*/
|
||||
private void cascadingCuts(HeapNode curr) {
|
||||
if (!curr.isMarked()) { //stop the recursion
|
||||
if (!curr.isMarked()) { //stop the recursion
|
||||
curr.mark();
|
||||
if (!curr.isRoot()) this.markedHeapNoodesCounter++;
|
||||
return;
|
||||
@ -257,7 +259,7 @@ public class FibonacciHeap {
|
||||
if (curr.parent.child == curr) { //we should change the parent's child
|
||||
if (curr.next == curr) { //curr do not have brothers
|
||||
curr.parent.child = null;
|
||||
} else {//curr have brothers
|
||||
} else { //curr have brothers
|
||||
curr.parent.child = curr.next;
|
||||
}
|
||||
}
|
||||
@ -272,7 +274,6 @@ public class FibonacciHeap {
|
||||
totalCuts++;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
*
|
||||
*/
|
||||
@ -285,7 +286,10 @@ public class FibonacciHeap {
|
||||
*
|
||||
*/
|
||||
private HeapNode[] toBuckets(HeapNode curr) {
|
||||
HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
|
||||
HeapNode[] buckets = new HeapNode[(int) Math.floor(
|
||||
Math.log(this.size()) / Math.log(GOLDEN_RATIO)
|
||||
) +
|
||||
1];
|
||||
curr.prev.next = null;
|
||||
HeapNode tmpCurr;
|
||||
while (curr != null) {
|
||||
@ -347,7 +351,6 @@ public class FibonacciHeap {
|
||||
return c1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* public class HeapNode
|
||||
* each HeapNode belongs to a heap (Inner class)
|
||||
@ -381,7 +384,6 @@ public class FibonacciHeap {
|
||||
return this.key;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* checks whether the node is marked
|
||||
* $ret = true if one child has been cut
|
||||
@ -397,7 +399,7 @@ public class FibonacciHeap {
|
||||
private void mark() {
|
||||
if (this.isRoot()) {
|
||||
return;
|
||||
} //check if the node is a root
|
||||
} //check if the node is a root
|
||||
this.marked = true;
|
||||
}
|
||||
|
||||
|
@ -2,70 +2,88 @@ package com.thealgorithms.datastructures.heaps;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class GenericHeap <T extends Comparable <T> >{
|
||||
ArrayList <T> data=new ArrayList<>();
|
||||
HashMap<T,Integer> map=new HashMap<>();
|
||||
public void add(T item) {
|
||||
this.data.add(item);
|
||||
map.put(item,this.data.size()-1);//
|
||||
upHeapify(this.data.size()-1);
|
||||
}
|
||||
private void upHeapify(int ci) {
|
||||
int pi=(ci-1)/2;
|
||||
if(isLarger(this.data.get(ci),this.data.get(pi))>0) {
|
||||
swap(pi,ci);
|
||||
upHeapify(pi);
|
||||
}
|
||||
}
|
||||
public void display() {
|
||||
System.out.println(this.data);
|
||||
}
|
||||
public int size() {
|
||||
return this.data.size();
|
||||
}
|
||||
public boolean isEmpty() {
|
||||
return this.size()==0;
|
||||
}
|
||||
public T remove() {
|
||||
this.swap(0,this.size()-1);
|
||||
T rv=this.data.remove(this.size()-1);
|
||||
downHeapify(0);
|
||||
map.remove(rv);
|
||||
return rv;
|
||||
}
|
||||
private void downHeapify(int pi) {
|
||||
int lci=2*pi+1;
|
||||
int rci=2*pi+2;
|
||||
int mini=pi;
|
||||
if(lci<this.size() && isLarger(this.data.get(lci),this.data.get(mini))>0) {
|
||||
mini=lci;
|
||||
}
|
||||
if(rci<this.size() && isLarger(this.data.get(rci),this.data.get(mini))>0) {
|
||||
mini=rci;
|
||||
}
|
||||
if(mini!=pi) {
|
||||
this.swap(pi,mini);
|
||||
downHeapify(mini);
|
||||
}
|
||||
}
|
||||
public T get() {
|
||||
return this.data.get(0);
|
||||
}
|
||||
//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);
|
||||
}
|
||||
public class GenericHeap<T extends Comparable<T>> {
|
||||
|
||||
ArrayList<T> data = new ArrayList<>();
|
||||
HashMap<T, Integer> map = new HashMap<>();
|
||||
|
||||
public void add(T item) {
|
||||
this.data.add(item);
|
||||
map.put(item, this.data.size() - 1); //
|
||||
upHeapify(this.data.size() - 1);
|
||||
}
|
||||
|
||||
private void upHeapify(int ci) {
|
||||
int pi = (ci - 1) / 2;
|
||||
if (isLarger(this.data.get(ci), this.data.get(pi)) > 0) {
|
||||
swap(pi, ci);
|
||||
upHeapify(pi);
|
||||
}
|
||||
}
|
||||
|
||||
public void display() {
|
||||
System.out.println(this.data);
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return this.data.size();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return this.size() == 0;
|
||||
}
|
||||
|
||||
public T remove() {
|
||||
this.swap(0, this.size() - 1);
|
||||
T rv = this.data.remove(this.size() - 1);
|
||||
downHeapify(0);
|
||||
map.remove(rv);
|
||||
return rv;
|
||||
}
|
||||
|
||||
private void downHeapify(int pi) {
|
||||
int lci = 2 * pi + 1;
|
||||
int rci = 2 * pi + 2;
|
||||
int mini = pi;
|
||||
if (
|
||||
lci < this.size() &&
|
||||
isLarger(this.data.get(lci), this.data.get(mini)) > 0
|
||||
) {
|
||||
mini = lci;
|
||||
}
|
||||
if (
|
||||
rci < this.size() &&
|
||||
isLarger(this.data.get(rci), this.data.get(mini)) > 0
|
||||
) {
|
||||
mini = rci;
|
||||
}
|
||||
if (mini != pi) {
|
||||
this.swap(pi, mini);
|
||||
downHeapify(mini);
|
||||
}
|
||||
}
|
||||
|
||||
public T get() {
|
||||
return this.data.get(0);
|
||||
}
|
||||
|
||||
//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);
|
||||
}
|
||||
}
|
||||
|
@ -19,7 +19,6 @@ package com.thealgorithms.datastructures.heaps;
|
||||
* @author Nicolas Renard
|
||||
*/
|
||||
public interface Heap {
|
||||
|
||||
/**
|
||||
* @return the top element in the heap, the one with lowest key for min-heap
|
||||
* or with the highest key for max-heap
|
||||
|
@ -122,8 +122,10 @@ public class HeapElement {
|
||||
return false;
|
||||
}
|
||||
HeapElement otherHeapElement = (HeapElement) o;
|
||||
return (this.key == otherHeapElement.key)
|
||||
&& (this.additionalInfo.equals(otherHeapElement.additionalInfo));
|
||||
return (
|
||||
(this.key == otherHeapElement.key) &&
|
||||
(this.additionalInfo.equals(otherHeapElement.additionalInfo))
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@ -132,7 +134,10 @@ public class HeapElement {
|
||||
public int hashCode() {
|
||||
int result = 0;
|
||||
result = 31 * result + (int) key;
|
||||
result = 31 * result + (additionalInfo != null ? additionalInfo.hashCode() : 0);
|
||||
result =
|
||||
31 *
|
||||
result +
|
||||
(additionalInfo != null ? additionalInfo.hashCode() : 0);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
@ -46,7 +46,7 @@ public class MaxHeap implements Heap {
|
||||
if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) {
|
||||
throw new IndexOutOfBoundsException("Index out of heap range");
|
||||
}
|
||||
|
||||
|
||||
return maxHeap.get(elementIndex - 1).getKey();
|
||||
}
|
||||
|
||||
@ -70,22 +70,30 @@ public class MaxHeap implements Heap {
|
||||
// than any of its children's
|
||||
private void toggleDown(int elementIndex) {
|
||||
double key = maxHeap.get(elementIndex - 1).getKey();
|
||||
boolean wrongOrder
|
||||
= (key < getElementKey(elementIndex * 2))
|
||||
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
|
||||
boolean wrongOrder =
|
||||
(key < getElementKey(elementIndex * 2)) ||
|
||||
(key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
|
||||
while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) {
|
||||
// Check whether it shall swap the element with its left child or its right one if any.
|
||||
if ((2 * elementIndex < maxHeap.size())
|
||||
&& (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) {
|
||||
if (
|
||||
(2 * elementIndex < maxHeap.size()) &&
|
||||
(
|
||||
getElementKey(elementIndex * 2 + 1) >
|
||||
getElementKey(elementIndex * 2)
|
||||
)
|
||||
) {
|
||||
swap(elementIndex, 2 * elementIndex + 1);
|
||||
elementIndex = 2 * elementIndex + 1;
|
||||
} else {
|
||||
swap(elementIndex, 2 * elementIndex);
|
||||
elementIndex = 2 * elementIndex;
|
||||
}
|
||||
wrongOrder
|
||||
= (key < getElementKey(elementIndex * 2))
|
||||
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
|
||||
wrongOrder =
|
||||
(key < getElementKey(elementIndex * 2)) ||
|
||||
(
|
||||
key <
|
||||
getElementKey(Math.min(elementIndex * 2, maxHeap.size()))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -103,9 +111,10 @@ public class MaxHeap implements Heap {
|
||||
|
||||
@Override
|
||||
public void deleteElement(int elementIndex) {
|
||||
if (maxHeap.isEmpty())
|
||||
try {
|
||||
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
|
||||
if (maxHeap.isEmpty()) try {
|
||||
throw new EmptyHeapException(
|
||||
"Attempt to delete an element from an empty heap"
|
||||
);
|
||||
} catch (EmptyHeapException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@ -116,13 +125,22 @@ public class MaxHeap implements Heap {
|
||||
maxHeap.set(elementIndex - 1, getElement(maxHeap.size()));
|
||||
maxHeap.remove(maxHeap.size());
|
||||
// Shall the new element be moved up...
|
||||
if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) {
|
||||
if (
|
||||
getElementKey(elementIndex) >
|
||||
getElementKey((int) Math.floor(elementIndex / 2.0))
|
||||
) {
|
||||
toggleUp(elementIndex);
|
||||
} // ... or down ?
|
||||
else if (((2 * elementIndex <= maxHeap.size())
|
||||
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))
|
||||
|| ((2 * elementIndex < maxHeap.size())
|
||||
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) {
|
||||
else if (
|
||||
(
|
||||
(2 * elementIndex <= maxHeap.size()) &&
|
||||
(getElementKey(elementIndex) < getElementKey(elementIndex * 2))
|
||||
) ||
|
||||
(
|
||||
(2 * elementIndex < maxHeap.size()) &&
|
||||
(getElementKey(elementIndex) < getElementKey(elementIndex * 2))
|
||||
)
|
||||
) {
|
||||
toggleDown(elementIndex);
|
||||
}
|
||||
}
|
||||
@ -132,7 +150,9 @@ public class MaxHeap implements Heap {
|
||||
try {
|
||||
return extractMax();
|
||||
} catch (Exception e) {
|
||||
throw new EmptyHeapException("Heap is empty. Error retrieving element");
|
||||
throw new EmptyHeapException(
|
||||
"Heap is empty. Error retrieving element"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -40,7 +40,7 @@ public class MinHeap implements Heap {
|
||||
if ((elementIndex <= 0) || (elementIndex > minHeap.size())) {
|
||||
throw new IndexOutOfBoundsException("Index out of heap range");
|
||||
}
|
||||
|
||||
|
||||
return minHeap.get(elementIndex - 1).getKey();
|
||||
}
|
||||
|
||||
@ -64,22 +64,30 @@ public class MinHeap implements Heap {
|
||||
// than any of its children's
|
||||
private void toggleDown(int elementIndex) {
|
||||
double key = minHeap.get(elementIndex - 1).getKey();
|
||||
boolean wrongOrder
|
||||
= (key > getElementKey(elementIndex * 2))
|
||||
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
|
||||
boolean wrongOrder =
|
||||
(key > getElementKey(elementIndex * 2)) ||
|
||||
(key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
|
||||
while ((2 * elementIndex <= minHeap.size()) && wrongOrder) {
|
||||
// Check whether it shall swap the element with its left child or its right one if any.
|
||||
if ((2 * elementIndex < minHeap.size())
|
||||
&& (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) {
|
||||
if (
|
||||
(2 * elementIndex < minHeap.size()) &&
|
||||
(
|
||||
getElementKey(elementIndex * 2 + 1) <
|
||||
getElementKey(elementIndex * 2)
|
||||
)
|
||||
) {
|
||||
swap(elementIndex, 2 * elementIndex + 1);
|
||||
elementIndex = 2 * elementIndex + 1;
|
||||
} else {
|
||||
swap(elementIndex, 2 * elementIndex);
|
||||
elementIndex = 2 * elementIndex;
|
||||
}
|
||||
wrongOrder
|
||||
= (key > getElementKey(elementIndex * 2))
|
||||
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
|
||||
wrongOrder =
|
||||
(key > getElementKey(elementIndex * 2)) ||
|
||||
(
|
||||
key >
|
||||
getElementKey(Math.min(elementIndex * 2, minHeap.size()))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -97,9 +105,10 @@ public class MinHeap implements Heap {
|
||||
|
||||
@Override
|
||||
public void deleteElement(int elementIndex) {
|
||||
if (minHeap.isEmpty())
|
||||
try {
|
||||
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
|
||||
if (minHeap.isEmpty()) try {
|
||||
throw new EmptyHeapException(
|
||||
"Attempt to delete an element from an empty heap"
|
||||
);
|
||||
} catch (EmptyHeapException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@ -110,13 +119,22 @@ public class MinHeap implements Heap {
|
||||
minHeap.set(elementIndex - 1, getElement(minHeap.size()));
|
||||
minHeap.remove(minHeap.size());
|
||||
// Shall the new element be moved up...
|
||||
if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) {
|
||||
if (
|
||||
getElementKey(elementIndex) <
|
||||
getElementKey((int) Math.floor(elementIndex / 2.0))
|
||||
) {
|
||||
toggleUp(elementIndex);
|
||||
} // ... or down ?
|
||||
else if (((2 * elementIndex <= minHeap.size())
|
||||
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))
|
||||
|| ((2 * elementIndex < minHeap.size())
|
||||
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) {
|
||||
else if (
|
||||
(
|
||||
(2 * elementIndex <= minHeap.size()) &&
|
||||
(getElementKey(elementIndex) > getElementKey(elementIndex * 2))
|
||||
) ||
|
||||
(
|
||||
(2 * elementIndex < minHeap.size()) &&
|
||||
(getElementKey(elementIndex) > getElementKey(elementIndex * 2))
|
||||
)
|
||||
) {
|
||||
toggleDown(elementIndex);
|
||||
}
|
||||
}
|
||||
@ -126,7 +144,9 @@ public class MinHeap implements Heap {
|
||||
try {
|
||||
return extractMin();
|
||||
} catch (Exception e) {
|
||||
throw new EmptyHeapException("Heap is empty. Error retrieving element");
|
||||
throw new EmptyHeapException(
|
||||
"Heap is empty. Error retrieving element"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -88,7 +88,10 @@ public class MinPriorityQueue {
|
||||
while (2 * k <= this.size || 2 * k + 1 <= this.size) {
|
||||
int minIndex;
|
||||
if (this.heap[2 * k] >= this.heap[k]) {
|
||||
if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) {
|
||||
if (
|
||||
2 * k + 1 <= this.size &&
|
||||
this.heap[2 * k + 1] >= this.heap[k]
|
||||
) {
|
||||
break;
|
||||
} else if (2 * k + 1 > this.size) {
|
||||
break;
|
||||
@ -97,8 +100,14 @@ public class MinPriorityQueue {
|
||||
if (2 * k + 1 > this.size) {
|
||||
minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k;
|
||||
} else {
|
||||
if (this.heap[k] > this.heap[2 * k] || this.heap[k] > this.heap[2 * k + 1]) {
|
||||
minIndex = this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1;
|
||||
if (
|
||||
this.heap[k] > this.heap[2 * k] ||
|
||||
this.heap[k] > this.heap[2 * k + 1]
|
||||
) {
|
||||
minIndex =
|
||||
this.heap[2 * k] < this.heap[2 * k + 1]
|
||||
? 2 * k
|
||||
: 2 * k + 1;
|
||||
} else {
|
||||
minIndex = k;
|
||||
}
|
||||
|
@ -38,7 +38,9 @@ public class CircleLinkedList<E> {
|
||||
public void append(E value) {
|
||||
if (value == null) {
|
||||
// we do not want to add null elements to the list.
|
||||
throw new NullPointerException("Cannot add null element to the list");
|
||||
throw new NullPointerException(
|
||||
"Cannot add null element to the list"
|
||||
);
|
||||
}
|
||||
// head.next points to the last element;
|
||||
if (tail == null) {
|
||||
@ -57,7 +59,7 @@ public class CircleLinkedList<E> {
|
||||
String s = "[ ";
|
||||
while (p != head) {
|
||||
s += p.value;
|
||||
if (p != tail){
|
||||
if (p != tail) {
|
||||
s += " , ";
|
||||
}
|
||||
p = p.next;
|
||||
@ -68,7 +70,9 @@ public class CircleLinkedList<E> {
|
||||
public E remove(int pos) {
|
||||
if (pos > size || pos < 0) {
|
||||
// catching errors
|
||||
throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
|
||||
throw new IndexOutOfBoundsException(
|
||||
"position cannot be greater than size or negative"
|
||||
);
|
||||
}
|
||||
// we need to keep track of the element before the element we want to remove we can see why
|
||||
// bellow.
|
||||
|
@ -33,15 +33,14 @@ public class CreateAndDetectLoop {
|
||||
}
|
||||
Node temp = head;
|
||||
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;
|
||||
count++;
|
||||
}
|
||||
|
||||
Node connectedPoint = temp;
|
||||
|
||||
while (temp.next != null) // Traverse remaining nodes
|
||||
{
|
||||
while (temp.next != null) { // Traverse remaining nodes
|
||||
temp = temp.next;
|
||||
}
|
||||
|
||||
|
@ -46,12 +46,9 @@ public class CursorLinkedList<T> {
|
||||
}
|
||||
|
||||
public void printList() {
|
||||
|
||||
if (head != -1) {
|
||||
|
||||
int start = head;
|
||||
while (start != -1) {
|
||||
|
||||
T element = cursorSpace[start].element;
|
||||
System.out.println(element.toString());
|
||||
start = cursorSpace[start].next;
|
||||
@ -64,7 +61,6 @@ public class CursorLinkedList<T> {
|
||||
* index of the [cursorSpace] array
|
||||
*/
|
||||
public int indexOf(T element) {
|
||||
|
||||
Objects.requireNonNull(element);
|
||||
Node<T> iterator = cursorSpace[head];
|
||||
for (int i = 0; i < count; i++) {
|
||||
@ -84,13 +80,10 @@ public class CursorLinkedList<T> {
|
||||
* @return
|
||||
*/
|
||||
public T get(int position) {
|
||||
|
||||
if (position >= 0 && position < count) {
|
||||
|
||||
int start = head;
|
||||
int counter = 0;
|
||||
while (start != -1) {
|
||||
|
||||
T element = cursorSpace[start].element;
|
||||
if (counter == position) {
|
||||
return element;
|
||||
@ -105,16 +98,13 @@ public class CursorLinkedList<T> {
|
||||
}
|
||||
|
||||
public void removeByIndex(int index) {
|
||||
|
||||
if (index >= 0 && index < count) {
|
||||
|
||||
T element = get(index);
|
||||
remove(element);
|
||||
}
|
||||
}
|
||||
|
||||
public void remove(T element) {
|
||||
|
||||
Objects.requireNonNull(element);
|
||||
|
||||
// case element is in the head
|
||||
@ -124,15 +114,14 @@ public class CursorLinkedList<T> {
|
||||
free(head);
|
||||
head = temp_next;
|
||||
} else { // otherwise cases
|
||||
|
||||
int prev_index = head;
|
||||
int current_index = cursorSpace[prev_index].next;
|
||||
|
||||
while (current_index != -1) {
|
||||
|
||||
T current_element = cursorSpace[current_index].element;
|
||||
if (current_element.equals(element)) {
|
||||
cursorSpace[prev_index].next = cursorSpace[current_index].next;
|
||||
cursorSpace[prev_index].next =
|
||||
cursorSpace[current_index].next;
|
||||
free(current_index);
|
||||
break;
|
||||
}
|
||||
@ -146,7 +135,6 @@ public class CursorLinkedList<T> {
|
||||
}
|
||||
|
||||
private void free(int index) {
|
||||
|
||||
Node os_node = cursorSpace[os];
|
||||
int os_next = os_node.next;
|
||||
cursorSpace[os].next = index;
|
||||
@ -155,7 +143,6 @@ public class CursorLinkedList<T> {
|
||||
}
|
||||
|
||||
public void append(T element) {
|
||||
|
||||
Objects.requireNonNull(element);
|
||||
int availableIndex = alloc();
|
||||
cursorSpace[availableIndex].element = element;
|
||||
@ -179,7 +166,6 @@ public class CursorLinkedList<T> {
|
||||
* @return the index of the next available node
|
||||
*/
|
||||
private int alloc() {
|
||||
|
||||
// 1- get the index at which the os is pointing
|
||||
int availableNodeIndex = cursorSpace[os].next;
|
||||
|
||||
|
@ -53,7 +53,7 @@ public class DoublyLinkedList {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
for (int i : array) {
|
||||
linkOperations.insertTail(i,this);
|
||||
linkOperations.insertTail(i, this);
|
||||
}
|
||||
size = array.length;
|
||||
}
|
||||
@ -136,13 +136,13 @@ class Link {
|
||||
public static void main(String args[]) {
|
||||
DoublyLinkedList myList = new DoublyLinkedList();
|
||||
LinkOperations linkOperations = new LinkOperations();
|
||||
linkOperations.insertHead(13,myList);
|
||||
linkOperations.insertHead(7,myList);
|
||||
linkOperations.insertHead(10,myList);
|
||||
linkOperations.insertHead(13, myList);
|
||||
linkOperations.insertHead(7, myList);
|
||||
linkOperations.insertHead(10, myList);
|
||||
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
|
||||
myList.displayBackwards();
|
||||
|
||||
linkOperations.insertTail(11,myList);
|
||||
linkOperations.insertTail(11, myList);
|
||||
myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) -->
|
||||
myList.displayBackwards();
|
||||
|
||||
@ -154,11 +154,11 @@ class Link {
|
||||
myList.display(); // <-- 10(head) <--> 13(tail) -->
|
||||
myList.displayBackwards();
|
||||
|
||||
linkOperations.insertOrdered(23,myList);
|
||||
linkOperations.insertOrdered(67,myList);
|
||||
linkOperations.insertOrdered(3,myList);
|
||||
linkOperations.insertOrdered(23, myList);
|
||||
linkOperations.insertOrdered(67, myList);
|
||||
linkOperations.insertOrdered(3, myList);
|
||||
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.displayBackwards();
|
||||
linkOperations.reverse(); // <-- 67(head) <--> 23 <--> 13 <--> 10 <--> 5 <--> 3(tail) -->
|
||||
@ -167,7 +167,7 @@ class Link {
|
||||
linkOperations.clearList();
|
||||
myList.display();
|
||||
myList.displayBackwards();
|
||||
linkOperations.insertHead(20,myList);
|
||||
linkOperations.insertHead(20, myList);
|
||||
myList.display();
|
||||
myList.displayBackwards();
|
||||
}
|
||||
@ -176,7 +176,8 @@ class Link {
|
||||
/*
|
||||
* This class implements the operations of the Link nodes.
|
||||
*/
|
||||
class LinkOperations{
|
||||
class LinkOperations {
|
||||
|
||||
/**
|
||||
* Head refers to the front of the list
|
||||
*/
|
||||
@ -196,10 +197,9 @@ class LinkOperations{
|
||||
*
|
||||
* @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
|
||||
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;
|
||||
} else {
|
||||
head.previous = newLink; // newLink <-- currenthead(head)
|
||||
@ -214,7 +214,7 @@ class LinkOperations{
|
||||
*
|
||||
* @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);
|
||||
newLink.next = null; // currentTail(tail) newlink -->
|
||||
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 index Index(from start) at which the element x to be inserted
|
||||
*/
|
||||
public void insertElementByIndex(int x, int index,DoublyLinkedList doublyLinkedList) {
|
||||
public void insertElementByIndex(
|
||||
int x,
|
||||
int index,
|
||||
DoublyLinkedList doublyLinkedList
|
||||
) {
|
||||
if (index > size) {
|
||||
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
|
||||
throw new IndexOutOfBoundsException(
|
||||
"Index: " + index + ", Size: " + size
|
||||
);
|
||||
}
|
||||
if (index == 0) {
|
||||
insertHead(x,doublyLinkedList);
|
||||
insertHead(x, doublyLinkedList);
|
||||
} else {
|
||||
if (index == size) {
|
||||
insertTail(x,doublyLinkedList);
|
||||
insertTail(x, doublyLinkedList);
|
||||
} else {
|
||||
Link newLink = new Link(x);
|
||||
Link previousLink = head; //
|
||||
@ -271,8 +277,7 @@ class LinkOperations{
|
||||
if (head == null) {
|
||||
tail = null;
|
||||
} else {
|
||||
head.previous
|
||||
= null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
|
||||
head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
|
||||
}
|
||||
--size;
|
||||
return temp;
|
||||
@ -309,7 +314,9 @@ class LinkOperations{
|
||||
if (current != tail) {
|
||||
current = current.next;
|
||||
} else { // If we reach the tail and the element is still not found
|
||||
throw new RuntimeException("The element to be deleted does not exist!");
|
||||
throw new RuntimeException(
|
||||
"The element to be deleted does not exist!"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -329,18 +336,17 @@ class LinkOperations{
|
||||
*
|
||||
* @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 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;
|
||||
}
|
||||
|
||||
if (current == head) {
|
||||
insertHead(x,doublyLinkedList);
|
||||
insertHead(x, doublyLinkedList);
|
||||
} else if (current == null) {
|
||||
insertTail(x,doublyLinkedList);
|
||||
insertTail(x, doublyLinkedList);
|
||||
} else { // Before: 1 <--> 2(current) <--> 3
|
||||
newLink.previous = current.previous; // 1 <-- newLink
|
||||
current.previous.next = newLink; // 1 <--> newLink
|
||||
@ -372,8 +378,7 @@ class LinkOperations{
|
||||
while (linkOne.next != null) { // list is present
|
||||
Link linkTwo = linkOne.next; // second link for comparison
|
||||
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
|
||||
}
|
||||
linkTwo = linkTwo.next; // go to next link
|
||||
@ -416,5 +421,4 @@ class LinkOperations{
|
||||
tail = null;
|
||||
size = 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -36,7 +36,11 @@ public class MergeSortedArrayList {
|
||||
* @param listB the second list to merge
|
||||
* @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;
|
||||
/* the index of listA */
|
||||
int pb = 0;
|
||||
|
@ -12,7 +12,9 @@ public class MergeSortedSinglyLinkedList extends SinglyLinkedList {
|
||||
}
|
||||
assert listA.toString().equals("2->4->6->8->10");
|
||||
assert listB.toString().equals("1->3->5->7->9");
|
||||
assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10");
|
||||
assert merge(listA, listB)
|
||||
.toString()
|
||||
.equals("1->2->3->4->5->6->7->8->9->10");
|
||||
}
|
||||
|
||||
/**
|
||||
@ -22,7 +24,10 @@ public class MergeSortedSinglyLinkedList extends SinglyLinkedList {
|
||||
* @param listB the second sored list
|
||||
* @return merged sorted list
|
||||
*/
|
||||
public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) {
|
||||
public static SinglyLinkedList merge(
|
||||
SinglyLinkedList listA,
|
||||
SinglyLinkedList listB
|
||||
) {
|
||||
Node headA = listA.getHead();
|
||||
Node headB = listB.getHead();
|
||||
|
||||
|
@ -18,7 +18,9 @@ public class Merge_K_SortedLinkedlist {
|
||||
*/
|
||||
Node mergeKList(Node[] a, int N) {
|
||||
// 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
|
||||
min.addAll(Arrays.asList(a).subList(0, N));
|
||||
@ -30,7 +32,6 @@ public class Merge_K_SortedLinkedlist {
|
||||
|
||||
// merging LinkedList
|
||||
while (!min.isEmpty()) {
|
||||
|
||||
Node temp = min.poll();
|
||||
curr.next = temp;
|
||||
curr = temp;
|
||||
|
@ -22,7 +22,6 @@
|
||||
* Step 7 : STOP
|
||||
*/
|
||||
|
||||
|
||||
package com.thealgorithms.datastructures.lists;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@ -30,11 +29,13 @@ import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
public class RandomNode {
|
||||
|
||||
private List<Integer> list;
|
||||
private int size;
|
||||
private static Random rand = new Random();
|
||||
|
||||
static class ListNode {
|
||||
|
||||
int val;
|
||||
ListNode next;
|
||||
|
||||
@ -74,8 +75,6 @@ public class RandomNode {
|
||||
System.out.println("Random Node : " + randomNum);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* OUTPUT :
|
||||
* First output :
|
||||
@ -87,7 +86,6 @@ public class RandomNode {
|
||||
* Time Complexity : O(n)
|
||||
* Auxiliary Space Complexity : O(1)
|
||||
*/
|
||||
|
||||
/** Time Complexity : O(n)
|
||||
* Auxiliary Space Complexity : O(1)
|
||||
*/
|
||||
|
@ -23,7 +23,10 @@ public class SearchSinglyLinkedListRecursion extends SinglyLinkedList {
|
||||
* {@code false}.
|
||||
*/
|
||||
private boolean searchRecursion(Node node, int key) {
|
||||
return node != null && (node.value == key || searchRecursion(node.next, key));
|
||||
return (
|
||||
node != null &&
|
||||
(node.value == key || searchRecursion(node.next, key))
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -5,7 +5,7 @@ import java.util.StringJoiner;
|
||||
/**
|
||||
* 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
|
||||
@ -56,42 +56,40 @@ public class SinglyLinkedList extends Node{
|
||||
|
||||
/**
|
||||
* Swaps nodes of two given values a and b.
|
||||
*
|
||||
*
|
||||
*/
|
||||
public void swapNodes(int valueFirst, int valueSecond) {
|
||||
if(valueFirst == valueSecond){
|
||||
if (valueFirst == valueSecond) {
|
||||
return;
|
||||
}
|
||||
Node previousA = null ,currentA = head;
|
||||
while(currentA != null && currentA.value != valueFirst){
|
||||
Node previousA = null, currentA = head;
|
||||
while (currentA != null && currentA.value != valueFirst) {
|
||||
previousA = currentA;
|
||||
currentA = currentA.next;
|
||||
}
|
||||
|
||||
Node previousB = null ,currentB = head;
|
||||
while(currentB != null && currentB.value != valueSecond){
|
||||
Node previousB = null, currentB = head;
|
||||
while (currentB != null && currentB.value != valueSecond) {
|
||||
previousB = currentB;
|
||||
currentB = currentB.next;
|
||||
}
|
||||
/** If either of 'a' or 'b' is not present, then return */
|
||||
if(currentA == null || currentB == null){
|
||||
if (currentA == null || currentB == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If 'a' is not head node of list
|
||||
if(previousA != null){
|
||||
if (previousA != null) {
|
||||
previousA.next = currentB;
|
||||
}
|
||||
else{
|
||||
} else {
|
||||
// make 'b' as the new head
|
||||
head = currentB;
|
||||
}
|
||||
|
||||
// If 'b' is not head node of list
|
||||
if(previousB != null){
|
||||
if (previousB != null) {
|
||||
previousB.next = currentA;
|
||||
}
|
||||
else{
|
||||
} else {
|
||||
// Make 'a' as new head
|
||||
head = currentA;
|
||||
}
|
||||
@ -108,7 +106,7 @@ public class SinglyLinkedList extends Node{
|
||||
*/
|
||||
Node reverseList(Node node) {
|
||||
Node prevNode = head;
|
||||
while(prevNode.next!=node){
|
||||
while (prevNode.next != node) {
|
||||
prevNode = prevNode.next;
|
||||
}
|
||||
Node prev = null, curr = node, next;
|
||||
@ -216,7 +214,6 @@ public class SinglyLinkedList extends Node{
|
||||
}
|
||||
|
||||
public void deleteDuplicates() {
|
||||
|
||||
Node pred = head;
|
||||
// predecessor = the node
|
||||
// having sublist of its duplicates
|
||||
@ -226,13 +223,14 @@ public class SinglyLinkedList extends Node{
|
||||
// skip all duplicates
|
||||
if (newHead.next != null && newHead.value == newHead.next.value) {
|
||||
// move till the end of duplicates sublist
|
||||
while (newHead.next != null && newHead.value == newHead.next.value) {
|
||||
while (
|
||||
newHead.next != null && newHead.value == newHead.next.value
|
||||
) {
|
||||
newHead = newHead.next;
|
||||
}
|
||||
// skip all duplicates
|
||||
pred.next = newHead.next;
|
||||
newHead = null;
|
||||
|
||||
// otherwise, move predecessor
|
||||
}
|
||||
// move forward
|
||||
@ -301,7 +299,6 @@ public class SinglyLinkedList extends Node{
|
||||
newNode.next = cur.next;
|
||||
cur.next = newNode;
|
||||
size++;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@ -375,6 +372,7 @@ public class SinglyLinkedList extends Node{
|
||||
throw new IndexOutOfBoundsException(position + "");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
@ -393,10 +391,15 @@ public class SinglyLinkedList extends Node{
|
||||
assert list.toString().equals("10->7->5->3->1");
|
||||
System.out.println(list.toString());
|
||||
/* Test search function */
|
||||
assert list.search(10) && list.search(5) && list.search(1) && !list.search(100);
|
||||
assert list.search(10) &&
|
||||
list.search(5) &&
|
||||
list.search(1) &&
|
||||
!list.search(100);
|
||||
|
||||
/* Test get function */
|
||||
assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1;
|
||||
assert list.getNth(0) == 10 &&
|
||||
list.getNth(2) == 5 &&
|
||||
list.getNth(4) == 1;
|
||||
|
||||
/* Test delete function */
|
||||
list.deleteHead();
|
||||
@ -419,13 +422,14 @@ public class SinglyLinkedList extends Node{
|
||||
}
|
||||
|
||||
SinglyLinkedList instance = new SinglyLinkedList();
|
||||
Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4)))));
|
||||
Node head = new Node(
|
||||
0,
|
||||
new Node(2, new Node(3, new Node(3, new Node(4))))
|
||||
);
|
||||
instance.setHead(head);
|
||||
instance.deleteDuplicates();
|
||||
instance.print();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@ -444,8 +448,7 @@ class Node {
|
||||
*/
|
||||
Node next;
|
||||
|
||||
Node() {
|
||||
}
|
||||
Node() {}
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
@ -466,5 +469,4 @@ class Node {
|
||||
this.value = value;
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -189,23 +189,25 @@ public class SkipList<E extends Comparable<E>> {
|
||||
}
|
||||
|
||||
Collections.reverse(layers);
|
||||
String result = layers.stream()
|
||||
.map(layer -> {
|
||||
StringBuilder acc = new StringBuilder();
|
||||
for (boolean b : layer) {
|
||||
if (b) {
|
||||
acc.append("[ ]");
|
||||
} else {
|
||||
acc.append("---");
|
||||
}
|
||||
acc.append(" ");
|
||||
String result = layers
|
||||
.stream()
|
||||
.map(layer -> {
|
||||
StringBuilder acc = new StringBuilder();
|
||||
for (boolean b : layer) {
|
||||
if (b) {
|
||||
acc.append("[ ]");
|
||||
} else {
|
||||
acc.append("---");
|
||||
}
|
||||
return acc.toString();
|
||||
})
|
||||
.collect(Collectors.joining("\n"));
|
||||
String positions = IntStream.range(0, sizeWithHeader - 1)
|
||||
.mapToObj(i -> String.format("%3d", i))
|
||||
.collect(Collectors.joining(" "));
|
||||
acc.append(" ");
|
||||
}
|
||||
return acc.toString();
|
||||
})
|
||||
.collect(Collectors.joining("\n"));
|
||||
String positions = IntStream
|
||||
.range(0, sizeWithHeader - 1)
|
||||
.mapToObj(i -> String.format("%3d", i))
|
||||
.collect(Collectors.joining(" "));
|
||||
|
||||
return result + String.format("%n H %s%n", positions);
|
||||
}
|
||||
@ -296,14 +298,18 @@ public class SkipList<E extends Comparable<E>> {
|
||||
|
||||
public BernoulliHeightStrategy(double probability) {
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int height(int expectedSize) {
|
||||
long height = Math.round(Math.log10(expectedSize) / Math.log10(1 / probability));
|
||||
long height = Math.round(
|
||||
Math.log10(expectedSize) / Math.log10(1 / probability)
|
||||
);
|
||||
if (height > Integer.MAX_VALUE) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
@ -69,7 +69,6 @@ public class CircularQueue {
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public int peek() {
|
||||
@ -86,7 +85,6 @@ public class CircularQueue {
|
||||
System.out.println("The Queue is deleted!");
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
CircularQueue cq = new CircularQueue(5);
|
||||
System.out.println(cq.isEmpty());
|
||||
@ -110,6 +108,5 @@ public class CircularQueue {
|
||||
System.out.println(cq.peek());
|
||||
System.out.println(cq.peek());
|
||||
cq.deleteQueue();
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -121,8 +121,7 @@ public class PriorityQueues {
|
||||
// [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top
|
||||
|
||||
for (int i = 3; i >= 0; i--) {
|
||||
System.out.print(
|
||||
myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2]
|
||||
System.out.print(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
|
||||
}
|
||||
|
@ -28,13 +28,16 @@ class BalancedBrackets {
|
||||
*/
|
||||
public static boolean isPaired(char leftBracket, char rightBracket) {
|
||||
char[][] pairedBrackets = {
|
||||
{'(', ')'},
|
||||
{'[', ']'},
|
||||
{'{', '}'},
|
||||
{'<', '>'}
|
||||
{ '(', ')' },
|
||||
{ '[', ']' },
|
||||
{ '{', '}' },
|
||||
{ '<', '>' },
|
||||
};
|
||||
for (char[] pairedBracket : pairedBrackets) {
|
||||
if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) {
|
||||
if (
|
||||
pairedBracket[0] == leftBracket &&
|
||||
pairedBracket[1] == rightBracket
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -63,7 +66,10 @@ class BalancedBrackets {
|
||||
case ')':
|
||||
case ']':
|
||||
case '}':
|
||||
if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) {
|
||||
if (
|
||||
bracketsStack.isEmpty() ||
|
||||
!isPaired(bracketsStack.pop(), bracket)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
|
@ -8,6 +8,7 @@ package com.thealgorithms.datastructures.stacks;
|
||||
import java.util.*;
|
||||
|
||||
public class CalculateMaxOfMin {
|
||||
|
||||
public static int calculateMaxOfMin(int[] a) {
|
||||
int n = a.length;
|
||||
int[] ans = new int[n];
|
||||
@ -34,4 +35,4 @@ public class CalculateMaxOfMin {
|
||||
/**
|
||||
* Given an integer array. The task is to find the maximum of the minimum of the
|
||||
* given array
|
||||
*/
|
||||
*/
|
||||
|
@ -24,10 +24,30 @@ public class DecimalToAnyUsingStack {
|
||||
private static String convert(int number, int radix) {
|
||||
if (radix < 2 || radix > 16) {
|
||||
throw new ArithmeticException(
|
||||
String.format("Invalid input -> number:%d,radius:%d", number, radix));
|
||||
String.format(
|
||||
"Invalid input -> number:%d,radius:%d",
|
||||
number,
|
||||
radix
|
||||
)
|
||||
);
|
||||
}
|
||||
char[] tables = {
|
||||
'0', '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<>();
|
||||
do {
|
||||
|
@ -2,7 +2,7 @@ package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
// 1. You are given a string exp representing an expression.
|
||||
// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each other.
|
||||
// 3. But, some of the pair of brackets maybe extra/needless.
|
||||
// 3. But, some of the pair of brackets maybe extra/needless.
|
||||
// 4. You are required to print true if you detect extra brackets and false otherwise.
|
||||
// e.g.'
|
||||
// ((a + b) + (c + d)) -> false
|
||||
@ -25,7 +25,6 @@ public class DuplicateBrackets {
|
||||
}
|
||||
st.pop();
|
||||
}
|
||||
|
||||
} else {
|
||||
st.push(ch);
|
||||
}
|
||||
@ -40,5 +39,4 @@ public class DuplicateBrackets {
|
||||
System.out.println(check(str));
|
||||
sc.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -10,7 +10,8 @@ public class InfixToPostfix {
|
||||
assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6"));
|
||||
}
|
||||
|
||||
public static String infix2PostFix(String infixExpression) throws Exception {
|
||||
public static String infix2PostFix(String infixExpression)
|
||||
throws Exception {
|
||||
if (!BalancedBrackets.isBalanced(infixExpression)) {
|
||||
throw new Exception("invalid expression");
|
||||
}
|
||||
@ -27,7 +28,10 @@ public class InfixToPostfix {
|
||||
}
|
||||
stack.pop();
|
||||
} else {
|
||||
while (!stack.isEmpty() && precedence(element) <= precedence(stack.peek())) {
|
||||
while (
|
||||
!stack.isEmpty() &&
|
||||
precedence(element) <= precedence(stack.peek())
|
||||
) {
|
||||
output.append(stack.pop());
|
||||
}
|
||||
stack.push(element);
|
||||
|
@ -1,33 +1,36 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author mohd rameez github.com/rameez471
|
||||
*/
|
||||
|
||||
public class LargestRectangle {
|
||||
public static String largestRectanglehistogram(int[] heights) {
|
||||
int n = heights.length, maxArea = 0;
|
||||
Stack<int[]> st = new Stack<>();
|
||||
for(int i=0;i<n;i++) {
|
||||
int start = i;
|
||||
while(!st.isEmpty() && st.peek()[1] > heights[i]) {
|
||||
int[] tmp = st.pop();
|
||||
maxArea = Math.max(maxArea, tmp[1]*(i - tmp[0]));
|
||||
start = tmp[0];
|
||||
}
|
||||
st.push(new int[]{start, heights[i]});
|
||||
}
|
||||
while(!st.isEmpty()) {
|
||||
int[] tmp = st.pop();
|
||||
maxArea = Math.max(maxArea, tmp[1]*(n-tmp[0]));
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author mohd rameez github.com/rameez471
|
||||
*/
|
||||
|
||||
public class LargestRectangle {
|
||||
|
||||
public static String largestRectanglehistogram(int[] heights) {
|
||||
int n = heights.length, maxArea = 0;
|
||||
Stack<int[]> st = new Stack<>();
|
||||
for (int i = 0; i < n; i++) {
|
||||
int start = i;
|
||||
while (!st.isEmpty() && st.peek()[1] > heights[i]) {
|
||||
int[] tmp = st.pop();
|
||||
maxArea = Math.max(maxArea, tmp[1] * (i - tmp[0]));
|
||||
start = tmp[0];
|
||||
}
|
||||
st.push(new int[] { start, heights[i] });
|
||||
}
|
||||
while (!st.isEmpty()) {
|
||||
int[] tmp = st.pop();
|
||||
maxArea = Math.max(maxArea, tmp[1] * (n - tmp[0]));
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
@ -97,10 +97,9 @@ public class MaximumMinimumWindow {
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
int[] arr = new int[]{10, 20, 30, 50, 10, 70, 30};
|
||||
int[] target = new int[]{70, 30, 20, 10, 10, 10, 10};
|
||||
int[] arr = new int[] { 10, 20, 30, 50, 10, 70, 30 };
|
||||
int[] target = new int[] { 70, 30, 20, 10, 10, 10, 10 };
|
||||
int[] res = calculateMaxOfMin(arr, arr.length);
|
||||
assert Arrays.equals(target, res);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,6 +1,8 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Stack;
|
||||
|
||||
/*
|
||||
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
|
||||
@ -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.
|
||||
*/
|
||||
|
||||
|
||||
public class NextGraterElement {
|
||||
|
||||
public static int[] findNextGreaterElements(int[] array) {
|
||||
|
||||
public static int[] findNextGreaterElements(int[] array) {
|
||||
if (array == null) {
|
||||
return array;
|
||||
}
|
||||
@ -60,8 +60,7 @@ public class NextGraterElement {
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
public static void main(String[] args) {
|
||||
int[] input = { 2, 7, 3, 5, 4, 6, 8 };
|
||||
int[] result = findNextGreaterElements(input);
|
||||
System.out.println(Arrays.toString(result));
|
||||
|
@ -1,8 +1,8 @@
|
||||
package com.thealgorithms.datastructures.stacks;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Stack;
|
||||
|
||||
|
||||
/*
|
||||
Given an array "input" you need to print the first smaller element for each element to the left side of an array.
|
||||
For a given element x of an array, the Next Smaller element of that element is the
|
||||
@ -38,8 +38,8 @@ import java.util.Stack;
|
||||
*/
|
||||
|
||||
public class NextSmallerElement {
|
||||
public static int[] findNextSmallerElements(int[] array)
|
||||
{
|
||||
|
||||
public static int[] findNextSmallerElements(int[] array) {
|
||||
// base case
|
||||
if (array == null) {
|
||||
return array;
|
||||
@ -60,8 +60,7 @@ public class NextSmallerElement {
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
public static void main(String[] args) {
|
||||
int[] input = { 2, 7, 3, 5, 4, 6, 8 };
|
||||
int[] result = findNextSmallerElements(input);
|
||||
System.out.println(Arrays.toString(result));
|
||||
|
@ -50,8 +50,7 @@ public class NodeStack<Item> {
|
||||
/**
|
||||
* Constructors for the NodeStack.
|
||||
*/
|
||||
public NodeStack() {
|
||||
}
|
||||
public NodeStack() {}
|
||||
|
||||
private NodeStack(Item item) {
|
||||
this.data = item;
|
||||
@ -63,7 +62,6 @@ public class NodeStack<Item> {
|
||||
* @param item : value to be put on the stack.
|
||||
*/
|
||||
public void push(Item item) {
|
||||
|
||||
NodeStack<Item> newNs = new NodeStack<Item>(item);
|
||||
|
||||
if (this.isEmpty()) {
|
||||
@ -85,7 +83,6 @@ public class NodeStack<Item> {
|
||||
* @return item : value that is returned.
|
||||
*/
|
||||
public Item pop() {
|
||||
|
||||
Item item = (Item) NodeStack.head.getData();
|
||||
|
||||
NodeStack.head.setHead(NodeStack.head.getPrevious());
|
||||
|
@ -18,11 +18,8 @@ import java.util.Stack;
|
||||
|
||||
public class PostfixToInfix {
|
||||
|
||||
|
||||
public static boolean isOperator(char token)
|
||||
{
|
||||
switch(token)
|
||||
{
|
||||
public static boolean isOperator(char token) {
|
||||
switch (token) {
|
||||
case '+':
|
||||
case '-':
|
||||
case '/':
|
||||
@ -34,43 +31,31 @@ public class PostfixToInfix {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public static boolean isValidPostfixExpression(String postfix)
|
||||
{
|
||||
public static boolean isValidPostfixExpression(String postfix) {
|
||||
/* 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 */
|
||||
if(isOperator(postfix.charAt(0))) return false;
|
||||
if(isOperator(postfix.charAt(1))) return false;
|
||||
|
||||
if (isOperator(postfix.charAt(0))) return false;
|
||||
if (isOperator(postfix.charAt(1))) return false;
|
||||
|
||||
int operandCount = 0;
|
||||
int operatorCount = 0;
|
||||
|
||||
|
||||
/* 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);
|
||||
|
||||
if(isOperator(token))
|
||||
{
|
||||
if (isOperator(token)) {
|
||||
operatorCount++;
|
||||
if(operatorCount >= operandCount) return false;
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
if(operatorCount == 0)
|
||||
{
|
||||
if (operatorCount >= operandCount) return false;
|
||||
} else {
|
||||
if (operatorCount == 0) {
|
||||
operandCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(operandCount != operatorCount + 1) return false;
|
||||
|
||||
if (operandCount != operatorCount + 1) return false;
|
||||
|
||||
/* Operand count is set to 2 because:-
|
||||
*
|
||||
@ -81,7 +66,6 @@ public class PostfixToInfix {
|
||||
*/
|
||||
operandCount = 2;
|
||||
|
||||
|
||||
/* Reset operator count */
|
||||
operatorCount = 0;
|
||||
}
|
||||
@ -90,17 +74,13 @@ public class PostfixToInfix {
|
||||
return (operandCount == operatorCount + 1);
|
||||
}
|
||||
|
||||
|
||||
public static String getPostfixToInfix(String postfix)
|
||||
{
|
||||
public static String getPostfixToInfix(String postfix) {
|
||||
String infix = "";
|
||||
|
||||
if(postfix.isEmpty()) return infix;
|
||||
|
||||
if (postfix.isEmpty()) return infix;
|
||||
|
||||
/* Validate Postfix expression before proceeding with the Infix conversion */
|
||||
if(!isValidPostfixExpression(postfix))
|
||||
{
|
||||
if (!isValidPostfixExpression(postfix)) {
|
||||
throw new IllegalArgumentException("Invalid Postfix Expression");
|
||||
}
|
||||
|
||||
@ -110,13 +90,10 @@ public class PostfixToInfix {
|
||||
String operandA, operandB;
|
||||
char operator;
|
||||
|
||||
|
||||
for(int index = 0; index < postfix.length(); index++)
|
||||
{
|
||||
for (int index = 0; index < postfix.length(); index++) {
|
||||
char token = postfix.charAt(index);
|
||||
|
||||
if(!isOperator(token))
|
||||
{
|
||||
if (!isOperator(token)) {
|
||||
stack.push(Character.toString(token));
|
||||
continue;
|
||||
}
|
||||
@ -141,13 +118,12 @@ public class PostfixToInfix {
|
||||
return infix;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String args[])
|
||||
{
|
||||
public static void main(String args[]) {
|
||||
assert getPostfixToInfix("ABC+/").equals("(A/(B+C))");
|
||||
assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))");
|
||||
assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)");
|
||||
assert getPostfixToInfix("ABCDE^*/-").equals("(A-(B/(C*(D^E))))");
|
||||
assert getPostfixToInfix("AB+CD^/E*FGH+-^").equals("((((A+B)/(C^D))*E)^(F-(G+H)))");
|
||||
assert getPostfixToInfix("AB+CD^/E*FGH+-^")
|
||||
.equals("((((A+B)/(C^D))*E)^(F-(G+H)))");
|
||||
}
|
||||
}
|
||||
|
@ -11,9 +11,10 @@ import java.util.Stack;
|
||||
public class ReverseStack {
|
||||
|
||||
public static void main(String args[]) {
|
||||
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("Enter the number of elements you wish to insert in the stack");
|
||||
System.out.println(
|
||||
"Enter the number of elements you wish to insert in the stack"
|
||||
);
|
||||
int n = sc.nextInt();
|
||||
int i;
|
||||
Stack<Integer> stack = new Stack<Integer>();
|
||||
@ -28,7 +29,6 @@ public class ReverseStack {
|
||||
System.out.print(stack.peek() + ",");
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void reverseStack(Stack<Integer> stack) {
|
||||
@ -46,11 +46,9 @@ public class ReverseStack {
|
||||
|
||||
//Insert the topmost element to the bottom of the stack
|
||||
insertAtBottom(stack, element);
|
||||
|
||||
}
|
||||
|
||||
private static void insertAtBottom(Stack<Integer> stack, int element) {
|
||||
|
||||
if (stack.isEmpty()) {
|
||||
//When stack is empty, insert the element so it will be present at the bottom of the stack
|
||||
stack.push(element);
|
||||
@ -66,5 +64,4 @@ public class ReverseStack {
|
||||
|
||||
stack.push(ele);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -9,7 +9,6 @@ import java.util.NoSuchElementException;
|
||||
class StackOfLinkedList {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
LinkedListStack stack = new LinkedListStack();
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
@ -24,7 +23,9 @@ class StackOfLinkedList {
|
||||
assert stack.pop() == 5;
|
||||
assert stack.pop() == 4;
|
||||
|
||||
System.out.println("Top element of stack currently is: " + stack.peek());
|
||||
System.out.println(
|
||||
"Top element of stack currently is: " + stack.peek()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -119,7 +120,9 @@ class LinkedListStack {
|
||||
builder.append(cur.data).append("->");
|
||||
cur = cur.next;
|
||||
}
|
||||
return builder.replace(builder.length() - 2, builder.length(), "").toString();
|
||||
return builder
|
||||
.replace(builder.length() - 2, builder.length(), "")
|
||||
.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -1,4 +1,3 @@
|
||||
|
||||
package com.thealgorithms.datastructures.trees;
|
||||
|
||||
/*
|
||||
@ -27,111 +26,106 @@ AVLTree tree=new AVLTree();
|
||||
|
||||
*/
|
||||
|
||||
|
||||
|
||||
public class AVLSimple {
|
||||
private class Node{
|
||||
int data;
|
||||
int height;
|
||||
Node left;
|
||||
Node right;
|
||||
Node(int data){
|
||||
this.data=data;
|
||||
this.height=1;
|
||||
}
|
||||
|
||||
}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
|
||||
}
|
||||
|
||||
private class Node {
|
||||
|
||||
int data;
|
||||
int height;
|
||||
Node left;
|
||||
Node right;
|
||||
|
||||
Node(int data) {
|
||||
this.data = data;
|
||||
this.height = 1;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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
Loading…
Reference in New Issue
Block a user