Format code with prettier (#3375)

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

View File

@ -22,7 +22,9 @@ public class IIRFilter {
*/
public IIRFilter(int order) throws IllegalArgumentException {
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];

View File

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

View File

@ -15,9 +15,7 @@ public class FloodFill {
*/
public static int getPixel(int[][] image, int x, int y) {
return image[x][y];
}
/**
@ -28,12 +26,9 @@ public class FloodFill {
* @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;
}
/**
* Fill the 2D image with new color
*
@ -44,8 +39,13 @@ 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;
@ -63,7 +63,5 @@ public class FloodFill {
floodFill(image, x - 1, y + 1, newColor, oldColor);
floodFill(image, x + 1, y + 1, newColor, oldColor);
floodFill(image, x - 1, y - 1, newColor, oldColor);
}
}

View File

@ -25,8 +25,17 @@ 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 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
@ -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[]>() {
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;

View File

@ -51,7 +51,9 @@ public class MazeRecursion {
setWay2(map2, 1, 1);
// Print out the new map1, with the ball footprint
System.out.println("After the ball goes through the map1show the current map1 condition");
System.out.println(
"After the ball goes through the map1show the current map1 condition"
);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map[i][j] + " ");
@ -60,7 +62,9 @@ public class MazeRecursion {
}
// Print out the new map2, with the ball footprint
System.out.println("After the ball goes through the map2show the current map2 condition");
System.out.println(
"After the ball goes through the map2show the current map2 condition"
);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map2[i][j] + " ");
@ -69,8 +73,6 @@ public class MazeRecursion {
}
}
// Using recursive path finding to help the ball find its way in the maze
// Description
// 1. map (means the maze)
@ -114,13 +116,11 @@ public class MazeRecursion {
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
@ -146,13 +146,10 @@ public class MazeRecursion {
map[i][j] = 3;
return false;
}
} else { // if the map[i][j] != 0 , it will probably be 1,2,3, return false because the
// ball cannot hit the wall, cannot go to the path that has gone though before,
// and cannot head to deadend.
return false;
}
}
}

View File

@ -47,7 +47,14 @@ public class NQueens {
List<List<String>> arrangements = new ArrayList<List<String>>();
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) {

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -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,6 +82,7 @@ public class Caesar {
private static boolean IsSmallLatinLetter(char c) {
return c >= 'a' && c <= 'z';
}
/**
* @return string array which contains all the possible decoded combination.
*/
@ -117,19 +109,27 @@ 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]);
System.out.println(
"FOR SHIFT " +
String.valueOf(i) +
" decoded message is " +
listOfAllTheAnswers[i]
);
}
default:
System.out.println("default case");

View File

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

View File

@ -157,7 +157,9 @@ public class HillCipher {
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;
}
}

View File

@ -20,7 +20,7 @@ public class Polybius {
/* 1 */{ 'F', 'G', 'H', 'I', 'J' },
/* 2 */{ 'K', 'L', 'M', 'N', 'O' },
/* 3 */{ 'P', 'Q', 'R', 'S', 'T' },
/* 4 */ {'V', 'W', 'X', 'Y', 'Z'}
/* 4 */{ 'V', 'W', 'X', 'Y', 'Z' },
};
private static String findLocationByCharacter(final char character) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,6 +4,7 @@ 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
@ -26,5 +27,4 @@ public class A5Cipher {
public void resetCounter() {
keyStreamGenerator.reInitialize();
}
}

View File

