Skip to content

Commit 634e9cc

Browse files
authored
Merge branch 'master' into add_test_tower_hanoi
2 parents bb1268e + 9b52ac9 commit 634e9cc

File tree

11 files changed

+499
-111
lines changed

11 files changed

+499
-111
lines changed

DIRECTORY.md

+18-1
Large diffs are not rendered by default.

src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java

+45-21
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,80 @@
11
package com.thealgorithms.bitmanipulation;
22

33
/**
4-
* This class provides methods to convert between BCD (Binary-Coded Decimal) and binary.
4+
* This class provides methods to convert between BCD (Binary-Coded Decimal) and decimal numbers.
55
*
6-
* Binary-Coded Decimal (BCD) is a class of binary encodings of decimal numbers where each decimal digit is represented by a fixed number of binary digits, usually four or eight.
6+
* BCD is a class of binary encodings of decimal numbers where each decimal digit is represented by a fixed number of binary digits, usually four or eight.
77
*
88
* For more information, refer to the
99
* <a href="https://en.wikipedia.org/wiki/Binary-coded_decimal">Binary-Coded Decimal</a> Wikipedia page.
1010
*
1111
* <b>Example usage:</b>
1212
* <pre>
13-
* int binary = BcdConversion.bcdToBinary(0x1234);
14-
* System.out.println("BCD 0x1234 to binary: " + binary); // Output: 1234
13+
* int decimal = BcdConversion.bcdToDecimal(0x1234);
14+
* System.out.println("BCD 0x1234 to decimal: " + decimal); // Output: 1234
1515
*
16-
* int bcd = BcdConversion.binaryToBcd(1234);
17-
* System.out.println("Binary 1234 to BCD: " + Integer.toHexString(bcd)); // Output: 0x1234
16+
* int bcd = BcdConversion.decimalToBcd(1234);
17+
* System.out.println("Decimal 1234 to BCD: " + Integer.toHexString(bcd)); // Output: 0x1234
1818
* </pre>
1919
*/
2020
public final class BcdConversion {
2121
private BcdConversion() {
2222
}
23+
2324
/**
24-
* Converts a BCD (Binary-Coded Decimal) number to binary.
25+
* Converts a BCD (Binary-Coded Decimal) number to a decimal number.
26+
* <p>Steps:
27+
* <p>1. Validate the BCD number to ensure all digits are between 0 and 9.
28+
* <p>2. Extract the last 4 bits (one BCD digit) from the BCD number.
29+
* <p>3. Multiply the extracted digit by the corresponding power of 10 and add it to the decimal number.
30+
* <p>4. Shift the BCD number right by 4 bits to process the next BCD digit.
31+
* <p>5. Repeat steps 1-4 until the BCD number is zero.
2532
*
2633
* @param bcd The BCD number.
27-
* @return The corresponding binary number.
34+
* @return The corresponding decimal number.
35+
* @throws IllegalArgumentException if the BCD number contains invalid digits.
2836
*/
29-
public static int bcdToBinary(int bcd) {
30-
int binary = 0;
37+
public static int bcdToDecimal(int bcd) {
38+
int decimal = 0;
3139
int multiplier = 1;
40+
41+
// Validate BCD digits
3242
while (bcd > 0) {
33-
int digit = bcd & 0xF; // Extract the last 4 bits (one BCD digit)
34-
binary += digit * multiplier;
43+
int digit = bcd & 0xF;
44+
if (digit > 9) {
45+
throw new IllegalArgumentException("Invalid BCD digit: " + digit);
46+
}
47+
decimal += digit * multiplier;
3548
multiplier *= 10;
36-
bcd >>= 4; // Shift right by 4 bits to process the next BCD digit
49+
bcd >>= 4;
3750
}
38-
return binary;
51+
return decimal;
3952
}
4053

4154
/**
42-
* Converts a binary number to BCD (Binary-Coded Decimal).
55+
* Converts a decimal number to BCD (Binary-Coded Decimal).
56+
* <p>Steps:
57+
* <p>1. Check if the decimal number is within the valid range for BCD (0 to 9999).
58+
* <p>2. Extract the last decimal digit from the decimal number.
59+
* <p>3. Shift the digit to the correct BCD position and add it to the BCD number.
60+
* <p>4. Remove the last decimal digit from the decimal number.
61+
* <p>5. Repeat steps 2-4 until the decimal number is zero.
4362
*
44-
* @param binary The binary number.
63+
* @param decimal The decimal number.
4564
* @return The corresponding BCD number.
65+
* @throws IllegalArgumentException if the decimal number is greater than 9999.
4666
*/
47-
public static int binaryToBcd(int binary) {
67+
public static int decimalToBcd(int decimal) {
68+
if (decimal < 0 || decimal > 9999) {
69+
throw new IllegalArgumentException("Value out of bounds for BCD representation: " + decimal);
70+
}
71+
4872
int bcd = 0;
4973
int shift = 0;
50-
while (binary > 0) {
51-
int digit = binary % 10; // Extract the last decimal digit
52-
bcd |= (digit << (shift * 4)); // Shift the digit to the correct BCD position
53-
binary /= 10; // Remove the last decimal digit
74+
while (decimal > 0) {
75+
int digit = decimal % 10;
76+
bcd |= (digit << (shift * 4));
77+
decimal /= 10;
5478
shift++;
5579
}
5680
return bcd;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.thealgorithms.conversions;
2+
3+
/**
4+
* Converts an IPv4 address to its binary equivalent and vice-versa.
5+
* IP to Binary: Converts an IPv4 address to its binary equivalent.
6+
* Example: 127.3.4.5 -> 01111111.00000011.00000100.00000101
7+
*
8+
* Binary to IP: Converts a binary equivalent to an IPv4 address.
9+
* Example: 01111111.00000011.00000100.00000101 -> 127.3.4.5
10+
*
11+
* @author Hardvan
12+
*/
13+
public final class IPConverter {
14+
private IPConverter() {
15+
}
16+
17+
/**
18+
* Converts an IPv4 address to its binary equivalent.
19+
* @param ip The IPv4 address to convert.
20+
* @return The binary equivalent of the IPv4 address.
21+
*/
22+
public static String ipToBinary(String ip) {
23+
StringBuilder binary = new StringBuilder();
24+
for (String octet : ip.split("\\.")) {
25+
binary.append(octetToBinary(Integer.parseInt(octet))).append(".");
26+
}
27+
return binary.substring(0, binary.length() - 1);
28+
}
29+
30+
/**
31+
* Converts a single octet to its 8-bit binary representation.
32+
* @param octet The octet to convert (0-255).
33+
* @return The 8-bit binary representation as a String.
34+
*/
35+
private static String octetToBinary(int octet) {
36+
char[] binary = {'0', '0', '0', '0', '0', '0', '0', '0'};
37+
for (int i = 7; i >= 0; i--) {
38+
if ((octet & 1) == 1) {
39+
binary[i] = '1';
40+
}
41+
octet >>>= 1;
42+
}
43+
return new String(binary);
44+
}
45+
46+
/**
47+
* Converts a binary equivalent to an IPv4 address.
48+
* @param binary The binary equivalent to convert.
49+
* @return The IPv4 address of the binary equivalent.
50+
*/
51+
public static String binaryToIP(String binary) {
52+
StringBuilder ip = new StringBuilder();
53+
for (String octet : binary.split("\\.")) {
54+
ip.append(Integer.parseInt(octet, 2)).append(".");
55+
}
56+
return ip.substring(0, ip.length() - 1);
57+
}
58+
}
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,65 @@
11
package com.thealgorithms.others;
22

3-
import java.util.Scanner;
3+
import java.util.List;
44

5+
/**
6+
* The {@code TowerOfHanoi} class provides a recursive solution to the Tower of Hanoi puzzle.
7+
* This puzzle involves moving a set of discs from one pole to another, following specific rules:
8+
* 1. Only one disc can be moved at a time.
9+
* 2. A disc can only be placed on top of a larger disc.
10+
* 3. All discs must start on one pole and end on another.
11+
*
12+
* This implementation recursively calculates the steps required to solve the puzzle and stores them
13+
* in a provided list.
14+
*
15+
* <p>
16+
* For more information about the Tower of Hanoi, see
17+
* <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi">Tower of Hanoi on Wikipedia</a>.
18+
* </p>
19+
*
20+
* The {@code shift} method takes the number of discs and the names of the poles,
21+
* and appends the steps required to solve the puzzle to the provided list.
22+
* Time Complexity: O(2^n) - Exponential time complexity due to the recursive nature of the problem.
23+
* Space Complexity: O(n) - Linear space complexity due to the recursion stack.
24+
* Wikipedia: https://en.wikipedia.org/wiki/Tower_of_Hanoi
25+
*/
526
final class TowerOfHanoi {
27+
628
private TowerOfHanoi() {
729
}
830

9-
public static void shift(int n, String startPole, String intermediatePole, String endPole) {
10-
// if n becomes zero the program returns thus ending the loop.
31+
/**
32+
* Recursively solve the Tower of Hanoi puzzle by moving discs between poles.
33+
*
34+
* @param n The number of discs to move.
35+
* @param startPole The name of the start pole from which discs are moved.
36+
* @param intermediatePole The name of the intermediate pole used as a temporary holding area.
37+
* @param endPole The name of the end pole to which discs are moved.
38+
* @param result A list to store the steps required to solve the puzzle.
39+
*
40+
* <p>
41+
* This method is called recursively to move n-1 discs
42+
* to the intermediate pole,
43+
* then moves the nth disc to the end pole, and finally
44+
* moves the n-1 discs from the
45+
* intermediate pole to the end pole.
46+
* </p>
47+
*
48+
* <p>
49+
* Time Complexity: O(2^n) - Exponential time complexity due to the recursive nature of the problem.
50+
* Space Complexity: O(n) - Linear space complexity due to the recursion stack.
51+
* </p>
52+
*/
53+
public static void shift(int n, String startPole, String intermediatePole, String endPole, List<String> result) {
1154
if (n != 0) {
12-
// Shift function is called in recursion for swapping the n-1 disc from the startPole to
13-
// the intermediatePole
14-
shift(n - 1, startPole, endPole, intermediatePole);
15-
System.out.format("Move %d from %s to %s%n", n, startPole, endPole); // Result Printing
16-
// Shift function is called in recursion for swapping the n-1 disc from the
17-
// intermediatePole to the endPole
18-
shift(n - 1, intermediatePole, startPole, endPole);
19-
}
20-
}
55+
// Move n-1 discs from startPole to intermediatePole
56+
shift(n - 1, startPole, endPole, intermediatePole, result);
2157

22-
public static void main(String[] args) {
23-
System.out.print("Enter number of discs on Pole 1: ");
24-
Scanner scanner = new Scanner(System.in);
25-
int numberOfDiscs = scanner.nextInt(); // input of number of discs on pole 1
26-
shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); // Shift function called
27-
scanner.close();
58+
// Add the move of the nth disc from startPole to endPole
59+
result.add(String.format("Move %d from %s to %s", n, startPole, endPole));
60+
61+
// Move the n-1 discs from intermediatePole to endPole
62+
shift(n - 1, intermediatePole, startPole, endPole, result);
63+
}
2864
}
2965
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package com.thealgorithms.stacks;
2+
3+
import java.util.Set;
4+
import java.util.Stack;
5+
6+
/**
7+
* Evaluate a postfix (Reverse Polish) expression using a stack.
8+
*
9+
* <p>Example: Expression "5 6 + 2 *" results in 22.
10+
* <p>Applications: Used in calculators and expression evaluation in compilers.
11+
*
12+
* @author Hardvan
13+
*/
14+
public final class PostfixEvaluator {
15+
private PostfixEvaluator() {
16+
}
17+
18+
private static final Set<String> OPERATORS = Set.of("+", "-", "*", "/");
19+
20+
/**
21+
* Evaluates the given postfix expression and returns the result.
22+
*
23+
* @param expression The postfix expression as a string with operands and operators separated by spaces.
24+
* @return The result of evaluating the postfix expression.
25+
* @throws IllegalArgumentException if the expression is invalid.
26+
*/
27+
public static int evaluatePostfix(String expression) {
28+
Stack<Integer> stack = new Stack<>();
29+
30+
for (String token : expression.split("\\s+")) {
31+
if (isOperator(token)) {
32+
int operand2 = stack.pop();
33+
int operand1 = stack.pop();
34+
stack.push(applyOperator(token, operand1, operand2));
35+
} else {
36+
stack.push(Integer.valueOf(token));
37+
}
38+
}
39+
40+
if (stack.size() != 1) {
41+
throw new IllegalArgumentException("Invalid expression");
42+
}
43+
44+
return stack.pop();
45+
}
46+
47+
/**
48+
* Checks if the given token is an operator.
49+
*
50+
* @param token The token to check.
51+
* @return true if the token is an operator, false otherwise.
52+
*/
53+
private static boolean isOperator(String token) {
54+
return OPERATORS.contains(token);
55+
}
56+
57+
/**
58+
* Applies the given operator to the two operands.
59+
*
60+
* @param operator The operator to apply.
61+
* @param a The first operand.
62+
* @param b The second operand.
63+
* @return The result of applying the operator to the operands.
64+
*/
65+
private static int applyOperator(String operator, int a, int b) {
66+
return switch (operator) {
67+
case "+" -> a + b;
68+
case "-" -> a - b;
69+
case "*" -> a * b;
70+
case "/" -> a / b;
71+
default -> throw new IllegalArgumentException("Invalid operator");
72+
};
73+
}
74+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.thealgorithms.stacks;
2+
3+
import java.util.Set;
4+
import java.util.Stack;
5+
6+
/**
7+
* Evaluate a prefix (Polish) expression using a stack.
8+
*
9+
* <p>Example: Expression "+ * 2 3 4" results in 10.
10+
* <p>Applications: Useful for implementing compilers and interpreters.
11+
*
12+
* @author Hardvan
13+
*/
14+
public final class PrefixEvaluator {
15+
private PrefixEvaluator() {
16+
}
17+
18+
private static final Set<String> OPERATORS = Set.of("+", "-", "*", "/");
19+
20+
/**
21+
* Evaluates the given prefix expression and returns the result.
22+
*
23+
* @param expression The prefix expression as a string with operands and operators separated by spaces.
24+
* @return The result of evaluating the prefix expression.
25+
* @throws IllegalArgumentException if the expression is invalid.
26+
*/
27+
public static int evaluatePrefix(String expression) {
28+
Stack<Integer> stack = new Stack<>();
29+
String[] tokens = expression.split("\\s+");
30+
31+
for (int i = tokens.length - 1; i >= 0; i--) {
32+
String token = tokens[i];
33+
if (isOperator(token)) {
34+
int operand1 = stack.pop();
35+
int operand2 = stack.pop();
36+
stack.push(applyOperator(token, operand1, operand2));
37+
} else {
38+
stack.push(Integer.valueOf(token));
39+
}
40+
}
41+
42+
if (stack.size() != 1) {
43+
throw new IllegalArgumentException("Invalid expression");
44+
}
45+
46+
return stack.pop();
47+
}
48+
49+
/**
50+
* Checks if the given token is an operator.
51+
*
52+
* @param token The token to check.
53+
* @return true if the token is an operator, false otherwise.
54+
*/
55+
private static boolean isOperator(String token) {
56+
return OPERATORS.contains(token);
57+
}
58+
59+
/**
60+
* Applies the given operator to the two operands.
61+
*
62+
* @param operator The operator to apply.
63+
* @param a The first operand.
64+
* @param b The second operand.
65+
* @return The result of applying the operator to the operands.
66+
*/
67+
private static int applyOperator(String operator, int a, int b) {
68+
return switch (operator) {
69+
case "+" -> a + b;
70+
case "-" -> a - b;
71+
case "*" -> a * b;
72+
case "/" -> a / b;
73+
default -> throw new IllegalArgumentException("Invalid operator");
74+
};
75+
}
76+
}

0 commit comments

Comments
 (0)