@ -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;
@ -30,8 +31,11 @@ public class A5KeyStreamGenerator extends CompositeLFSR {
}
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) {

View File

@ -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<>();
/**
@ -18,8 +19,7 @@ public abstract class CompositeLFSR implements BaseLFSR {
boolean result = false;
for (var register : registers) {
result ^= register.getLastBit();
if ( register.getClockBit() == majorityBit )
register.clock();
if (register.getClockBit() == majorityBit) register.clock();
}
return result;
}
@ -29,7 +29,12 @@ public abstract class CompositeLFSR implements BaseLFSR {
bitCount.put(false, 0);
bitCount.put(true, 0);
registers.forEach( lfsr -> bitCount.put( lfsr.getClockBit(), bitCount.get( lfsr.getClockBit() ) + 1 ) );
registers.forEach(lfsr ->
bitCount.put(
lfsr.getClockBit(),
bitCount.get(lfsr.getClockBit()) + 1
)
);
return bitCount.get(false) <= bitCount.get(true);
}
}

View File

@ -3,6 +3,7 @@ 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;

View File

@ -7,6 +7,7 @@ package com.thealgorithms.ciphers.a5;
import java.util.BitSet;
public class Utils {
public static boolean increment(BitSet bits, int size) {
int i = size - 1;
while (i >= 0 && bits.get(i)) {

View File

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

View File

@ -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 .

View File

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

View File

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

View File

@ -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.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -26,23 +26,62 @@ public class RgbHsvConversion {
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(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;
@ -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;

View File

@ -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 = ' ';

View File

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

View File

@ -1,6 +1,5 @@
package com.thealgorithms.datastructures.bloomfilter;
import java.util.BitSet;
public class BloomFilter<T> {
@ -59,5 +58,4 @@ public class BloomFilter<T> {
return number;
}
}
}

View File

@ -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++;

View File

@ -10,6 +10,7 @@ import java.util.Map;
public class LFUCache<K, V> {
private class Node {
private K key;
private V value;
private int frequency;
@ -70,8 +71,7 @@ public class LFUCache<K,V> {
node.frequency += 1;
removeNode(node);
addNodeWithUpdatedFrequency(node);
}
else {
} else {
if (map.size() >= capacity) {
map.remove(this.head.key);
removeNode(head);
@ -97,16 +97,14 @@ public class LFUCache<K,V> {
temp.previous = node;
this.head = node;
break;
}
else {
} else {
node.next = temp;
node.previous = temp.previous;
temp.previous.next = node;
node.previous = temp.previous;
break;
}
}
else {
} else {
temp = temp.next;
if (temp == null) {
tail.next = node;
@ -117,8 +115,7 @@ public class LFUCache<K,V> {
}
}
}
}
else {
} else {
tail = node;
head = tail;
}
@ -132,15 +129,13 @@ public class LFUCache<K,V> {
private void removeNode(Node node) {
if (node.previous != null) {
node.previous.next = node.next;
}
else {
} else {
this.head = node.next;
}
if (node.next != null) {
node.next.previous = node.previous;
}
else {
} else {
this.tail = node.previous;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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(" ");

View File

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

View File

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

View File

@ -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,7 +60,8 @@ class dijkstras {
}
public static void main(String[] args) {
int graph[][] = new int[][]{{0, 4, 0, 0, 0, 0, 0, 8, 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 },
@ -64,13 +69,12 @@ class dijkstras {
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{0, 0, 2, 0, 0, 0, 6, 7, 0}};
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 },
};
dijkstras t = new dijkstras();
t.dijkstra(graph, 0);
} //main
} //djikstras
/*
OUTPUT :
Vertex Distance

View File

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

View File

@ -34,8 +34,7 @@ public class HamiltonianCycle {
for (int i = 0; i < this.cycle.length; i++) {
this.cycle[i] = -1;
}
}
else {
} else {
this.cycle[this.cycle.length - 1] = this.cycle[0];
}
@ -88,7 +87,6 @@ public class HamiltonianCycle {
* @param vertex Starting vertex
*/
public boolean isPresent(int vertex) {
for (int i = 0; i < pathCount - 1; i++) {
if (cycle[i] == vertex) {
return true;

View File

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

View File

@ -30,7 +30,12 @@ public class Kruskal {
}
}
private static void addEdge(HashSet<Edge>[] graph, int from, int to, int weight) {
private static void addEdge(
HashSet<Edge>[] graph,
int from,
int to,
int weight
) {
graph[from].add(new Edge(from, to, weight));
}
@ -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

View File

@ -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;
@ -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);
}
@ -313,9 +321,11 @@ class AdjacencyMatrixGraph {
// 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);
}

View File

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

View File

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

View File

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

View File

@ -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,12 +202,15 @@ 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.
*
@ -204,7 +218,16 @@ public class HashMapCuckooHashing {
* @return int the index where the key is located
*/
public boolean checkTableContainsKey(int key) {
return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key)) || (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key));
return (
(
buckets[hashFunction1(key)] != null &&
buckets[hashFunction1(key)].equals(key)
) ||
(
buckets[hashFunction2(key)] != null &&
buckets[hashFunction2(key)] == key
)
);
}
/**
@ -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;
}
}

View File

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

View File

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

View File

@ -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,24 +20,28 @@ public class Main {
choice = In.nextInt();
switch (choice) {
case 1: {
case 1:
{
System.out.println("Enter the Key: ");
key = In.nextInt();
h.insertHash(key);
break;
}
case 2: {
case 2:
{
System.out.println("Enter the Key delete: ");
key = In.nextInt();
h.deleteHash(key);
break;
}
case 3: {
case 3:
{
System.out.println("Print table");
h.displayHashtable();
break;
}
case 4: {
case 4:
{
In.close();
return;
}

View File

@ -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,38 +24,56 @@ public class MainCuckooHashing {
choice = In.nextInt();
switch (choice) {
case 1: {
case 1:
{
System.out.println("Enter the Key: ");
key = In.nextInt();
h.insertKey2HashTable(key);
break;
}
case 2: {
case 2:
{
System.out.println("Enter the Key delete: ");
key = In.nextInt();
h.deleteKeyFromHashTable(key);
break;
}
case 3: {
case 3:
{
System.out.println("Print table:\n");
h.displayHashtable();
break;
}
case 4: {
case 4:
{
In.close();
return;
}
case 5: {
System.out.println("Enter the Key to find and print: ");
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");
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());
case 6:
{
System.out.printf(
"Load factor is: %.2f\n",
h.checkLoadFactor()
);
break;
}
case 7: {
case 7:
{
h.reHashTableIncreasesTableSize();
break;
}

View File

@ -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,34 +22,44 @@ public class MainLinearProbing {
choice = In.nextInt();
switch (choice) {
case 1: {
case 1:
{
System.out.println("Enter the Key: ");
key = In.nextInt();
h.insertHash(key);
break;
}
case 2: {
case 2:
{
System.out.println("Enter the Key delete: ");
key = In.nextInt();
h.deleteHash(key);
break;
}
case 3: {
case 3:
{
System.out.println("Print table");
h.displayHashtable();
break;
}
case 4: {
case 4:
{
In.close();
return;
}
case 5: {
System.out.println("Enter the Key to find and print: ");
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));
System.out.println(
"Key: " + key + " is at index: " + h.findHash(key)
);
break;
}
case 6: {
case 6:
{
h.checkLoadFactor();
break;
}

View File

@ -1,6 +1,5 @@
package com.thealgorithms.datastructures.heaps;
public class FibonacciHeap {
private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;
@ -144,7 +143,10 @@ public class FibonacciHeap {
if (this.empty()) {
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) {
@ -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

View File

@ -3,13 +3,16 @@ 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) {
@ -17,15 +20,19 @@ public class GenericHeap <T extends Comparable <T> >{
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);
@ -33,14 +40,21 @@ public class GenericHeap <T extends Comparable <T> >{
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) {
if (
lci < this.size() &&
isLarger(this.data.get(lci), this.data.get(mini)) > 0
) {
mini = lci;
}
if(rci<this.size() && isLarger(this.data.get(rci),this.data.get(mini))>0) {
if (
rci < this.size() &&
isLarger(this.data.get(rci), this.data.get(mini)) > 0
) {
mini = rci;
}
if (mini != pi) {
@ -48,13 +62,16 @@ public class GenericHeap <T extends Comparable <T> >{
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);
@ -63,6 +80,7 @@ public class GenericHeap <T extends Comparable <T> >{
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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -40,8 +40,7 @@ public class CreateAndDetectLoop {
Node connectedPoint = temp;
while (temp.next != null) // Traverse remaining nodes
{
while (temp.next != null) { // Traverse remaining nodes
temp = temp.next;
}

View File

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

View File

@ -177,6 +177,7 @@ class Link {
* This class implements the operations of the Link nodes.
*/
class LinkOperations {
/**
* Head refers to the front of the list
*/
@ -198,8 +199,7 @@ class LinkOperations{
*/
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)
@ -234,9 +234,15 @@ 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);
@ -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!"
);
}
}
@ -332,8 +339,7 @@ class LinkOperations{
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;
}
@ -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;
}
}

View File

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

View File

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

View File

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

View File

@ -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)
*/

View File

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

View File

@ -81,8 +81,7 @@ public class SinglyLinkedList extends Node{
// If 'a' is not head node of list
if (previousA != null) {
previousA.next = currentB;
}
else{
} else {
// make 'b' as the new head
head = currentB;
}
@ -90,8 +89,7 @@ public class SinglyLinkedList extends Node{
// If 'b' is not head node of list
if (previousB != null) {
previousB.next = currentA;
}
else{
} else {
// Make 'a' as new head
head = currentA;
}
@ -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;
}
}

View File

@ -189,7 +189,8 @@ public class SkipList<E extends Comparable<E>> {
}
Collections.reverse(layers);
String result = layers.stream()
String result = layers
.stream()
.map(layer -> {
StringBuilder acc = new StringBuilder();
for (boolean b : layer) {
@ -203,7 +204,8 @@ public class SkipList<E extends Comparable<E>> {
return acc.toString();
})
.collect(Collectors.joining("\n"));
String positions = IntStream.range(0, sizeWithHeader - 1)
String positions = IntStream
.range(0, sizeWithHeader - 1)
.mapToObj(i -> String.format("%3d", i))
.collect(Collectors.joining(" "));
@ -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();
}

View File

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

View File

@ -121,8 +121,7 @@ public class PriorityQueues {
// [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top
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
}

View File

@ -31,10 +31,13 @@ class BalancedBrackets {
{ '(', ')' },
{ '[', ']' },
{ '{', '}' },
{'<', '>'}
{ '<', '>' },
};
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;

View File

@ -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];

View File

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

View File

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

View File

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

View File

@ -8,6 +8,7 @@ import java.util.Stack;
*/
public class LargestRectangle {
public static String largestRectanglehistogram(int[] heights) {
int n = heights.length, maxArea = 0;
Stack<int[]> st = new Stack<>();
@ -26,8 +27,10 @@ public class LargestRectangle {
}
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, 1, 5, 6, 2, 3 })
.equals("10");
assert largestRectanglehistogram(new int[] { 2, 4 }).equals("4");
}
}

View File

@ -102,5 +102,4 @@ public class MaximumMinimumWindow {
int[] res = calculateMaxOfMin(arr, arr.length);
assert Arrays.equals(target, res);
}
}

View File

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

View File

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

View File

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

View File

@ -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,44 +31,32 @@ 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;
/* First two characters should NOT be operators */
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)
{
} else {
if (operatorCount == 0) {
operandCount++;
continue;
}
if (operandCount != operatorCount + 1) return false;
/* Operand count is set to 2 because:-
*
* 1) the previous set of operands & operators combined have become a single valid expression,
@ -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;
/* 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)))");
}
}

View File

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

View File

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

View File

@ -1,4 +1,3 @@
package com.thealgorithms.datastructures.trees;
/*
@ -27,24 +26,27 @@ 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);
@ -59,11 +61,9 @@ public class AVLSimple {
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);
if (bf > 1 && item < node.left.data) return rightRotate(node);
//RR case
if(bf<-1&&item>node.right.data)
return leftRotate(node);
if (bf < -1 && item > node.right.data) return leftRotate(node);
//RL case
if (bf < -1 && item < node.right.data) {
node.right = rightRotate(node.right);
@ -77,37 +77,33 @@ public class AVLSimple {
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=>";
if (node.left != null) str += node.left.data + "=>"; else str +=
"END=>";
str += node.data + "";
if(node.right!=null)
str+="<="+node.right.data;
else
str+="<=END";
if (node.right != null) str += "<=" + node.right.data; else str +=
"<=END";
System.out.println(str);
if(node.left!=null)
display(node.left);
if(node.right!=null)
display(node.right);
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;
if (node == null) return 0;
return height(node.left) - height(node.right);
}
@ -120,8 +116,8 @@ public class AVLSimple {
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;
@ -131,7 +127,5 @@ public class AVLSimple {
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