repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/TrappingRainwater.java
src/main/java/com/thealgorithms/stacks/TrappingRainwater.java
package com.thealgorithms.stacks; /** * Trapping Rainwater Problem * Given an array of non-negative integers representing the height of bars, * compute how much water it can trap after raining. * * Example: * Input: [4,2,0,3,2,5] * Output: 9 * * Time Complexity: O(n) * Space Complexity: O(1) * * Reference: https://en.wikipedia.org/wiki/Trapping_rain_water */ public final class TrappingRainwater { private TrappingRainwater() { throw new UnsupportedOperationException("Utility class"); } public static int trap(int[] height) { int left = 0; int right = height.length - 1; int leftMax = 0; int rightMax = 0; int result = 0; while (left < right) { if (height[left] < height[right]) { if (height[left] >= leftMax) { leftMax = height[left]; } else { result += leftMax - height[left]; } left++; } else { if (height[right] >= rightMax) { rightMax = height[right]; } else { result += rightMax - height[right]; } right--; } } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/MinStackUsingTwoStacks.java
src/main/java/com/thealgorithms/stacks/MinStackUsingTwoStacks.java
package com.thealgorithms.stacks; import java.util.Stack; /** * Min-Stack implementation that supports push, pop, and retrieving the minimum element in constant time. * * @author Hardvan */ public final class MinStackUsingTwoStacks { MinStackUsingTwoStacks() { } private final Stack<Integer> stack = new Stack<>(); private final Stack<Integer> minStack = new Stack<>(); /** * Pushes a new element onto the {@code stack}. * If the value is less than or equal to the current minimum, it is also pushed onto the {@code minStack}. * * @param value The value to be pushed. */ public void push(int value) { stack.push(value); if (minStack.isEmpty() || value <= minStack.peek()) { minStack.push(value); } } /** * Removes the top element from the stack. * If the element is the minimum element, it is also removed from the {@code minStack}. */ public void pop() { if (stack.pop().equals(minStack.peek())) { minStack.pop(); } } /** * Retrieves the top element of the stack. * * @return The top element. */ public int top() { return stack.peek(); } /** * Retrieves the minimum element in the stack. * * @return The minimum element. */ public int getMin() { return minStack.peek(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/InfixToPrefix.java
src/main/java/com/thealgorithms/stacks/InfixToPrefix.java
package com.thealgorithms.stacks; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Utility class for converting an infix arithmetic expression * into its equivalent prefix notation expression. * <p> * This class provides a static method to perform the conversion, * validating balanced brackets before processing. * </p> */ public final class InfixToPrefix { private InfixToPrefix() { } /** * Converts a given infix expression string to a prefix expression string. * <p> * The method validates that the input expression has balanced brackets using * {@code BalancedBrackets.isBalanced} on the filtered bracket characters. * It throws an {@code IllegalArgumentException} if the brackets are unbalanced, * and a {@code NullPointerException} if the input is null. * </p> * <p> * Supported operators: {@code +, -, *, /, ^} and operands can be letters or digits. * </p> * * @param infixExpression the arithmetic expression in infix notation * @return the equivalent prefix notation expression * @throws IllegalArgumentException if brackets are unbalanced * @throws NullPointerException if the input expression is null */ public static String infix2Prefix(String infixExpression) { if (infixExpression == null) { throw new NullPointerException("Input expression cannot be null."); } infixExpression = infixExpression.trim(); if (infixExpression.isEmpty()) { return ""; } if (!BalancedBrackets.isBalanced(filterBrackets(infixExpression))) { throw new IllegalArgumentException("Invalid expression: unbalanced brackets."); } StringBuilder output = new StringBuilder(); Stack<Character> operatorStack = new Stack<>(); // Reverse the infix expression to facilitate prefix conversion String reversedInfix = new StringBuilder(infixExpression).reverse().toString(); for (char token : reversedInfix.toCharArray()) { if (Character.isLetterOrDigit(token)) { // Append operands directly to output output.append(token); } else if (token == ')') { // Push ')' onto stack (since expression is reversed, '(' and ')' roles swapped) operatorStack.push(token); } else if (token == '(') { // Pop operators until ')' is found while (!operatorStack.isEmpty() && operatorStack.peek() != ')') { output.append(operatorStack.pop()); } operatorStack.pop(); // Remove the ')' } else { // Pop operators with higher precedence before pushing current operator while (!operatorStack.isEmpty() && precedence(token) < precedence(operatorStack.peek())) { output.append(operatorStack.pop()); } operatorStack.push(token); } } // Append any remaining operators in stack while (!operatorStack.isEmpty()) { output.append(operatorStack.pop()); } // Reverse the output to obtain the final prefix expression return output.reverse().toString(); } /** * Returns the precedence level of the given operator. * * @param operator the operator character (e.g., '+', '-', '*', '/', '^') * @return the precedence value: higher means higher precedence, * or -1 if the character is not a recognized operator */ private static int precedence(char operator) { return switch (operator) { case '+', '-' -> 0; case '*', '/' -> 1; case '^' -> 2; default -> -1; }; } /** * Extracts only the bracket characters from the input string. * Supports parentheses (), curly braces {}, square brackets [], and angle brackets &lt;&gt;. * * @param input the original expression string * @return a string containing only bracket characters from the input */ private static String filterBrackets(String input) { Pattern pattern = Pattern.compile("[^(){}\\[\\]<>]"); Matcher matcher = pattern.matcher(input); return matcher.replaceAll(""); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java
src/main/java/com/thealgorithms/stacks/BalancedBrackets.java
package com.thealgorithms.stacks; import java.util.Stack; /** * The nested brackets problem is a problem that determines if a sequence of * brackets are properly nested. A sequence of brackets s is considered properly * nested if any of the following conditions are true: - s is empty - s has the * form (U) or [U] or {U} where U is a properly nested string - s has the form * VW where V and W are properly nested strings For example, the string * "()()[()]" is properly nested but "[(()]" is not. The function called * is_balanced takes as input a string S which is a sequence of brackets and * returns true if S is nested and false otherwise. * * @author akshay sharma * @author <a href="https://github.com/khalil2535">khalil2535<a> * @author shellhub */ final class BalancedBrackets { private BalancedBrackets() { } /** * Check if {@code leftBracket} and {@code rightBracket} is paired or not * * @param leftBracket left bracket * @param rightBracket right bracket * @return {@code true} if {@code leftBracket} and {@code rightBracket} is * paired, otherwise {@code false} */ public static boolean isPaired(char leftBracket, char rightBracket) { char[][] pairedBrackets = { {'(', ')'}, {'[', ']'}, {'{', '}'}, {'<', '>'}, }; for (char[] pairedBracket : pairedBrackets) { if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) { return true; } } return false; } /** * Check if {@code brackets} is balanced * * @param brackets the brackets * @return {@code true} if {@code brackets} is balanced, otherwise * {@code false} */ public static boolean isBalanced(String brackets) { if (brackets == null) { throw new IllegalArgumentException("brackets is null"); } Stack<Character> bracketsStack = new Stack<>(); for (char bracket : brackets.toCharArray()) { switch (bracket) { case '(': case '[': case '<': case '{': bracketsStack.push(bracket); break; case ')': case ']': case '>': case '}': if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) { return false; } break; default: return false; } } return bracketsStack.isEmpty(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/LargestRectangle.java
src/main/java/com/thealgorithms/stacks/LargestRectangle.java
package com.thealgorithms.stacks; import java.util.Stack; /** * Utility class to calculate the largest rectangle area in a histogram. * Each bar's width is assumed to be 1 unit. * * <p>This implementation uses a monotonic stack to efficiently calculate * the area of the largest rectangle that can be formed from the histogram bars.</p> * * <p>Example usage: * <pre>{@code * int[] heights = {2, 1, 5, 6, 2, 3}; * String area = LargestRectangle.largestRectangleHistogram(heights); * // area is "10" * }</pre> */ public final class LargestRectangle { private LargestRectangle() { } /** * Calculates the largest rectangle area in the given histogram. * * @param heights an array of non-negative integers representing bar heights * @return the largest rectangle area as a {@link String} */ public static String largestRectangleHistogram(int[] heights) { int maxArea = 0; Stack<int[]> stack = new Stack<>(); for (int i = 0; i < heights.length; i++) { int start = i; while (!stack.isEmpty() && stack.peek()[1] > heights[i]) { int[] popped = stack.pop(); maxArea = Math.max(maxArea, popped[1] * (i - popped[0])); start = popped[0]; } stack.push(new int[] {start, heights[i]}); } int totalLength = heights.length; while (!stack.isEmpty()) { int[] remaining = stack.pop(); maxArea = Math.max(maxArea, remaining[1] * (totalLength - remaining[0])); } return Integer.toString(maxArea); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/MaximumMinimumWindow.java
src/main/java/com/thealgorithms/stacks/MaximumMinimumWindow.java
package com.thealgorithms.stacks; import java.util.Arrays; import java.util.Stack; /** * Given an integer array. The task is to find the maximum of the minimum of * every window size in the array. Note: Window size varies from 1 to the size * of the Array. * <p> * For example, * <p> * N = 7 * arr[] = {10,20,30,50,10,70,30} * <p> * So the answer for the above would be : 70 30 20 10 10 10 10 * <p> * We need to consider window sizes from 1 to length of array in each iteration. * So in the iteration 1 the windows would be [10], [20], [30], [50], [10], * [70], [30]. Now we need to check the minimum value in each window. Since the * window size is 1 here the minimum element would be the number itself. Now the * maximum out of these is the result in iteration 1. In the second iteration we * need to consider window size 2, so there would be [10,20], [20,30], [30,50], * [50,10], [10,70], [70,30]. Now the minimum of each window size would be * [10,20,30,10,10] and the maximum out of these is 30. Similarly we solve for * other window sizes. * * @author sahil */ public final class MaximumMinimumWindow { private MaximumMinimumWindow() { } /** * This function contains the logic of finding maximum of minimum for every * window size using Stack Data Structure. * * @param arr Array containing the numbers * @param n Length of the array * @return result array */ public static int[] calculateMaxOfMin(int[] arr, int n) { Stack<Integer> s = new Stack<>(); int[] left = new int[n + 1]; int[] right = new int[n + 1]; for (int i = 0; i < n; i++) { left[i] = -1; right[i] = n; } for (int i = 0; i < n; i++) { while (!s.empty() && arr[s.peek()] >= arr[i]) { s.pop(); } if (!s.empty()) { left[i] = s.peek(); } s.push(i); } while (!s.empty()) { s.pop(); } for (int i = n - 1; i >= 0; i--) { while (!s.empty() && arr[s.peek()] >= arr[i]) { s.pop(); } if (!s.empty()) { right[i] = s.peek(); } s.push(i); } int[] ans = new int[n + 1]; for (int i = 0; i <= n; i++) { ans[i] = 0; } for (int i = 0; i < n; i++) { int len = right[i] - left[i] - 1; ans[len] = Math.max(ans[len], arr[i]); } for (int i = n - 1; i >= 1; i--) { ans[i] = Math.max(ans[i], ans[i + 1]); } // Print the result for (int i = 1; i <= n; i++) { System.out.print(ans[i] + " "); } return ans; } public static void main(String[] args) { int[] arr = new int[] {10, 20, 30, 50, 10, 70, 30}; int[] target = new int[] {70, 30, 20, 10, 10, 10, 10}; int[] res = calculateMaxOfMin(arr, arr.length); assert Arrays.equals(target, res); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/SortStack.java
src/main/java/com/thealgorithms/stacks/SortStack.java
package com.thealgorithms.stacks; import java.util.Stack; /** * A utility class that provides a method to sort a stack using recursion. * The elements are sorted in ascending order, with the largest element at the top. * This algorithm is implemented using only recursion and the original stack, * without utilizing any additional data structures apart from the stack itself. */ public final class SortStack { private SortStack() { } /** * Sorts the given stack in ascending order using recursion. * The sorting is performed such that the largest element ends up on top of the stack. * This method modifies the original stack and does not return a new stack. * * The algorithm works as follows: * 1. Remove the top element. * 2. Recursively sort the remaining stack. * 3. Insert the removed element back into the sorted stack at the correct position. * * @param stack The stack to be sorted, containing Integer elements. * @throws IllegalArgumentException if the stack contains `null` elements. */ public static void sortStack(Stack<Integer> stack) { if (stack.isEmpty()) { return; } int top = stack.pop(); sortStack(stack); insertInSortedOrder(stack, top); } /** * Helper method to insert an element into the correct position in a sorted stack. * This method is called recursively to place the given element into the stack * such that the stack remains sorted in ascending order. * * The element is inserted in such a way that all elements below it are smaller * (if the stack is non-empty), and elements above it are larger, maintaining * the ascending order. * * @param stack The stack in which the element needs to be inserted. * @param element The element to be inserted into the stack in sorted order. */ private static void insertInSortedOrder(Stack<Integer> stack, int element) { if (stack.isEmpty() || element > stack.peek()) { stack.push(element); return; } int top = stack.pop(); insertInSortedOrder(stack, element); stack.push(top); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/InfixToPostfix.java
src/main/java/com/thealgorithms/stacks/InfixToPostfix.java
package com.thealgorithms.stacks; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Utility class for converting an infix arithmetic expression * into its equivalent postfix (Reverse Polish Notation) form. * <p> * This class provides a static method to perform the conversion, * validating balanced brackets before processing. * </p> */ public final class InfixToPostfix { private InfixToPostfix() { } /** * Converts a given infix expression string to a postfix expression string. * <p> * The method first checks if the brackets in the input expression are balanced * by calling {@code BalancedBrackets.isBalanced} on the filtered brackets. * If the brackets are not balanced, it throws an IllegalArgumentException. * </p> * <p> * Supported operators are: {@code +, -, *, /, ^} * and operands can be letters or digits. * </p> * * @param infixExpression the arithmetic expression in infix notation * @return the equivalent postfix notation expression * @throws IllegalArgumentException if the brackets in the expression are unbalanced */ public static String infix2PostFix(String infixExpression) { if (!BalancedBrackets.isBalanced(filterBrackets(infixExpression))) { throw new IllegalArgumentException("Invalid expression: unbalanced brackets."); } StringBuilder output = new StringBuilder(); Stack<Character> operatorStack = new Stack<>(); for (char token : infixExpression.toCharArray()) { if (Character.isLetterOrDigit(token)) { // Append operands (letters or digits) directly to output output.append(token); } else if (token == '(') { // Push '(' to stack operatorStack.push(token); } else if (token == ')') { // Pop and append until '(' is found while (!operatorStack.isEmpty() && operatorStack.peek() != '(') { output.append(operatorStack.pop()); } operatorStack.pop(); // Remove '(' from stack } else { // Pop operators with higher or equal precedence and append them while (!operatorStack.isEmpty() && precedence(token) <= precedence(operatorStack.peek())) { output.append(operatorStack.pop()); } operatorStack.push(token); } } // Pop any remaining operators while (!operatorStack.isEmpty()) { output.append(operatorStack.pop()); } return output.toString(); } /** * Returns the precedence level of the given operator. * * @param operator the operator character (e.g., '+', '-', '*', '/', '^') * @return the precedence value: higher means higher precedence, * or -1 if the character is not a recognized operator */ private static int precedence(char operator) { return switch (operator) { case '+', '-' -> 0; case '*', '/' -> 1; case '^' -> 2; default -> -1; }; } /** * Extracts only the bracket characters from the input string. * Supports parentheses (), curly braces {}, square brackets [], and angle brackets &lt;&gt;. * * @param input the original expression string * @return a string containing only bracket characters from the input */ private static String filterBrackets(String input) { Pattern pattern = Pattern.compile("[^(){}\\[\\]<>]"); Matcher matcher = pattern.matcher(input); return matcher.replaceAll(""); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java
src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java
package com.thealgorithms.stacks; import java.util.Scanner; import java.util.Stack; import java.util.function.BiFunction; /** * Utility class for evaluating postfix expressions using integer arithmetic. * <p> * Postfix notation, also known as Reverse Polish Notation (RPN), is a mathematical notation in which operators follow their operands. * This class provides a method to evaluate expressions written in postfix notation. * </p> * <p> * For more information on postfix notation, refer to * <a href="https://en.wikipedia.org/wiki/Reverse_Polish_notation">Reverse Polish Notation (RPN) on Wikipedia</a>. * </p> */ public final class StackPostfixNotation { private StackPostfixNotation() { } private static BiFunction<Integer, Integer, Integer> getOperator(final String operationSymbol) { // note the order of operands switch (operationSymbol) { case "+": return (a, b) -> b + a; case "-": return (a, b) -> b - a; case "*": return (a, b) -> b * a; case "/": return (a, b) -> b / a; default: throw new IllegalArgumentException("exp contains an unknown operation."); } } private static void performOperation(Stack<Integer> s, final String operationSymbol) { if (s.size() < 2) { throw new IllegalArgumentException("exp is not a proper postfix expression (too few arguments)."); } s.push(getOperator(operationSymbol).apply(s.pop(), s.pop())); } private static void consumeExpression(Stack<Integer> s, final String exp) { Scanner tokens = new Scanner(exp); while (tokens.hasNext()) { if (tokens.hasNextInt()) { s.push(tokens.nextInt()); } else { performOperation(s, tokens.next()); } } tokens.close(); } /** * @brief Evaluates the given postfix expression. * @param exp the expression to evaluate. * @return the value of the given expression. * @exception IllegalArgumentException exp is not a valid postix expression. */ public static int postfixEvaluate(final String exp) { Stack<Integer> s = new Stack<>(); consumeExpression(s, exp); if (s.size() != 1) { throw new IllegalArgumentException("exp is not a proper postfix expression."); } return s.pop(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/PrefixEvaluator.java
src/main/java/com/thealgorithms/stacks/PrefixEvaluator.java
package com.thealgorithms.stacks; import java.util.Set; import java.util.Stack; /** * Evaluate a prefix (Polish) expression using a stack. * * <p>Example: Expression "+ * 2 3 4" results in 10. * <p>Applications: Useful for implementing compilers and interpreters. * * @author Hardvan */ public final class PrefixEvaluator { private PrefixEvaluator() { } private static final Set<String> OPERATORS = Set.of("+", "-", "*", "/"); /** * Evaluates the given prefix expression and returns the result. * * @param expression The prefix expression as a string with operands and operators separated by spaces. * @return The result of evaluating the prefix expression. * @throws IllegalArgumentException if the expression is invalid. */ public static int evaluatePrefix(String expression) { Stack<Integer> stack = new Stack<>(); String[] tokens = expression.split("\\s+"); for (int i = tokens.length - 1; i >= 0; i--) { String token = tokens[i]; if (isOperator(token)) { int operand1 = stack.pop(); int operand2 = stack.pop(); stack.push(applyOperator(token, operand1, operand2)); } else { stack.push(Integer.valueOf(token)); } } if (stack.size() != 1) { throw new IllegalArgumentException("Invalid expression"); } return stack.pop(); } /** * Checks if the given token is an operator. * * @param token The token to check. * @return true if the token is an operator, false otherwise. */ private static boolean isOperator(String token) { return OPERATORS.contains(token); } /** * Applies the given operator to the two operands. * * @param operator The operator to apply. * @param a The first operand. * @param b The second operand. * @return The result of applying the operator to the operands. */ private static int applyOperator(String operator, int a, int b) { return switch (operator) { case "+" -> a + b; case "-" -> a - b; case "*" -> a * b; case "/" -> a / b; default -> throw new IllegalArgumentException("Invalid operator"); }; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/NextGreaterElement.java
src/main/java/com/thealgorithms/stacks/NextGreaterElement.java
package com.thealgorithms.stacks; import java.util.Stack; /** * Utility class to find the next greater element for each element in a given integer array. * * <p>The next greater element for an element x is the first greater element on the right side of x in the array. * If no such element exists, the result will contain 0 for that position.</p> * * <p>Example:</p> * <pre> * Input: {2, 7, 3, 5, 4, 6, 8} * Output: {7, 0, 5, 6, 6, 8, 0} * </pre> */ public final class NextGreaterElement { private NextGreaterElement() { } /** * Finds the next greater element for each element in the given array. * * @param array the input array of integers * @return an array where each element is replaced by the next greater element on the right side in the input array, * or 0 if there is no greater element. * @throws IllegalArgumentException if the input array is null */ public static int[] findNextGreaterElements(int[] array) { if (array == null) { throw new IllegalArgumentException("Input array cannot be null"); } int[] result = new int[array.length]; Stack<Integer> stack = new Stack<>(); for (int i = 0; i < array.length; i++) { while (!stack.isEmpty() && array[stack.peek()] < array[i]) { result[stack.pop()] = array[i]; } stack.push(i); } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/ConstrainedShortestPath.java
src/main/java/com/thealgorithms/graph/ConstrainedShortestPath.java
package com.thealgorithms.graph; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * This class implements a solution for the Constrained Shortest Path Problem (CSPP). * also known as Shortest Path Problem with Resource Constraints (SPPRC). * The goal is to find the shortest path between two nodes while ensuring that * the resource constraint is not exceeded. * * @author <a href="https://github.com/DenizAltunkapan">Deniz Altunkapan</a> */ public class ConstrainedShortestPath { /** * Represents a graph using an adjacency list. * This graph is designed for the Constrained Shortest Path Problem (CSPP). */ public static class Graph { private List<List<Edge>> adjacencyList; public Graph(int numNodes) { adjacencyList = new ArrayList<>(); for (int i = 0; i < numNodes; i++) { adjacencyList.add(new ArrayList<>()); } } /** * Adds an edge to the graph. * @param from the starting node * @param to the ending node * @param cost the cost of the edge * @param resource the resource required to traverse the edge */ public void addEdge(int from, int to, int cost, int resource) { adjacencyList.get(from).add(new Edge(from, to, cost, resource)); } /** * Gets the edges that are adjacent to a given node. * @param node the node to get the edges for * @return the list of edges adjacent to the node */ public List<Edge> getEdges(int node) { return adjacencyList.get(node); } /** * Gets the number of nodes in the graph. * @return the number of nodes */ public int getNumNodes() { return adjacencyList.size(); } public record Edge(int from, int to, int cost, int resource) { } } private Graph graph; private int maxResource; /** * Constructs a CSPSolver with the given graph and maximum resource constraint. * * @param graph the graph representing the problem * @param maxResource the maximum allowable resource */ public ConstrainedShortestPath(Graph graph, int maxResource) { this.graph = graph; this.maxResource = maxResource; } /** * Solves the CSP to find the shortest path from the start node to the target node * without exceeding the resource constraint. * * @param start the starting node * @param target the target node * @return the minimum cost to reach the target node within the resource constraint, * or -1 if no valid path exists */ public int solve(int start, int target) { int numNodes = graph.getNumNodes(); int[][] dp = new int[maxResource + 1][numNodes]; // Initialize dp table with maximum values for (int i = 0; i <= maxResource; i++) { Arrays.fill(dp[i], Integer.MAX_VALUE); } dp[0][start] = 0; // Dynamic Programming: Iterate over resources and nodes for (int r = 0; r <= maxResource; r++) { for (int u = 0; u < numNodes; u++) { if (dp[r][u] == Integer.MAX_VALUE) { continue; } for (Graph.Edge edge : graph.getEdges(u)) { int v = edge.to(); int cost = edge.cost(); int resource = edge.resource(); if (r + resource <= maxResource) { dp[r + resource][v] = Math.min(dp[r + resource][v], dp[r][u] + cost); } } } } // Find the minimum cost to reach the target node int minCost = Integer.MAX_VALUE; for (int r = 0; r <= maxResource; r++) { minCost = Math.min(minCost, dp[r][target]); } return minCost == Integer.MAX_VALUE ? -1 : minCost; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/EdmondsKarp.java
src/main/java/com/thealgorithms/graph/EdmondsKarp.java
package com.thealgorithms.graph; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; /** * Implementation of the Edmonds–Karp algorithm for computing the maximum flow of a directed graph. * <p> * The algorithm runs in O(V * E^2) time and is a specific implementation of the Ford–Fulkerson * method where the augmenting paths are found using breadth-first search (BFS) to ensure the * shortest augmenting paths (in terms of the number of edges) are used. * </p> * * <p>The graph is represented with a capacity matrix where {@code capacity[u][v]} denotes the * capacity of the edge from {@code u} to {@code v}. Negative capacities are not allowed.</p> * * @author <a href="https://en.wikipedia.org/wiki/Edmonds%E2%80%93Karp_algorithm">Wikipedia: EdmondsKarp algorithm</a> */ public final class EdmondsKarp { private EdmondsKarp() { } /** * Computes the maximum flow from {@code source} to {@code sink} in the provided capacity matrix. * * @param capacity the capacity matrix representing the directed graph; must be square and non-null * @param source the source vertex index * @param sink the sink vertex index * @return the value of the maximum flow between {@code source} and {@code sink} * @throws IllegalArgumentException if the matrix is {@code null}, not square, contains negative * capacities, or if {@code source} / {@code sink} indices are invalid */ public static int maxFlow(int[][] capacity, int source, int sink) { if (capacity == null || capacity.length == 0) { throw new IllegalArgumentException("Capacity matrix must not be null or empty"); } final int n = capacity.length; for (int row = 0; row < n; row++) { if (capacity[row] == null || capacity[row].length != n) { throw new IllegalArgumentException("Capacity matrix must be square"); } for (int col = 0; col < n; col++) { if (capacity[row][col] < 0) { throw new IllegalArgumentException("Capacities must be non-negative"); } } } if (source < 0 || source >= n || sink < 0 || sink >= n) { throw new IllegalArgumentException("Source and sink must be valid vertex indices"); } if (source == sink) { return 0; } final int[][] residual = new int[n][n]; for (int i = 0; i < n; i++) { residual[i] = Arrays.copyOf(capacity[i], n); } final int[] parent = new int[n]; int maxFlow = 0; while (bfs(residual, source, sink, parent)) { int pathFlow = Integer.MAX_VALUE; for (int v = sink; v != source; v = parent[v]) { int u = parent[v]; pathFlow = Math.min(pathFlow, residual[u][v]); } for (int v = sink; v != source; v = parent[v]) { int u = parent[v]; residual[u][v] -= pathFlow; residual[v][u] += pathFlow; } maxFlow += pathFlow; } return maxFlow; } private static boolean bfs(int[][] residual, int source, int sink, int[] parent) { Arrays.fill(parent, -1); parent[source] = source; Queue<Integer> queue = new ArrayDeque<>(); queue.add(source); while (!queue.isEmpty()) { int u = queue.poll(); for (int v = 0; v < residual.length; v++) { if (residual[u][v] > 0 && parent[v] == -1) { parent[v] = u; if (v == sink) { return true; } queue.add(v); } } } return false; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/GomoryHuTree.java
src/main/java/com/thealgorithms/graph/GomoryHuTree.java
package com.thealgorithms.graph; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; /** * Gomory–Hu tree construction for undirected graphs via n−1 max-flow computations. * * <p>API: {@code buildTree(int[][])} returns {@code {parent, weight}} arrays for the tree. * * @see <a href="https://en.wikipedia.org/wiki/Gomory%E2%80%93Hu_tree">Wikipedia: Gomory–Hu tree</a> */ public final class GomoryHuTree { private GomoryHuTree() { } public static int[][] buildTree(int[][] cap) { validateCapacityMatrix(cap); final int n = cap.length; if (n == 1) { return new int[][] {new int[] {-1}, new int[] {0}}; } int[] parent = new int[n]; int[] weight = new int[n]; Arrays.fill(parent, 0); parent[0] = -1; weight[0] = 0; for (int s = 1; s < n; s++) { int t = parent[s]; MaxFlowResult res = edmondsKarpWithMinCut(cap, s, t); int f = res.flow; weight[s] = f; for (int v = 0; v < n; v++) { if (v != s && parent[v] == t && res.reachable[v]) { parent[v] = s; } } if (t != 0 && res.reachable[parent[t]]) { parent[s] = parent[t]; parent[t] = s; weight[s] = weight[t]; weight[t] = f; } } return new int[][] {parent, weight}; } private static void validateCapacityMatrix(int[][] cap) { if (cap == null || cap.length == 0) { throw new IllegalArgumentException("Capacity matrix must not be null or empty"); } final int n = cap.length; for (int i = 0; i < n; i++) { if (cap[i] == null || cap[i].length != n) { throw new IllegalArgumentException("Capacity matrix must be square"); } for (int j = 0; j < n; j++) { if (cap[i][j] < 0) { throw new IllegalArgumentException("Capacities must be non-negative"); } } } } private static final class MaxFlowResult { final int flow; final boolean[] reachable; MaxFlowResult(int flow, boolean[] reachable) { this.flow = flow; this.reachable = reachable; } } private static MaxFlowResult edmondsKarpWithMinCut(int[][] capacity, int source, int sink) { final int n = capacity.length; int[][] residual = new int[n][n]; for (int i = 0; i < n; i++) { residual[i] = Arrays.copyOf(capacity[i], n); } int[] parent = new int[n]; int maxFlow = 0; while (bfs(residual, source, sink, parent)) { int pathFlow = Integer.MAX_VALUE; for (int v = sink; v != source; v = parent[v]) { int u = parent[v]; pathFlow = Math.min(pathFlow, residual[u][v]); } for (int v = sink; v != source; v = parent[v]) { int u = parent[v]; residual[u][v] -= pathFlow; residual[v][u] += pathFlow; } maxFlow += pathFlow; } boolean[] reachable = new boolean[n]; markReachable(residual, source, reachable); return new MaxFlowResult(maxFlow, reachable); } private static boolean bfs(int[][] residual, int source, int sink, int[] parent) { Arrays.fill(parent, -1); parent[source] = source; Queue<Integer> q = new ArrayDeque<>(); q.add(source); while (!q.isEmpty()) { int u = q.poll(); for (int v = 0; v < residual.length; v++) { if (residual[u][v] > 0 && parent[v] == -1) { parent[v] = u; if (v == sink) { return true; } q.add(v); } } } return false; } private static void markReachable(int[][] residual, int source, boolean[] vis) { Arrays.fill(vis, false); Queue<Integer> q = new ArrayDeque<>(); vis[source] = true; q.add(source); while (!q.isEmpty()) { int u = q.poll(); for (int v = 0; v < residual.length; v++) { if (!vis[v] && residual[u][v] > 0) { vis[v] = true; q.add(v); } } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/Dinic.java
src/main/java/com/thealgorithms/graph/Dinic.java
package com.thealgorithms.graph; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; /** * Dinic's algorithm for computing maximum flow in a directed graph. * * <p>Time complexity: O(E * V^2) in the worst case, but typically faster in practice * and near O(E * sqrt(V)) for unit networks.</p> * * <p>The graph is represented using a capacity matrix where capacity[u][v] is the * capacity of the directed edge u -> v. Capacities must be non-negative. * The algorithm builds level graphs using BFS and finds blocking flows using DFS * with current-edge optimization.</p> * * <p>This implementation mirrors the API and validation style of * {@link EdmondsKarp#maxFlow(int[][], int, int)} for consistency.</p> * * @see <a href="https://en.wikipedia.org/wiki/Dinic%27s_algorithm">Wikipedia: Dinic's algorithm</a> */ public final class Dinic { private Dinic() { } /** * Computes the maximum flow from source to sink using Dinic's algorithm. * * @param capacity square capacity matrix (n x n); entries must be >= 0 * @param source source vertex index in [0, n) * @param sink sink vertex index in [0, n) * @return the maximum flow value * @throws IllegalArgumentException if the input matrix is null/non-square/has negatives or * indices invalid */ public static int maxFlow(int[][] capacity, int source, int sink) { if (capacity == null || capacity.length == 0) { throw new IllegalArgumentException("Capacity matrix must not be null or empty"); } final int n = capacity.length; for (int i = 0; i < n; i++) { if (capacity[i] == null || capacity[i].length != n) { throw new IllegalArgumentException("Capacity matrix must be square"); } for (int j = 0; j < n; j++) { if (capacity[i][j] < 0) { throw new IllegalArgumentException("Capacities must be non-negative"); } } } if (source < 0 || sink < 0 || source >= n || sink >= n) { throw new IllegalArgumentException("Source and sink must be valid vertex indices"); } if (source == sink) { return 0; } // residual capacities int[][] residual = new int[n][n]; for (int i = 0; i < n; i++) { residual[i] = Arrays.copyOf(capacity[i], n); } int[] level = new int[n]; int flow = 0; while (bfsBuildLevelGraph(residual, source, sink, level)) { int[] next = new int[n]; // current-edge optimization int pushed; do { pushed = dfsBlocking(residual, level, next, source, sink, Integer.MAX_VALUE); flow += pushed; } while (pushed > 0); } return flow; } private static boolean bfsBuildLevelGraph(int[][] residual, int source, int sink, int[] level) { Arrays.fill(level, -1); level[source] = 0; Queue<Integer> q = new ArrayDeque<>(); q.add(source); while (!q.isEmpty()) { int u = q.poll(); for (int v = 0; v < residual.length; v++) { if (residual[u][v] > 0 && level[v] == -1) { level[v] = level[u] + 1; if (v == sink) { return true; } q.add(v); } } } return level[sink] != -1; } private static int dfsBlocking(int[][] residual, int[] level, int[] next, int u, int sink, int f) { if (u == sink) { return f; } final int n = residual.length; for (int v = next[u]; v < n; v++, next[u] = v) { if (residual[u][v] <= 0) { continue; } if (level[v] != level[u] + 1) { continue; } int pushed = dfsBlocking(residual, level, next, v, sink, Math.min(f, residual[u][v])); if (pushed > 0) { residual[u][v] -= pushed; residual[v][u] += pushed; return pushed; } } return 0; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/StoerWagner.java
src/main/java/com/thealgorithms/graph/StoerWagner.java
package com.thealgorithms.graph; /** * An implementation of the Stoer-Wagner algorithm to find the global minimum cut of an undirected, weighted graph. * A minimum cut is a partition of the graph's vertices into two disjoint sets with the minimum possible edge weight * sum connecting the two sets. * * Wikipedia: https://en.wikipedia.org/wiki/Stoer%E2%80%93Wagner_algorithm * Time Complexity: O(V^3) where V is the number of vertices. */ public class StoerWagner { /** * Finds the minimum cut in the given undirected, weighted graph. * * @param graph An adjacency matrix representing the graph. graph[i][j] is the weight of the edge between i and j. * @return The weight of the minimum cut. */ public int findMinCut(int[][] graph) { int n = graph.length; if (n < 2) { return 0; } int[][] currentGraph = new int[n][n]; for (int i = 0; i < n; i++) { System.arraycopy(graph[i], 0, currentGraph[i], 0, n); } int minCut = Integer.MAX_VALUE; boolean[] merged = new boolean[n]; for (int phase = 0; phase < n - 1; phase++) { boolean[] inSetA = new boolean[n]; int[] weights = new int[n]; int prev = -1; int last = -1; for (int i = 0; i < n - phase; i++) { int maxWeight = -1; int currentVertex = -1; for (int j = 0; j < n; j++) { if (!merged[j] && !inSetA[j] && weights[j] > maxWeight) { maxWeight = weights[j]; currentVertex = j; } } if (currentVertex == -1) { // This can happen if the graph is disconnected. return 0; } prev = last; last = currentVertex; inSetA[last] = true; for (int j = 0; j < n; j++) { if (!merged[j] && !inSetA[j]) { weights[j] += currentGraph[last][j]; } } } minCut = Math.min(minCut, weights[last]); // Merge 'last' vertex into 'prev' vertex for (int i = 0; i < n; i++) { currentGraph[prev][i] += currentGraph[last][i]; currentGraph[i][prev] = currentGraph[prev][i]; } merged[last] = true; } return minCut; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/HungarianAlgorithm.java
src/main/java/com/thealgorithms/graph/HungarianAlgorithm.java
package com.thealgorithms.graph; import java.util.Arrays; /** * Hungarian algorithm (a.k.a. Kuhn–Munkres) for the Assignment Problem. * * <p>Given an n x m cost matrix (n tasks, m workers), finds a minimum-cost * one-to-one assignment. If the matrix is rectangular, the algorithm pads to a * square internally. Costs must be finite non-negative integers. * * <p>Time complexity: O(n^3) with n = max(rows, cols). * * <p>API returns the assignment as an array where {@code assignment[i]} is the * column chosen for row i (or -1 if unassigned when rows != cols), and a total * minimal cost. * * @see <a href="https://en.wikipedia.org/wiki/Hungarian_algorithm">Wikipedia: Hungarian algorithm</a> */ public final class HungarianAlgorithm { private HungarianAlgorithm() { } /** Result holder for the Hungarian algorithm. */ public static final class Result { public final int[] assignment; // assignment[row] = col or -1 public final int minCost; public Result(int[] assignment, int minCost) { this.assignment = assignment; this.minCost = minCost; } } /** * Solves the assignment problem for a non-negative cost matrix. * * @param cost an r x c matrix of non-negative costs * @return Result with row-to-column assignment and minimal total cost * @throws IllegalArgumentException for null/empty or negative costs */ public static Result solve(int[][] cost) { validate(cost); int rows = cost.length; int cols = cost[0].length; int n = Math.max(rows, cols); // Build square matrix with padding 0 for missing cells int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { if (i < rows) { for (int j = 0; j < n; j++) { a[i][j] = (j < cols) ? cost[i][j] : 0; } } else { Arrays.fill(a[i], 0); } } // Potentials and matching arrays int[] u = new int[n + 1]; int[] v = new int[n + 1]; int[] p = new int[n + 1]; int[] way = new int[n + 1]; for (int i = 1; i <= n; i++) { p[0] = i; int j0 = 0; int[] minv = new int[n + 1]; boolean[] used = new boolean[n + 1]; Arrays.fill(minv, Integer.MAX_VALUE); Arrays.fill(used, false); do { used[j0] = true; int i0 = p[j0]; int delta = Integer.MAX_VALUE; int j1 = 0; for (int j = 1; j <= n; j++) { if (!used[j]) { int cur = a[i0 - 1][j - 1] - u[i0] - v[j]; if (cur < minv[j]) { minv[j] = cur; way[j] = j0; } if (minv[j] < delta) { delta = minv[j]; j1 = j; } } } for (int j = 0; j <= n; j++) { if (used[j]) { u[p[j]] += delta; v[j] -= delta; } else { minv[j] -= delta; } } j0 = j1; } while (p[j0] != 0); do { int j1 = way[j0]; p[j0] = p[j1]; j0 = j1; } while (j0 != 0); } int[] matchColForRow = new int[n]; Arrays.fill(matchColForRow, -1); for (int j = 1; j <= n; j++) { if (p[j] != 0) { matchColForRow[p[j] - 1] = j - 1; } } // Build assignment for original rows only, ignore padded rows int[] assignment = new int[rows]; Arrays.fill(assignment, -1); int total = 0; for (int i = 0; i < rows; i++) { int j = matchColForRow[i]; if (j >= 0 && j < cols) { assignment[i] = j; total += cost[i][j]; } } return new Result(assignment, total); } private static void validate(int[][] cost) { if (cost == null || cost.length == 0) { throw new IllegalArgumentException("Cost matrix must not be null or empty"); } int c = cost[0].length; if (c == 0) { throw new IllegalArgumentException("Cost matrix must have at least 1 column"); } for (int i = 0; i < cost.length; i++) { if (cost[i] == null || cost[i].length != c) { throw new IllegalArgumentException("Cost matrix must be rectangular with equal row lengths"); } for (int j = 0; j < c; j++) { if (cost[i][j] < 0) { throw new IllegalArgumentException("Costs must be non-negative"); } } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/BronKerbosch.java
src/main/java/com/thealgorithms/graph/BronKerbosch.java
package com.thealgorithms.graph; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Implementation of the Bron–Kerbosch algorithm with pivoting for enumerating all maximal cliques * in an undirected graph. * * <p>The input graph is represented as an adjacency list where {@code adjacency.get(u)} returns the * set of vertices adjacent to {@code u}. The algorithm runs in time proportional to the number of * maximal cliques produced and is widely used for clique enumeration problems.</p> * * @author <a href="https://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm">Wikipedia: Bron–Kerbosch algorithm</a> */ public final class BronKerbosch { private BronKerbosch() { } /** * Finds all maximal cliques of the provided graph. * * @param adjacency adjacency list where {@code adjacency.size()} equals the number of vertices * @return a list containing every maximal clique, each represented as a {@link Set} of vertices * @throws IllegalArgumentException if the adjacency list is {@code null}, contains {@code null} * entries, or references invalid vertices */ public static List<Set<Integer>> findMaximalCliques(List<Set<Integer>> adjacency) { if (adjacency == null) { throw new IllegalArgumentException("Adjacency list must not be null"); } int n = adjacency.size(); List<Set<Integer>> graph = new ArrayList<>(n); for (int u = 0; u < n; u++) { Set<Integer> neighbors = adjacency.get(u); if (neighbors == null) { throw new IllegalArgumentException("Adjacency list must not contain null sets"); } Set<Integer> copy = new HashSet<>(); for (int v : neighbors) { if (v < 0 || v >= n) { throw new IllegalArgumentException("Neighbor index out of bounds: " + v); } if (v != u) { copy.add(v); } } graph.add(copy); } Set<Integer> r = new HashSet<>(); Set<Integer> p = new HashSet<>(); Set<Integer> x = new HashSet<>(); for (int v = 0; v < n; v++) { p.add(v); } List<Set<Integer>> cliques = new ArrayList<>(); bronKerboschPivot(r, p, x, graph, cliques); return cliques; } private static void bronKerboschPivot(Set<Integer> r, Set<Integer> p, Set<Integer> x, List<Set<Integer>> graph, List<Set<Integer>> cliques) { if (p.isEmpty() && x.isEmpty()) { cliques.add(new HashSet<>(r)); return; } int pivot = choosePivot(p, x, graph); Set<Integer> candidates = new HashSet<>(p); if (pivot != -1) { candidates.removeAll(graph.get(pivot)); } for (Integer v : candidates) { r.add(v); Set<Integer> newP = intersection(p, graph.get(v)); Set<Integer> newX = intersection(x, graph.get(v)); bronKerboschPivot(r, newP, newX, graph, cliques); r.remove(v); p.remove(v); x.add(v); } } private static int choosePivot(Set<Integer> p, Set<Integer> x, List<Set<Integer>> graph) { int pivot = -1; int maxDegree = -1; Set<Integer> union = new HashSet<>(p); union.addAll(x); for (Integer v : union) { int degree = graph.get(v).size(); if (degree > maxDegree) { maxDegree = degree; pivot = v; } } return pivot; } private static Set<Integer> intersection(Set<Integer> base, Set<Integer> neighbors) { Set<Integer> result = new HashSet<>(); for (Integer v : base) { if (neighbors.contains(v)) { result.add(v); } } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/TravelingSalesman.java
src/main/java/com/thealgorithms/graph/TravelingSalesman.java
package com.thealgorithms.graph; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * This class provides solutions to the Traveling Salesman Problem (TSP) using both brute-force and dynamic programming approaches. * For more information, see <a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem">Wikipedia</a>. * @author <a href="https://github.com/DenizAltunkapan">Deniz Altunkapan</a> */ public final class TravelingSalesman { // Private constructor to prevent instantiation private TravelingSalesman() { } /** * Solves the Traveling Salesman Problem (TSP) using brute-force approach. * This method generates all possible permutations of cities, calculates the total distance for each route, and returns the shortest distance found. * * @param distanceMatrix A square matrix where element [i][j] represents the distance from city i to city j. * @return The shortest possible route distance visiting all cities exactly once and returning to the starting city. */ public static int bruteForce(int[][] distanceMatrix) { if (distanceMatrix.length <= 1) { return 0; } List<Integer> cities = new ArrayList<>(); for (int i = 1; i < distanceMatrix.length; i++) { cities.add(i); } List<List<Integer>> permutations = generatePermutations(cities); int minDistance = Integer.MAX_VALUE; for (List<Integer> permutation : permutations) { List<Integer> route = new ArrayList<>(); route.add(0); route.addAll(permutation); int currentDistance = calculateDistance(distanceMatrix, route); if (currentDistance < minDistance) { minDistance = currentDistance; } } return minDistance; } /** * Computes the total distance of a given route. * * @param distanceMatrix A square matrix where element [i][j] represents the * distance from city i to city j. * @param route A list representing the order in which the cities are visited. * @return The total distance of the route, or Integer.MAX_VALUE if the route is invalid. */ public static int calculateDistance(int[][] distanceMatrix, List<Integer> route) { int distance = 0; for (int i = 0; i < route.size() - 1; i++) { int d = distanceMatrix[route.get(i)][route.get(i + 1)]; if (d == Integer.MAX_VALUE) { return Integer.MAX_VALUE; } distance += d; } int returnDist = distanceMatrix[route.get(route.size() - 1)][route.get(0)]; return (returnDist == Integer.MAX_VALUE) ? Integer.MAX_VALUE : distance + returnDist; } /** * Generates all permutations of a given list of cities. * * @param cities A list of cities to permute. * @return A list of all possible permutations. */ private static List<List<Integer>> generatePermutations(List<Integer> cities) { List<List<Integer>> permutations = new ArrayList<>(); permute(cities, 0, permutations); return permutations; } /** * Recursively generates permutations using backtracking. * * @param arr The list of cities. * @param k The current index in the permutation process. * @param output The list to store generated permutations. */ private static void permute(List<Integer> arr, int k, List<List<Integer>> output) { if (k == arr.size()) { output.add(new ArrayList<>(arr)); return; } for (int i = k; i < arr.size(); i++) { Collections.swap(arr, i, k); permute(arr, k + 1, output); Collections.swap(arr, i, k); } } /** * Solves the Traveling Salesman Problem (TSP) using dynamic programming with the Held-Karp algorithm. * * @param distanceMatrix A square matrix where element [i][j] represents the distance from city i to city j. * @return The shortest possible route distance visiting all cities exactly once and returning to the starting city. * @throws IllegalArgumentException if the input matrix is not square. */ public static int dynamicProgramming(int[][] distanceMatrix) { if (distanceMatrix.length == 0) { return 0; } int n = distanceMatrix.length; for (int[] row : distanceMatrix) { if (row.length != n) { throw new IllegalArgumentException("Matrix must be square"); } } int[][] dp = new int[n][1 << n]; for (int[] row : dp) { Arrays.fill(row, Integer.MAX_VALUE); } dp[0][1] = 0; for (int mask = 1; mask < (1 << n); mask++) { for (int u = 0; u < n; u++) { if ((mask & (1 << u)) == 0 || dp[u][mask] == Integer.MAX_VALUE) { continue; } for (int v = 0; v < n; v++) { if ((mask & (1 << v)) != 0 || distanceMatrix[u][v] == Integer.MAX_VALUE) { continue; } int newMask = mask | (1 << v); dp[v][newMask] = Math.min(dp[v][newMask], dp[u][mask] + distanceMatrix[u][v]); } } } int minDistance = Integer.MAX_VALUE; int fullMask = (1 << n) - 1; for (int i = 1; i < n; i++) { if (dp[i][fullMask] != Integer.MAX_VALUE && distanceMatrix[i][0] != Integer.MAX_VALUE) { minDistance = Math.min(minDistance, dp[i][fullMask] + distanceMatrix[i][0]); } } return minDistance == Integer.MAX_VALUE ? 0 : minDistance; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/Edmonds.java
src/main/java/com/thealgorithms/graph/Edmonds.java
package com.thealgorithms.graph; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * An implementation of Edmonds's algorithm (also known as the Chu–Liu/Edmonds algorithm) * for finding a Minimum Spanning Arborescence (MSA). * * <p>An MSA is a directed graph equivalent of a Minimum Spanning Tree. It is a tree rooted * at a specific vertex 'r' that reaches all other vertices, such that the sum of the * weights of its edges is minimized. * * <p>The algorithm works recursively: * <ol> * <li>For each vertex other than the root, select the incoming edge with the minimum weight.</li> * <li>If the selected edges form a spanning arborescence, it is the MSA.</li> * <li>If cycles are formed, contract each cycle into a new "supernode".</li> * <li>Modify the weights of edges entering the new supernode.</li> * <li>Recursively call the algorithm on the contracted graph.</li> * <li>The final cost is the sum of the initial edge selections and the result of the recursive call.</li> * </ol> * * <p>Time Complexity: O(E * V) where E is the number of edges and V is the number of vertices. * * <p>References: * <ul> * <li><a href="https://en.wikipedia.org/wiki/Edmonds%27_algorithm">Wikipedia: Edmonds's algorithm</a></li> * </ul> */ public final class Edmonds { private Edmonds() { } /** * Represents a directed weighted edge in the graph. */ public static class Edge { final int from; final int to; final long weight; /** * Constructs a directed edge. * * @param from source vertex * @param to destination vertex * @param weight edge weight */ public Edge(int from, int to, long weight) { this.from = from; this.to = to; this.weight = weight; } } /** * Computes the total weight of the Minimum Spanning Arborescence of a directed, * weighted graph from a given root. * * @param numVertices the number of vertices, labeled {@code 0..numVertices-1} * @param edges list of directed edges in the graph * @param root the root vertex * @return the total weight of the MSA. Returns -1 if not all vertices are reachable * from the root or if a valid arborescence cannot be formed. * @throws IllegalArgumentException if {@code numVertices <= 0} or {@code root} is out of range. */ public static long findMinimumSpanningArborescence(int numVertices, List<Edge> edges, int root) { if (root < 0 || root >= numVertices) { throw new IllegalArgumentException("Invalid number of vertices or root"); } if (numVertices == 1) { return 0; } return findMSARecursive(numVertices, edges, root); } /** * Recursive helper method for finding MSA. */ private static long findMSARecursive(int n, List<Edge> edges, int root) { long[] minWeightEdge = new long[n]; int[] predecessor = new int[n]; Arrays.fill(minWeightEdge, Long.MAX_VALUE); Arrays.fill(predecessor, -1); for (Edge edge : edges) { if (edge.to != root && edge.weight < minWeightEdge[edge.to]) { minWeightEdge[edge.to] = edge.weight; predecessor[edge.to] = edge.from; } } // Check if all non-root nodes are reachable for (int i = 0; i < n; i++) { if (i != root && minWeightEdge[i] == Long.MAX_VALUE) { return -1; // No spanning arborescence exists } } int[] cycleId = new int[n]; Arrays.fill(cycleId, -1); boolean[] visited = new boolean[n]; int cycleCount = 0; for (int i = 0; i < n; i++) { if (visited[i]) { continue; } List<Integer> path = new ArrayList<>(); int curr = i; // Follow predecessor chain while (curr != -1 && !visited[curr]) { visited[curr] = true; path.add(curr); curr = predecessor[curr]; } // If we hit a visited node, check if it forms a cycle if (curr != -1) { boolean inCycle = false; for (int node : path) { if (node == curr) { inCycle = true; } if (inCycle) { cycleId[node] = cycleCount; } } if (inCycle) { cycleCount++; } } } if (cycleCount == 0) { long totalWeight = 0; for (int i = 0; i < n; i++) { if (i != root) { totalWeight += minWeightEdge[i]; } } return totalWeight; } long cycleWeightSum = 0; for (int i = 0; i < n; i++) { if (cycleId[i] >= 0) { cycleWeightSum += minWeightEdge[i]; } } // Map old nodes to new nodes (cycles become supernodes) int[] newNodeMap = new int[n]; int[] cycleToNewNode = new int[cycleCount]; int newN = 0; // Assign new node IDs to cycles first for (int i = 0; i < cycleCount; i++) { cycleToNewNode[i] = newN++; } // Assign new node IDs to non-cycle nodes for (int i = 0; i < n; i++) { if (cycleId[i] == -1) { newNodeMap[i] = newN++; } else { newNodeMap[i] = cycleToNewNode[cycleId[i]]; } } int newRoot = newNodeMap[root]; // Build contracted graph List<Edge> newEdges = new ArrayList<>(); for (Edge edge : edges) { int uCycleId = cycleId[edge.from]; int vCycleId = cycleId[edge.to]; // Skip edges internal to a cycle if (uCycleId >= 0 && uCycleId == vCycleId) { continue; } int newU = newNodeMap[edge.from]; int newV = newNodeMap[edge.to]; long newWeight = edge.weight; // Adjust weight for edges entering a cycle if (vCycleId >= 0) { newWeight -= minWeightEdge[edge.to]; } if (newU != newV) { newEdges.add(new Edge(newU, newV, newWeight)); } } return cycleWeightSum + findMSARecursive(newN, newEdges, newRoot); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/PredecessorConstrainedDfs.java
src/main/java/com/thealgorithms/graph/PredecessorConstrainedDfs.java
package com.thealgorithms.graph; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * DFS that visits a successor only when all its predecessors are already visited, * emitting VISIT and SKIP events. * <p> * This class includes a DFS variant that visits a successor only when all of its * predecessors have already been visited * </p> * <p>Related reading: * <ul> * <li><a href="https://en.wikipedia.org/wiki/Topological_sorting">Topological sorting</a></li> * <li><a href="https://en.wikipedia.org/wiki/Depth-first_search">Depth-first search</a></li> * </ul> * </p> */ public final class PredecessorConstrainedDfs { private PredecessorConstrainedDfs() { // utility class } /** An event emitted by the traversal: either a VISIT with an order, or a SKIP with a note. */ public record TraversalEvent<T>(T node, Integer order, // non-null for visit, null for skip String note // non-null for skip, null for visit ) { public TraversalEvent { Objects.requireNonNull(node); // order and note can be null based on event type } /** A visit event with an increasing order (0,1,2,...) */ public static <T> TraversalEvent<T> visit(T node, int order) { return new TraversalEvent<>(node, order, null); } /** A skip event with an explanatory note (e.g., not all parents visited yet). */ public static <T> TraversalEvent<T> skip(T node, String note) { return new TraversalEvent<>(node, null, Objects.requireNonNull(note)); } public boolean isVisit() { return order != null; } public boolean isSkip() { return order == null; } @Override public String toString() { return isVisit() ? "VISIT(" + node + ", order=" + order + ")" : "SKIP(" + node + ", " + note + ")"; } } /** * DFS (recursive) that records the order of first visit starting at {@code start}, * but only recurses to a child when <b>all</b> its predecessors have been visited. * If a child is encountered early (some parent unvisited), a SKIP event is recorded. * * <p>Equivalent idea to the Python pseudo in the user's description (with successors and predecessors), * but implemented in Java and returning a sequence of {@link TraversalEvent}s.</p> * * @param successors adjacency list: for each node, its outgoing neighbors * @param start start node * @return immutable list of traversal events (VISITs with monotonically increasing order and SKIPs with messages) * @throws IllegalArgumentException if {@code successors} is null */ public static <T> List<TraversalEvent<T>> dfsRecursiveOrder(Map<T, List<T>> successors, T start) { if (successors == null) { throw new IllegalArgumentException("successors must not be null"); } // derive predecessors once Map<T, List<T>> predecessors = derivePredecessors(successors); return dfsRecursiveOrder(successors, predecessors, start); } /** * Same as {@link #dfsRecursiveOrder(Map, Object)} but with an explicit predecessors map. */ public static <T> List<TraversalEvent<T>> dfsRecursiveOrder(Map<T, List<T>> successors, Map<T, List<T>> predecessors, T start) { if (successors == null || predecessors == null) { throw new IllegalArgumentException("successors and predecessors must not be null"); } if (start == null) { return List.of(); } if (!successors.containsKey(start) && !appearsAnywhere(successors, start)) { return List.of(); // start not present in graph } List<TraversalEvent<T>> events = new ArrayList<>(); Set<T> visited = new HashSet<>(); int[] order = {0}; dfs(start, successors, predecessors, visited, order, events); return Collections.unmodifiableList(events); } private static <T> void dfs(T currentNode, Map<T, List<T>> successors, Map<T, List<T>> predecessors, Set<T> visited, int[] order, List<TraversalEvent<T>> result) { if (!visited.add(currentNode)) { return; // already visited } result.add(TraversalEvent.visit(currentNode, order[0]++)); // record visit and increment for (T childNode : successors.getOrDefault(currentNode, List.of())) { if (visited.contains(childNode)) { continue; } if (allParentsVisited(childNode, visited, predecessors)) { dfs(childNode, successors, predecessors, visited, order, result); } else { result.add(TraversalEvent.skip(childNode, "⛔ Skipping " + childNode + ": not all parents are visited yet.")); // do not mark visited; it may be visited later from another parent } } } private static <T> boolean allParentsVisited(T node, Set<T> visited, Map<T, List<T>> predecessors) { for (T parent : predecessors.getOrDefault(node, List.of())) { if (!visited.contains(parent)) { return false; } } return true; } private static <T> boolean appearsAnywhere(Map<T, List<T>> successors, T node) { if (successors.containsKey(node)) { return true; } for (List<T> neighbours : successors.values()) { if (neighbours != null && neighbours.contains(node)) { return true; } } return false; } private static <T> Map<T, List<T>> derivePredecessors(Map<T, List<T>> successors) { Map<T, List<T>> predecessors = new HashMap<>(); // ensure keys exist for all nodes appearing anywhere for (Map.Entry<T, List<T>> entry : successors.entrySet()) { predecessors.computeIfAbsent(entry.getKey(), key -> new ArrayList<>()); for (T childNode : entry.getValue()) { predecessors.computeIfAbsent(childNode, key -> new ArrayList<>()).add(entry.getKey()); } } return predecessors; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/PushRelabel.java
src/main/java/com/thealgorithms/graph/PushRelabel.java
package com.thealgorithms.graph; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; /** * Push–Relabel (Relabel-to-Front variant simplified to array scanning) for maximum flow. * * <p>Input graph is a capacity matrix where {@code capacity[u][v]} is the capacity of the edge * {@code u -> v}. Capacities must be non-negative. Vertices are indexed in {@code [0, n)}. * * <p>Time complexity: O(V^3) in the worst case for the array-based variant; typically fast in * practice. This implementation uses a residual network over an adjacency-matrix representation. * * <p>The API mirrors {@link EdmondsKarp#maxFlow(int[][], int, int)} and {@link Dinic#maxFlow(int[][], int, int)}. * * @see <a href="https://en.wikipedia.org/wiki/Push%E2%80%93relabel_maximum_flow_algorithm">Wikipedia: Push–Relabel maximum flow algorithm</a> */ public final class PushRelabel { private PushRelabel() { } /** * Computes the maximum flow from {@code source} to {@code sink} using Push–Relabel. * * @param capacity square capacity matrix (n x n); entries must be >= 0 * @param source source vertex index in [0, n) * @param sink sink vertex index in [0, n) * @return the maximum flow value * @throws IllegalArgumentException if inputs are invalid */ public static int maxFlow(int[][] capacity, int source, int sink) { validate(capacity, source, sink); final int n = capacity.length; if (source == sink) { return 0; } int[][] residual = new int[n][n]; for (int i = 0; i < n; i++) { residual[i] = Arrays.copyOf(capacity[i], n); } int[] height = new int[n]; int[] excess = new int[n]; int[] nextNeighbor = new int[n]; // Preflow initialization height[source] = n; for (int v = 0; v < n; v++) { int cap = residual[source][v]; if (cap > 0) { residual[source][v] -= cap; residual[v][source] += cap; excess[v] += cap; excess[source] -= cap; } } // Active queue contains vertices (except source/sink) with positive excess Queue<Integer> active = new ArrayDeque<>(); for (int v = 0; v < n; v++) { if (v != source && v != sink && excess[v] > 0) { active.add(v); } } State state = new State(residual, height, excess, nextNeighbor, source, sink, active); while (!active.isEmpty()) { int u = active.poll(); discharge(u, state); if (excess[u] > 0) { // still active after discharge; push to back active.add(u); } } // Total flow equals excess at sink return excess[sink]; } private static void discharge(int u, State s) { final int n = s.residual.length; while (s.excess[u] > 0) { if (s.nextNeighbor[u] >= n) { relabel(u, s.residual, s.height); s.nextNeighbor[u] = 0; continue; } int v = s.nextNeighbor[u]; if (s.residual[u][v] > 0 && s.height[u] == s.height[v] + 1) { int delta = Math.min(s.excess[u], s.residual[u][v]); s.residual[u][v] -= delta; s.residual[v][u] += delta; s.excess[u] -= delta; int prevExcessV = s.excess[v]; s.excess[v] += delta; if (v != s.source && v != s.sink && prevExcessV == 0) { s.active.add(v); } } else { s.nextNeighbor[u]++; } } } private static final class State { final int[][] residual; final int[] height; final int[] excess; final int[] nextNeighbor; final int source; final int sink; final Queue<Integer> active; State(int[][] residual, int[] height, int[] excess, int[] nextNeighbor, int source, int sink, Queue<Integer> active) { this.residual = residual; this.height = height; this.excess = excess; this.nextNeighbor = nextNeighbor; this.source = source; this.sink = sink; this.active = active; } } private static void relabel(int u, int[][] residual, int[] height) { final int n = residual.length; int minHeight = Integer.MAX_VALUE; for (int v = 0; v < n; v++) { if (residual[u][v] > 0) { minHeight = Math.min(minHeight, height[v]); } } if (minHeight < Integer.MAX_VALUE) { height[u] = minHeight + 1; } } private static void validate(int[][] capacity, int source, int sink) { if (capacity == null || capacity.length == 0) { throw new IllegalArgumentException("Capacity matrix must not be null or empty"); } int n = capacity.length; for (int i = 0; i < n; i++) { if (capacity[i] == null || capacity[i].length != n) { throw new IllegalArgumentException("Capacity matrix must be square"); } for (int j = 0; j < n; j++) { if (capacity[i][j] < 0) { throw new IllegalArgumentException("Capacities must be non-negative"); } } } if (source < 0 || sink < 0 || source >= n || sink >= n) { throw new IllegalArgumentException("Source and sink must be valid vertex indices"); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java
src/main/java/com/thealgorithms/graph/StronglyConnectedComponentOptimized.java
package com.thealgorithms.graph; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Stack; /** * Finds the strongly connected components in a directed graph. * * @param adjList The adjacency list representation of the graph. * @param n The number of nodes in the graph. * @return The number of strongly connected components. */ public class StronglyConnectedComponentOptimized { public void btrack(HashMap<Integer, List<Integer>> adjList, int[] visited, Stack<Integer> dfsCallsNodes, int currentNode) { visited[currentNode] = 1; List<Integer> neighbors = adjList.get(currentNode); // Check for null before iterating if (neighbors != null) { for (int neighbor : neighbors) { if (visited[neighbor] == -1) { btrack(adjList, visited, dfsCallsNodes, neighbor); } } } dfsCallsNodes.add(currentNode); } public void btrack2(HashMap<Integer, List<Integer>> adjRevList, int[] visited, int currentNode, List<Integer> newScc) { visited[currentNode] = 1; newScc.add(currentNode); List<Integer> neighbors = adjRevList.get(currentNode); // Check for null before iterating if (neighbors != null) { for (int neighbor : neighbors) { if (visited[neighbor] == -1) { btrack2(adjRevList, visited, neighbor, newScc); } } } } public int getOutput(HashMap<Integer, List<Integer>> adjList, int n) { int[] visited = new int[n]; Arrays.fill(visited, -1); Stack<Integer> dfsCallsNodes = new Stack<>(); for (int i = 0; i < n; i++) { if (visited[i] == -1) { btrack(adjList, visited, dfsCallsNodes, i); } } HashMap<Integer, List<Integer>> adjRevList = new HashMap<>(); for (int i = 0; i < n; i++) { adjRevList.put(i, new ArrayList<>()); } for (int i = 0; i < n; i++) { List<Integer> neighbors = adjList.get(i); // Check for null before iterating if (neighbors != null) { for (int neighbor : neighbors) { adjRevList.get(neighbor).add(i); } } } Arrays.fill(visited, -1); int stronglyConnectedComponents = 0; while (!dfsCallsNodes.isEmpty()) { int node = dfsCallsNodes.pop(); if (visited[node] == -1) { List<Integer> newScc = new ArrayList<>(); btrack2(adjRevList, visited, node, newScc); stronglyConnectedComponents++; } } return stronglyConnectedComponents; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/HierholzerEulerianPath.java
src/main/java/com/thealgorithms/graph/HierholzerEulerianPath.java
package com.thealgorithms.graph; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; /** * Implementation of Hierholzer's Algorithm for finding an Eulerian Path or Circuit * in a directed graph. * * <p> * An <b>Eulerian Circuit</b> is a path that starts and ends at the same vertex * and visits every edge exactly once. * </p> * * <p> * An <b>Eulerian Path</b> visits every edge exactly once but may start and end * at different vertices. * </p> * * <p> * <b>Algorithm Summary:</b><br> * 1. Compute indegree and outdegree for all vertices.<br> * 2. Check if the graph satisfies Eulerian path or circuit conditions.<br> * 3. Verify that all vertices with non-zero degree are weakly connected (undirected connectivity).<br> * 4. Use Hierholzer’s algorithm to build the path by exploring unused edges iteratively. * </p> * * <p> * <b>Time Complexity:</b> O(E + V).<br> * <b>Space Complexity:</b> O(V + E). * </p> * * @author <a href="https://en.wikipedia.org/wiki/Eulerian_path#Hierholzer's_algorithm">Wikipedia: Hierholzer algorithm</a> */ public class HierholzerEulerianPath { /** * Simple directed graph represented by adjacency lists. */ public static class Graph { private final List<List<Integer>> adjacencyList; /** * Constructs a graph with a given number of vertices. * * @param numNodes number of vertices */ public Graph(int numNodes) { adjacencyList = new ArrayList<>(); for (int i = 0; i < numNodes; i++) { adjacencyList.add(new ArrayList<>()); } } /** * Adds a directed edge from vertex {@code from} to vertex {@code to}. * * @param from source vertex * @param to destination vertex */ public void addEdge(int from, int to) { adjacencyList.get(from).add(to); } /** * Returns a list of outgoing edges from the given vertex. * * @param node vertex index * @return list of destination vertices */ public List<Integer> getEdges(int node) { return adjacencyList.get(node); } /** * Returns the number of vertices in the graph. * * @return number of vertices */ public int getNumNodes() { return adjacencyList.size(); } } private final Graph graph; /** * Creates a Hierholzer solver for the given graph. * * @param graph directed graph */ public HierholzerEulerianPath(Graph graph) { this.graph = graph; } /** * Finds an Eulerian Path or Circuit using Hierholzer’s Algorithm. * * @return list of vertices representing the Eulerian Path/Circuit, * or an empty list if none exists */ public List<Integer> findEulerianPath() { int n = graph.getNumNodes(); // empty graph -> no path if (n == 0) { return new ArrayList<>(); } int[] inDegree = new int[n]; int[] outDegree = new int[n]; int edgeCount = computeDegrees(inDegree, outDegree); // no edges -> single vertex response requested by tests: [0] if (edgeCount == 0) { return Collections.singletonList(0); } int startNode = determineStartNode(inDegree, outDegree); if (startNode == -1) { return new ArrayList<>(); } if (!allNonZeroDegreeVerticesWeaklyConnected(startNode, n, outDegree, inDegree)) { return new ArrayList<>(); } List<Integer> path = buildHierholzerPath(startNode, n); if (path.size() != edgeCount + 1) { return new ArrayList<>(); } return rotateEulerianCircuitIfNeeded(path, outDegree, inDegree); } private int computeDegrees(int[] inDegree, int[] outDegree) { int edgeCount = 0; for (int u = 0; u < graph.getNumNodes(); u++) { for (int v : graph.getEdges(u)) { outDegree[u]++; inDegree[v]++; edgeCount++; } } return edgeCount; } private int determineStartNode(int[] inDegree, int[] outDegree) { int n = graph.getNumNodes(); int startNode = -1; int startCount = 0; int endCount = 0; for (int i = 0; i < n; i++) { int diff = outDegree[i] - inDegree[i]; if (diff == 1) { startNode = i; startCount++; } else if (diff == -1) { endCount++; } else if (Math.abs(diff) > 1) { return -1; } } if (!((startCount == 1 && endCount == 1) || (startCount == 0 && endCount == 0))) { return -1; } if (startNode == -1) { for (int i = 0; i < n; i++) { if (outDegree[i] > 0) { startNode = i; break; } } } return startNode; } private List<Integer> buildHierholzerPath(int startNode, int n) { List<Deque<Integer>> tempAdj = new ArrayList<>(); for (int i = 0; i < n; i++) { tempAdj.add(new ArrayDeque<>(graph.getEdges(i))); } Deque<Integer> stack = new ArrayDeque<>(); List<Integer> path = new ArrayList<>(); stack.push(startNode); while (!stack.isEmpty()) { int u = stack.peek(); if (!tempAdj.get(u).isEmpty()) { stack.push(tempAdj.get(u).pollFirst()); } else { path.add(stack.pop()); } } Collections.reverse(path); return path; } private List<Integer> rotateEulerianCircuitIfNeeded(List<Integer> path, int[] outDegree, int[] inDegree) { int startCount = 0; int endCount = 0; for (int i = 0; i < outDegree.length; i++) { int diff = outDegree[i] - inDegree[i]; if (diff == 1) { startCount++; } else if (diff == -1) { endCount++; } } if (startCount == 0 && endCount == 0 && !path.isEmpty()) { int preferredStart = -1; for (int i = 0; i < outDegree.length; i++) { if (outDegree[i] > 0) { preferredStart = i; break; } } if (preferredStart != -1 && path.get(0) != preferredStart) { int idx = 0; for (Integer node : path) { // replaced indexed loop if (node == preferredStart) { break; } idx++; } if (idx > 0) { List<Integer> rotated = new ArrayList<>(); int currentIndex = 0; for (Integer node : path) { // replaced indexed loop if (currentIndex >= idx) { rotated.add(node); } currentIndex++; } currentIndex = 0; for (Integer node : path) { // replaced indexed loop if (currentIndex < idx) { rotated.add(node); } currentIndex++; } path = rotated; } } } return path; } /** * Checks weak connectivity (undirected) among vertices that have non-zero degree. * * @param startNode node to start DFS from (must be a vertex with non-zero degree) * @param n number of vertices * @param outDegree out-degree array * @param inDegree in-degree array * @return true if all vertices having non-zero degree belong to a single weak component */ private boolean allNonZeroDegreeVerticesWeaklyConnected(int startNode, int n, int[] outDegree, int[] inDegree) { boolean[] visited = new boolean[n]; Deque<Integer> stack = new ArrayDeque<>(); stack.push(startNode); visited[startNode] = true; while (!stack.isEmpty()) { int u = stack.pop(); for (int v : graph.getEdges(u)) { if (!visited[v]) { visited[v] = true; stack.push(v); } } for (int x = 0; x < n; x++) { if (!visited[x]) { for (int y : graph.getEdges(x)) { if (y == u) { visited[x] = true; stack.push(x); break; } } } } } for (int i = 0; i < n; i++) { if (outDegree[i] + inDegree[i] > 0 && !visited[i]) { return false; } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/YensKShortestPaths.java
src/main/java/com/thealgorithms/graph/YensKShortestPaths.java
package com.thealgorithms.graph; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.PriorityQueue; import java.util.Set; /** * Yen's algorithm for finding K loopless shortest paths in a directed graph with non-negative edge weights. * * <p>Input is an adjacency matrix of edge weights. A value of -1 indicates no edge. * All existing edge weights must be non-negative. Zero-weight edges are allowed.</p> * * <p>References: * - Wikipedia: Yen's algorithm (https://en.wikipedia.org/wiki/Yen%27s_algorithm) * - Dijkstra's algorithm for the base shortest path computation.</p> */ public final class YensKShortestPaths { private YensKShortestPaths() { } private static final int NO_EDGE = -1; private static final long INF_COST = Long.MAX_VALUE / 4; /** * Compute up to k loopless shortest paths from src to dst using Yen's algorithm. * * @param weights adjacency matrix; weights[u][v] = -1 means no edge; otherwise non-negative edge weight * @param src source vertex index * @param dst destination vertex index * @param k maximum number of paths to return (k >= 1) * @return list of paths, each path is a list of vertex indices in order from src to dst * @throws IllegalArgumentException on invalid inputs (null, non-square, negatives on existing edges, bad indices, k < 1) */ public static List<List<Integer>> kShortestPaths(int[][] weights, int src, int dst, int k) { validate(weights, src, dst, k); final int n = weights.length; // Make a defensive copy to avoid mutating caller's matrix int[][] weightsCopy = new int[n][n]; for (int i = 0; i < n; i++) { weightsCopy[i] = Arrays.copyOf(weights[i], n); } List<Path> shortestPaths = new ArrayList<>(); PriorityQueue<Path> candidates = new PriorityQueue<>(); // min-heap by cost then lexicographic nodes Set<String> seen = new HashSet<>(); // deduplicate candidate paths by node sequence key Path first = dijkstra(weightsCopy, src, dst, new boolean[n]); if (first == null) { return List.of(); } shortestPaths.add(first); for (int kIdx = 1; kIdx < k; kIdx++) { Path lastPath = shortestPaths.get(kIdx - 1); List<Integer> lastNodes = lastPath.nodes; for (int i = 0; i < lastNodes.size() - 1; i++) { int spurNode = lastNodes.get(i); List<Integer> rootPath = lastNodes.subList(0, i + 1); // Build modified graph: remove edges that would recreate same root + next edge as any A path int[][] modifiedWeights = cloneMatrix(weightsCopy); for (Path p : shortestPaths) { if (startsWith(p.nodes, rootPath) && p.nodes.size() > i + 1) { int u = p.nodes.get(i); int v = p.nodes.get(i + 1); modifiedWeights[u][v] = NO_EDGE; // remove edge } } // Prevent revisiting nodes in rootPath (loopless constraint), except spurNode itself boolean[] blocked = new boolean[n]; for (int j = 0; j < rootPath.size() - 1; j++) { blocked[rootPath.get(j)] = true; } Path spurPath = dijkstra(modifiedWeights, spurNode, dst, blocked); if (spurPath != null) { // concatenate rootPath (excluding spurNode at end) + spurPath List<Integer> totalNodes = new ArrayList<>(rootPath); // spurPath.nodes starts with spurNode; avoid duplication for (int idx = 1; idx < spurPath.nodes.size(); idx++) { totalNodes.add(spurPath.nodes.get(idx)); } long rootCost = pathCost(weightsCopy, rootPath); long totalCost = rootCost + spurPath.cost; // spurPath.cost covers from spurNode to dst Path candidate = new Path(totalNodes, totalCost); String key = candidate.key(); if (seen.add(key)) { candidates.add(candidate); } } } if (candidates.isEmpty()) { break; } shortestPaths.add(candidates.poll()); } // Map to list of node indices for output List<List<Integer>> result = new ArrayList<>(shortestPaths.size()); for (Path p : shortestPaths) { result.add(new ArrayList<>(p.nodes)); } return result; } private static void validate(int[][] weights, int src, int dst, int k) { if (weights == null || weights.length == 0) { throw new IllegalArgumentException("Weights matrix must not be null or empty"); } int n = weights.length; for (int i = 0; i < n; i++) { if (weights[i] == null || weights[i].length != n) { throw new IllegalArgumentException("Weights matrix must be square"); } for (int j = 0; j < n; j++) { int val = weights[i][j]; if (val < NO_EDGE) { throw new IllegalArgumentException("Weights must be -1 (no edge) or >= 0"); } } } if (src < 0 || dst < 0 || src >= n || dst >= n) { throw new IllegalArgumentException("Invalid src/dst indices"); } if (k < 1) { throw new IllegalArgumentException("k must be >= 1"); } } private static boolean startsWith(List<Integer> list, List<Integer> prefix) { if (prefix.size() > list.size()) { return false; } for (int i = 0; i < prefix.size(); i++) { if (!Objects.equals(list.get(i), prefix.get(i))) { return false; } } return true; } private static int[][] cloneMatrix(int[][] a) { int n = a.length; int[][] b = new int[n][n]; for (int i = 0; i < n; i++) { b[i] = Arrays.copyOf(a[i], n); } return b; } private static long pathCost(int[][] weights, List<Integer> nodes) { long cost = 0; for (int i = 0; i + 1 < nodes.size(); i++) { int u = nodes.get(i); int v = nodes.get(i + 1); int edgeCost = weights[u][v]; if (edgeCost < 0) { return INF_COST; // invalid } cost += edgeCost; } return cost; } private static Path dijkstra(int[][] weights, int src, int dst, boolean[] blocked) { int n = weights.length; final long inf = INF_COST; long[] dist = new long[n]; int[] parent = new int[n]; Arrays.fill(dist, inf); Arrays.fill(parent, -1); PriorityQueue<Node> queue = new PriorityQueue<>(); if (blocked[src]) { return null; } dist[src] = 0; queue.add(new Node(src, 0)); while (!queue.isEmpty()) { Node current = queue.poll(); if (current.dist != dist[current.u]) { continue; } if (current.u == dst) { break; } for (int v = 0; v < n; v++) { int edgeWeight = weights[current.u][v]; if (edgeWeight >= 0 && !blocked[v]) { long newDist = current.dist + edgeWeight; if (newDist < dist[v]) { dist[v] = newDist; parent[v] = current.u; queue.add(new Node(v, newDist)); } } } } if (dist[dst] >= inf) { // If src==dst and not blocked, the path is trivial with cost 0 if (src == dst) { List<Integer> nodes = new ArrayList<>(); nodes.add(src); return new Path(nodes, 0); } return null; } // Reconstruct path List<Integer> nodes = new ArrayList<>(); int cur = dst; while (cur != -1) { nodes.add(0, cur); cur = parent[cur]; } return new Path(nodes, dist[dst]); } private static final class Node implements Comparable<Node> { final int u; final long dist; Node(int u, long dist) { this.u = u; this.dist = dist; } public int compareTo(Node o) { return Long.compare(this.dist, o.dist); } } private static final class Path implements Comparable<Path> { final List<Integer> nodes; final long cost; Path(List<Integer> nodes, long cost) { this.nodes = nodes; this.cost = cost; } String key() { return nodes.toString(); } @Override public int compareTo(Path o) { int costCmp = Long.compare(this.cost, o.cost); if (costCmp != 0) { return costCmp; } // tie-break lexicographically on nodes int minLength = Math.min(this.nodes.size(), o.nodes.size()); for (int i = 0; i < minLength; i++) { int aNode = this.nodes.get(i); int bNode = o.nodes.get(i); if (aNode != bNode) { return Integer.compare(aNode, bNode); } } return Integer.compare(this.nodes.size(), o.nodes.size()); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/HierholzerAlgorithm.java
src/main/java/com/thealgorithms/graph/HierholzerAlgorithm.java
package com.thealgorithms.graph; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; /** * Implementation of Hierholzer's algorithm to find an Eulerian Circuit in an undirected graph. * <p> * An Eulerian circuit is a trail in a graph that visits every edge exactly once, * starting and ending at the same vertex. This algorithm finds such a circuit if one exists. * </p> * <p> * This implementation is designed for an <strong>undirected graph</strong>. For a valid Eulerian * circuit to exist, the graph must satisfy two conditions: * <ol> * <li>All vertices with a non-zero degree must be part of a single connected component.</li> * <li>Every vertex must have an even degree (an even number of edges connected to it).</li> * </ol> * </p> * <p> * The algorithm runs in O(E + V) time, where E is the number of edges and V is the number of vertices. * The graph is represented by a Map where keys are vertices and values are a LinkedList of adjacent vertices. * </p> * * @see <a href="https://en.wikipedia.org/wiki/Eulerian_path#Hierholzer's_algorithm">Wikipedia: Hierholzer's algorithm</a> */ public final class HierholzerAlgorithm { private final Map<Integer, LinkedList<Integer>> graph; public HierholzerAlgorithm(Map<Integer, LinkedList<Integer>> graph) { this.graph = (graph == null) ? new HashMap<>() : graph; } public boolean hasEulerianCircuit() { if (graph.isEmpty()) { return true; } for (List<Integer> neighbors : graph.values()) { if (neighbors.size() % 2 != 0) { return false; } } return isCoherentlyConnected(); } public List<Integer> findEulerianCircuit() { if (!hasEulerianCircuit()) { return Collections.emptyList(); } Map<Integer, LinkedList<Integer>> tempGraph = new HashMap<>(); for (Map.Entry<Integer, LinkedList<Integer>> entry : graph.entrySet()) { tempGraph.put(entry.getKey(), new LinkedList<>(entry.getValue())); } Stack<Integer> currentPath = new Stack<>(); LinkedList<Integer> circuit = new LinkedList<>(); int startVertex = -1; for (Map.Entry<Integer, LinkedList<Integer>> entry : tempGraph.entrySet()) { if (!entry.getValue().isEmpty()) { startVertex = entry.getKey(); break; } } if (startVertex == -1) { if (graph.isEmpty()) { return Collections.emptyList(); } return Collections.singletonList(graph.keySet().iterator().next()); } currentPath.push(startVertex); while (!currentPath.isEmpty()) { int currentVertex = currentPath.peek(); if (tempGraph.containsKey(currentVertex) && !tempGraph.get(currentVertex).isEmpty()) { int nextVertex = tempGraph.get(currentVertex).pollFirst(); tempGraph.get(nextVertex).remove(Integer.valueOf(currentVertex)); currentPath.push(nextVertex); } else { circuit.addFirst(currentVertex); currentPath.pop(); } } return circuit; } private boolean isCoherentlyConnected() { if (graph.isEmpty()) { return true; } Set<Integer> visited = new HashSet<>(); int startNode = -1; for (Map.Entry<Integer, LinkedList<Integer>> entry : graph.entrySet()) { if (!entry.getValue().isEmpty()) { startNode = entry.getKey(); break; } } if (startNode == -1) { return true; } dfs(startNode, visited); for (Map.Entry<Integer, LinkedList<Integer>> entry : graph.entrySet()) { if (!entry.getValue().isEmpty() && !visited.contains(entry.getKey())) { return false; } } return true; } private void dfs(int u, Set<Integer> visited) { visited.add(u); if (graph.containsKey(u)) { for (int v : graph.get(u)) { if (!visited.contains(v)) { dfs(v, visited); } } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/ZeroOneBfs.java
src/main/java/com/thealgorithms/graph/ZeroOneBfs.java
package com.thealgorithms.graph; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import java.util.List; /** * 0-1 BFS for shortest paths on graphs with edges weighted 0 or 1. * * <p>Time Complexity: O(V + E). Space Complexity: O(V). * * <p>References: * <ul> * <li>https://cp-algorithms.com/graph/01_bfs.html</li> * </ul> */ public final class ZeroOneBfs { private ZeroOneBfs() { // Utility class; do not instantiate. } /** * Computes shortest distances from {@code src} in a graph whose edges have weight 0 or 1. * * @param n the number of vertices, labeled {@code 0..n-1} * @param adj adjacency list; for each vertex u, {@code adj.get(u)} is a list of pairs * {@code (v, w)} where {@code v} is a neighbor and {@code w} is 0 or 1 * @param src the source vertex * @return an array of distances; {@code Integer.MAX_VALUE} denotes unreachable * @throws IllegalArgumentException if {@code n < 0}, {@code src} is out of range, * or any edge has weight other than 0 or 1 */ public static int[] shortestPaths(int n, List<List<int[]>> adj, int src) { if (n < 0 || src < 0 || src >= n) { throw new IllegalArgumentException("Invalid n or src"); } int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); Deque<Integer> dq = new ArrayDeque<>(); dist[src] = 0; dq.addFirst(src); while (!dq.isEmpty()) { int u = dq.pollFirst(); List<int[]> edges = adj.get(u); if (edges == null) { continue; } for (int[] e : edges) { if (e == null || e.length < 2) { continue; } int v = e[0]; int w = e[1]; if (v < 0 || v >= n) { continue; // ignore bad edges } if (w != 0 && w != 1) { throw new IllegalArgumentException("Edge weight must be 0 or 1"); } int nd = dist[u] + w; if (nd < dist[v]) { dist[v] = nd; if (w == 0) { dq.addFirst(v); } else { dq.addLast(v); } } } } return dist; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/graph/HopcroftKarp.java
src/main/java/com/thealgorithms/graph/HopcroftKarp.java
package com.thealgorithms.graph; import java.util.ArrayDeque; import java.util.Arrays; import java.util.List; import java.util.Queue; /** * Hopcroft–Karp algorithm for maximum bipartite matching. * * Left part: vertices [0,nLeft-1], Right part: [0,nRight-1]. * Adjacency list: for each left vertex u, list right vertices v it connects to. * * Time complexity: O(E * sqrt(V)). * * @see <a href="https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm"> * Wikipedia: Hopcroft–Karp algorithm</a> * @author ptzecher */ public class HopcroftKarp { private final int nLeft; private final List<List<Integer>> adj; private final int[] pairU; private final int[] pairV; private final int[] dist; public HopcroftKarp(int nLeft, int nRight, List<List<Integer>> adj) { this.nLeft = nLeft; this.adj = adj; this.pairU = new int[nLeft]; this.pairV = new int[nRight]; this.dist = new int[nLeft]; Arrays.fill(pairU, -1); Arrays.fill(pairV, -1); } /** Returns the size of the maximum matching. */ public int maxMatching() { int matching = 0; while (bfs()) { for (int u = 0; u < nLeft; u++) { if (pairU[u] == -1 && dfs(u)) { matching++; } } } return matching; } // BFS to build layers private boolean bfs() { Queue<Integer> queue = new ArrayDeque<>(); Arrays.fill(dist, -1); for (int u = 0; u < nLeft; u++) { if (pairU[u] == -1) { dist[u] = 0; queue.add(u); } } boolean foundAugPath = false; while (!queue.isEmpty()) { int u = queue.poll(); for (int v : adj.get(u)) { int matchedLeft = pairV[v]; if (matchedLeft == -1) { foundAugPath = true; } else if (dist[matchedLeft] == -1) { dist[matchedLeft] = dist[u] + 1; queue.add(matchedLeft); } } } return foundAugPath; } // DFS to find augmenting paths within the BFS layering private boolean dfs(int u) { for (int v : adj.get(u)) { int matchedLeft = pairV[v]; if (matchedLeft == -1 || (dist[matchedLeft] == dist[u] + 1 && dfs(matchedLeft))) { pairU[u] = v; pairV[v] = u; return true; } } dist[u] = -1; return false; } public int[] getLeftMatches() { return pairU.clone(); } public int[] getRightMatches() { return pairV.clone(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java
src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java
package com.thealgorithms.greedyalgorithms; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Problem Statement: * Given an array of intervals where intervals[i] = [starti, endi]. * * Merge all overlapping intervals and return an array of the non-overlapping * intervals * that cover all the intervals in the input. */ public final class MergeIntervals { /** * Private constructor to prevent instantiation of this utility class. */ private MergeIntervals() { } /** * Merges overlapping intervals from the given array of intervals. * * The method sorts the intervals by their start time, then iterates through the * sorted intervals * and merges overlapping intervals. If an interval overlaps with the last * merged interval, * it updates the end time of the last merged interval. Otherwise, it adds the * interval as a new entry. * * @param intervals A 2D array representing intervals where each element is an * interval [starti, endi]. * @return A 2D array of merged intervals where no intervals overlap. * * Example: * Input: {{1, 3}, {2, 6}, {8, 10}, {15, 18}} * Output: {{1, 6}, {8, 10}, {15, 18}} */ public static int[][] merge(int[][] intervals) { // Sort the intervals by their start time (ascending order) Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); // List to store merged intervals List<int[]> merged = new ArrayList<>(); for (int[] interval : intervals) { // Each interval // If the merged list is empty or the current interval does not overlap with // the last merged interval, add it to the merged list. if (merged.isEmpty() || interval[0] > merged.get(merged.size() - 1)[1]) { merged.add(interval); } else { // If there is an overlap, merge the intervals by updating the end time // of the last merged interval to the maximum end time between the two // intervals. merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], interval[1]); } } // Convert the list of merged intervals back to a 2D array and return it return merged.toArray(new int[merged.size()][]); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java
src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java
package com.thealgorithms.greedyalgorithms; import java.util.ArrayList; import java.util.Arrays; // Problem Link: https://en.wikipedia.org/wiki/Job-shop_scheduling public final class JobSequencing { private JobSequencing() { } // Define a Job class that implements Comparable for sorting by profit in descending order static class Job implements Comparable<Job> { char id; int deadline; int profit; // Compare jobs by profit in descending order @Override public int compareTo(Job otherJob) { return otherJob.profit - this.profit; } Job(char id, int deadline, int profit) { this.id = id; this.deadline = deadline; this.profit = profit; } } // Function to print the job sequence public static String findJobSequence(ArrayList<Job> jobs, int size) { Boolean[] slots = new Boolean[size]; Arrays.fill(slots, Boolean.FALSE); int[] result = new int[size]; // Iterate through jobs to find the optimal job sequence for (int i = 0; i < size; i++) { for (int j = jobs.get(i).deadline - 1; j >= 0; j--) { if (!slots[j]) { result[j] = i; slots[j] = Boolean.TRUE; break; } } } // Create a StringBuilder to build the job sequence string StringBuilder jobSequenceBuilder = new StringBuilder(); jobSequenceBuilder.append("Job Sequence: "); for (int i = 0; i < jobs.size(); i++) { if (slots[i]) { jobSequenceBuilder.append(jobs.get(result[i]).id).append(" -> "); } } // Remove the trailing " -> " from the job sequence if (jobSequenceBuilder.length() >= 4) { jobSequenceBuilder.setLength(jobSequenceBuilder.length() - 4); } // Return the job sequence as a string return jobSequenceBuilder.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java
src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java
package com.thealgorithms.greedyalgorithms; import java.util.Arrays; import java.util.Comparator; /** * The FractionalKnapsack class provides a method to solve the fractional knapsack problem * using a greedy algorithm approach. It allows for selecting fractions of items to maximize * the total value in a knapsack with a given weight capacity. * * The problem consists of a set of items, each with a weight and a value, and a knapsack * that can carry a maximum weight. The goal is to maximize the value of items in the knapsack, * allowing for the inclusion of fractions of items. * * Problem Link: https://en.wikipedia.org/wiki/Continuous_knapsack_problem */ public final class FractionalKnapsack { private FractionalKnapsack() { } /** * Computes the maximum value that can be accommodated in a knapsack of a given capacity. * * @param weight an array of integers representing the weights of the items * @param value an array of integers representing the values of the items * @param capacity an integer representing the maximum weight capacity of the knapsack * @return the maximum value that can be obtained by including the items in the knapsack */ public static int fractionalKnapsack(int[] weight, int[] value, int capacity) { double[][] ratio = new double[weight.length][2]; for (int i = 0; i < weight.length; i++) { ratio[i][0] = i; ratio[i][1] = value[i] / (double) weight[i]; } Arrays.sort(ratio, Comparator.comparingDouble(o -> o[1])); int finalValue = 0; double current = capacity; for (int i = ratio.length - 1; i >= 0; i--) { int index = (int) ratio[i][0]; if (current >= weight[index]) { finalValue += value[index]; current -= weight[index]; } else { finalValue += (int) (ratio[i][1] * current); break; } } return finalValue; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/KCenters.java
src/main/java/com/thealgorithms/greedyalgorithms/KCenters.java
package com.thealgorithms.greedyalgorithms; import java.util.Arrays; /** * Given a set of points and a number k. * The goal is to minimize the maximum distance between any point and its nearest center. * Each point is assigned to the nearest center. * The distance between two points is the Euclidean distance. * The problem is NP-hard. * * @author Hardvan */ public final class KCenters { private KCenters() { } /** * Finds the maximum distance to the nearest center given k centers. * Steps: * 1. Initialize an array {@code selected} of size n and an array {@code maxDist} of size n. * 2. Set the first node as selected and update the maxDist array. * 3. For each center, find the farthest node from the selected centers. * 4. Update the maxDist array. * 5. Return the maximum distance to the nearest center. * * @param distances matrix representing distances between nodes * @param k the number of centers * @return the maximum distance to the nearest center */ public static int findKCenters(int[][] distances, int k) { int n = distances.length; boolean[] selected = new boolean[n]; int[] maxDist = new int[n]; Arrays.fill(maxDist, Integer.MAX_VALUE); selected[0] = true; for (int i = 1; i < n; i++) { maxDist[i] = Math.min(maxDist[i], distances[0][i]); } for (int centers = 1; centers < k; centers++) { int farthest = -1; for (int i = 0; i < n; i++) { if (!selected[i] && (farthest == -1 || maxDist[i] > maxDist[farthest])) { farthest = i; } } selected[farthest] = true; for (int i = 0; i < n; i++) { maxDist[i] = Math.min(maxDist[i], distances[farthest][i]); } } int result = 0; for (int dist : maxDist) { result = Math.max(result, dist); } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/BinaryAddition.java
src/main/java/com/thealgorithms/greedyalgorithms/BinaryAddition.java
package com.thealgorithms.greedyalgorithms; import java.util.Collections; /** * BinaryAddition class to perform binary addition of two binary strings. */ public class BinaryAddition { /** * Computes the sum of two binary characters and a carry. * @param a First binary character ('0' or '1'). * @param b Second binary character ('0' or '1'). * @param carry The carry from the previous operation ('0' or '1'). * @return The sum as a binary character ('0' or '1'). */ public char sum(char a, char b, char carry) { int count = 0; if (a == '1') { count++; } if (b == '1') { count++; } if (carry == '1') { count++; } return count % 2 == 0 ? '0' : '1'; } /** * Computes the carry for the next higher bit from two binary characters and a carry. * @param a First binary character ('0' or '1'). * @param b Second binary character ('0' or '1'). * @param carry The carry from the previous operation ('0' or '1'). * @return The carry for the next bit ('0' or '1'). */ public char carry(char a, char b, char carry) { int count = 0; if (a == '1') { count++; } if (b == '1') { count++; } if (carry == '1') { count++; } return count >= 2 ? '1' : '0'; } /** * Adds two binary strings and returns their sum as a binary string. * @param a First binary string. * @param b Second binary string. * @return Binary string representing the sum of the two binary inputs. */ public String addBinary(String a, String b) { // Padding the shorter string with leading zeros int maxLength = Math.max(a.length(), b.length()); a = String.join("", Collections.nCopies(maxLength - a.length(), "0")) + a; b = String.join("", Collections.nCopies(maxLength - b.length(), "0")) + b; StringBuilder result = new StringBuilder(); char carry = '0'; // Iterating over the binary strings from the least significant to the most significant bit for (int i = maxLength - 1; i >= 0; i--) { char sum = sum(a.charAt(i), b.charAt(i), carry); carry = carry(a.charAt(i), b.charAt(i), carry); result.append(sum); } // If there's a remaining carry, append it if (carry == '1') { result.append('1'); } // Reverse the result as we constructed it from the least significant bit return result.reverse().toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java
src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java
package com.thealgorithms.greedyalgorithms; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; // Problem Link : https://en.wikipedia.org/wiki/Change-making_problem public final class CoinChange { private CoinChange() { } // Function to solve the coin change problem public static ArrayList<Integer> coinChangeProblem(int amount) { // Define an array of coin denominations in descending order Integer[] coins = {1, 2, 5, 10, 20, 50, 100, 500, 2000}; // Sort the coin denominations in descending order Arrays.sort(coins, Comparator.reverseOrder()); ArrayList<Integer> ans = new ArrayList<>(); // List to store selected coins // Iterate through the coin denominations for (int i = 0; i < coins.length; i++) { // Check if the current coin denomination can be used to reduce the remaining amount if (coins[i] <= amount) { // Repeatedly subtract the coin denomination from the remaining amount while (coins[i] <= amount) { ans.add(coins[i]); // Add the coin to the list of selected coins amount -= coins[i]; // Update the remaining amount } } } return ans; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/OptimalFileMerging.java
src/main/java/com/thealgorithms/greedyalgorithms/OptimalFileMerging.java
package com.thealgorithms.greedyalgorithms; import java.util.PriorityQueue; /** * Class to solve the Optimal File Merging Problem. * The goal is to minimize the cost of merging files, where the cost of merging two files is the sum of their sizes. * The cost of merging all files is the sum of the costs of merging each pair of files. * Example: * files = [4, 3, 2, 6] * The minimum cost to merge all files is 29. * Steps: * 1. Merge files 2 and 3 (cost = 2 + 3 = 5). New files = [4, 5, 6] * 2. Merge files 4 and 5 (cost = 4 + 5 = 9). New files = [6, 9] * 3. Merge files 6 and 9 (cost = 6 + 9 = 15). New files = [15] * Total cost = 5 + 9 + 15 = 29 * * @author Hardvan */ public final class OptimalFileMerging { private OptimalFileMerging() { } /** * Calculates the minimum cost to merge all files. * Steps: * 1. Add all files to a min heap. * 2. Remove the two smallest files from the heap, merge them, and add the result back to the heap. * 3. Repeat step 2 until there is only one file left in the heap. * 4. The total cost is the sum of all the costs of merging the files. * * @param files array of file sizes * @return the minimum cost to merge the files */ public static int minMergeCost(int[] files) { PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for (int file : files) { minHeap.add(file); } int totalCost = 0; while (minHeap.size() > 1) { int first = minHeap.poll(); int second = minHeap.poll(); int cost = first + second; totalCost += cost; minHeap.add(cost); } return totalCost; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/StockProfitCalculator.java
src/main/java/com/thealgorithms/greedyalgorithms/StockProfitCalculator.java
package com.thealgorithms.greedyalgorithms; /** * The StockProfitCalculator class provides a method to calculate the maximum profit * that can be made from a single buy and sell of one share of stock. * The approach uses a greedy algorithm to efficiently determine the maximum profit. * * @author Hardvan */ public final class StockProfitCalculator { private StockProfitCalculator() { } /** * Calculates the maximum profit from a list of stock prices. * * @param prices an array of integers representing the stock prices on different days * @return the maximum profit that can be achieved from a single buy and sell * transaction, or 0 if no profit can be made */ public static int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int minPrice = prices[0]; int maxProfit = 0; for (int price : prices) { minPrice = Math.min(price, minPrice); maxProfit = Math.max(price - minPrice, maxProfit); } return maxProfit; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java
src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java
package com.thealgorithms.greedyalgorithms; import java.util.Arrays; public final class MinimizingLateness { private MinimizingLateness() { } public static class Job { String jobName; int startTime = 0; int lateness = 0; int processingTime; int deadline; public Job(String jobName, int processingTime, int deadline) { this.jobName = jobName; this.processingTime = processingTime; this.deadline = deadline; } public static Job of(String jobName, int processingTime, int deadline) { return new Job(jobName, processingTime, deadline); } @Override public String toString() { return String.format("%s, startTime: %d, endTime: %d, lateness: %d", jobName, startTime, processingTime + startTime, lateness); } } static void calculateLateness(Job... jobs) { // sort the jobs based on their deadline Arrays.sort(jobs, (a, b) -> a.deadline - b.deadline); int startTime = 0; for (Job job : jobs) { job.startTime = startTime; startTime += job.processingTime; job.lateness = Math.max(0, startTime - job.deadline); // if the job finishes before deadline the lateness is 0 } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/BandwidthAllocation.java
src/main/java/com/thealgorithms/greedyalgorithms/BandwidthAllocation.java
package com.thealgorithms.greedyalgorithms; import java.util.Arrays; /** * Class to solve the Bandwidth Allocation Problem. * The goal is to maximize the value gained by allocating bandwidth to users. * Example: * Bandwidth = 10 * Users = [3, 5, 7] * Values = [10, 20, 30] * The maximum value achievable is 40 by allocating 3 units to user 0 and 7 units to user 2. * * @author Hardvan */ public final class BandwidthAllocation { private BandwidthAllocation() { } /** * Allocates bandwidth to maximize value. * Steps: * 1. Calculate the ratio of value/demand for each user. * 2. Sort the users in descending order of the ratio. * 3. Allocate bandwidth to users in order of the sorted list. * 4. If the bandwidth is not enough to allocate the full demand of a user, allocate a fraction of the demand. * 5. Return the maximum value achievable. * * @param bandwidth total available bandwidth to allocate * @param users array of user demands * @param values array of values associated with each user's demand * @return the maximum value achievable */ public static int maxValue(int bandwidth, int[] users, int[] values) { int n = users.length; double[][] ratio = new double[n][2]; // {index, ratio} for (int i = 0; i < n; i++) { ratio[i][0] = i; ratio[i][1] = (double) values[i] / users[i]; } Arrays.sort(ratio, (a, b) -> Double.compare(b[1], a[1])); int maxValue = 0; for (int i = 0; i < n; i++) { int index = (int) ratio[i][0]; if (bandwidth >= users[index]) { maxValue += values[index]; bandwidth -= users[index]; } else { maxValue += (int) (ratio[i][1] * bandwidth); break; } } return maxValue; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/DigitSeparation.java
src/main/java/com/thealgorithms/greedyalgorithms/DigitSeparation.java
package com.thealgorithms.greedyalgorithms; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * This class provides methods to separate the digits of a large positive number into a list. */ public class DigitSeparation { public DigitSeparation() { } /** * Separates the digits of a large positive number into a list in reverse order. * @param largeNumber The large number to separate digits from. * @return A list of digits in reverse order. */ public List<Long> digitSeparationReverseOrder(long largeNumber) { List<Long> result = new ArrayList<>(); if (largeNumber != 0) { while (largeNumber != 0) { result.add(Math.abs(largeNumber % 10)); largeNumber = largeNumber / 10; } } else { result.add(0L); } return result; } /** * Separates the digits of a large positive number into a list in forward order. * @param largeNumber The large number to separate digits from. * @return A list of digits in forward order. */ public List<Long> digitSeparationForwardOrder(long largeNumber) { List<Long> result = this.digitSeparationReverseOrder(largeNumber); Collections.reverse(result); return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/EgyptianFraction.java
src/main/java/com/thealgorithms/greedyalgorithms/EgyptianFraction.java
package com.thealgorithms.greedyalgorithms; import java.util.ArrayList; import java.util.List; /** * Class to represent a fraction as a sum of unique unit fractions. * Example: * 2/3 = 1/2 + 1/6 * 3/10 = 1/4 + 1/20 * * @author Hardvan */ public final class EgyptianFraction { private EgyptianFraction() { } /** * Calculates the Egyptian Fraction representation of a given fraction. * * @param numerator the numerator of the fraction * @param denominator the denominator of the fraction * @return List of unit fractions represented as strings "1/x" */ public static List<String> getEgyptianFraction(int numerator, int denominator) { List<String> result = new ArrayList<>(); while (numerator != 0) { int x = (int) Math.ceil((double) denominator / numerator); result.add("1/" + x); numerator = numerator * x - denominator; denominator = denominator * x; } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/GaleShapley.java
src/main/java/com/thealgorithms/greedyalgorithms/GaleShapley.java
package com.thealgorithms.greedyalgorithms; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; /** * Implementation of the Gale-Shapley Algorithm for Stable Matching. * Problem link: https://en.wikipedia.org/wiki/Stable_marriage_problem */ public final class GaleShapley { private GaleShapley() { } /** * Function to find stable matches between men and women. * * @param womenPrefs A map containing women's preferences where each key is a woman and the value is an array of men in order of preference. * @param menPrefs A map containing men's preferences where each key is a man and the value is an array of women in order of preference. * @return A map containing stable matches where the key is a woman and the value is her matched man. */ public static Map<String, String> stableMatch(Map<String, LinkedList<String>> womenPrefs, Map<String, LinkedList<String>> menPrefs) { // Initialize all men as free Map<String, String> engagements = new HashMap<>(); LinkedList<String> freeMen = new LinkedList<>(menPrefs.keySet()); // While there are free men while (!freeMen.isEmpty()) { String man = freeMen.poll(); // Get the first free man LinkedList<String> manPref = menPrefs.get(man); // Get the preferences of the man // Check if manPref is null or empty if (manPref == null || manPref.isEmpty()) { continue; // Skip if no preferences } // Propose to the first woman in the man's preference list String woman = manPref.poll(); String fiance = engagements.get(woman); // If the woman is not engaged, engage her with the current man if (fiance == null) { engagements.put(woman, man); } else { // If the woman prefers the current man over her current fiance LinkedList<String> womanPrefList = womenPrefs.get(woman); // Check if womanPrefList is null if (womanPrefList == null) { continue; // Skip if no preferences for the woman } if (womanPrefList.indexOf(man) < womanPrefList.indexOf(fiance)) { engagements.put(woman, man); freeMen.add(fiance); // Previous fiance becomes free } else { // Woman rejects the new proposal, the man remains free freeMen.add(man); } } } return engagements; // Return the stable matches } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTime.java
src/main/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTime.java
package com.thealgorithms.greedyalgorithms; import java.util.Arrays; /** * The MinimumWaitingTime class provides a method to calculate the minimum * waiting time for a list of queries using a greedy algorithm. * * @author Hardvan */ public final class MinimumWaitingTime { private MinimumWaitingTime() { } /** * Calculates the minimum waiting time for a list of queries. * The function sorts the queries in non-decreasing order and then calculates * the waiting time for each query based on its position in the sorted list. * * @param queries an array of integers representing the query times in picoseconds * @return the minimum waiting time in picoseconds */ public static int minimumWaitingTime(int[] queries) { int n = queries.length; if (n <= 1) { return 0; } Arrays.sort(queries); int totalWaitingTime = 0; for (int i = 0; i < n; i++) { totalWaitingTime += queries[i] * (n - i - 1); } return totalWaitingTime; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java
src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java
package com.thealgorithms.greedyalgorithms; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; // Problem Link: https://en.wikipedia.org/wiki/Activity_selection_problem public final class ActivitySelection { // Private constructor to prevent instantiation of the utility class private ActivitySelection() { } /** * Function to perform activity selection using a greedy approach. * * The goal is to select the maximum number of activities that don't overlap * with each other, based on their start and end times. Activities are chosen * such that no two selected activities overlap. * * @param startTimes Array containing the start times of the activities. * @param endTimes Array containing the end times of the activities. * @return A list of indices representing the selected activities that can be * performed without overlap. */ public static ArrayList<Integer> activitySelection(int[] startTimes, int[] endTimes) { int n = startTimes.length; // Create a 2D array to store activity indices along with their start and end // times. // Each row represents an activity in the format: [activity index, start time, // end time]. int[][] activities = new int[n][3]; // Populate the 2D array with the activity index, start time, and end time. for (int i = 0; i < n; i++) { activities[i][0] = i; // Assign the activity index activities[i][1] = startTimes[i]; // Assign the start time of the activity activities[i][2] = endTimes[i]; // Assign the end time of the activity } // Sort activities based on their end times in ascending order. // This ensures that we always try to finish earlier activities first. Arrays.sort(activities, Comparator.comparingDouble(activity -> activity[2])); int lastEndTime; // Variable to store the end time of the last selected activity // List to store the indices of selected activities ArrayList<Integer> selectedActivities = new ArrayList<>(); // Select the first activity (as it has the earliest end time after sorting) selectedActivities.add(activities[0][0]); // Add the first activity index to the result lastEndTime = activities[0][2]; // Keep track of the end time of the last selected activity // Iterate over the sorted activities to select the maximum number of compatible // activities. for (int i = 1; i < n; i++) { // If the start time of the current activity is greater than or equal to the // end time of the last selected activity, it means there's no overlap. if (activities[i][1] >= lastEndTime) { selectedActivities.add(activities[i][0]); // Select this activity lastEndTime = activities[i][2]; // Update the end time of the last selected activity } } // Return the list of selected activity indices. return selectedActivities; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/RotateMatrixBy90Degrees.java
src/main/java/com/thealgorithms/matrix/RotateMatrixBy90Degrees.java
package com.thealgorithms.matrix; import java.util.Scanner; /** * Given a matrix of size n x n We have to rotate this matrix by 90 Degree Here * is the algorithm for this problem . */ final class RotateMatrixBy90Degrees { private RotateMatrixBy90Degrees() { } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[][] arr = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = sc.nextInt(); } } Rotate.rotate(arr); printMatrix(arr); } sc.close(); } static void printMatrix(int[][] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(""); } } } /** * Class containing the algo to rotate matrix by 90 degree */ final class Rotate { private Rotate() { } static void rotate(int[][] a) { int n = a.length; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i > j) { int temp = a[i][j]; a[i][j] = a[j][i]; a[j][i] = temp; } } } int i = 0; int k = n - 1; while (i < k) { for (int j = 0; j < n; j++) { int temp = a[i][j]; a[i][j] = a[k][j]; a[k][j] = temp; } i++; k--; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/MatrixMultiplication.java
src/main/java/com/thealgorithms/matrix/MatrixMultiplication.java
package com.thealgorithms.matrix; /** * This class provides a method to perform matrix multiplication. * * <p>Matrix multiplication takes two 2D arrays (matrices) as input and * produces their product, following the mathematical definition of * matrix multiplication. * * <p>For more details: * https://www.geeksforgeeks.org/java/java-program-to-multiply-two-matrices-of-any-size/ * https://en.wikipedia.org/wiki/Matrix_multiplication * * <p>Time Complexity: O(n^3) – where n is the dimension of the matrices * (assuming square matrices for simplicity). * * <p>Space Complexity: O(n^2) – for storing the result matrix. * * * @author Nishitha Wihala Pitigala * */ public final class MatrixMultiplication { private MatrixMultiplication() { } /** * Multiplies two matrices. * * @param matrixA the first matrix rowsA x colsA * @param matrixB the second matrix rowsB x colsB * @return the product of the two matrices rowsA x colsB * @throws IllegalArgumentException if the matrices cannot be multiplied */ public static double[][] multiply(double[][] matrixA, double[][] matrixB) { // Check the input matrices are not null if (matrixA == null || matrixB == null) { throw new IllegalArgumentException("Input matrices cannot be null"); } // Check for empty matrices if (matrixA.length == 0 || matrixB.length == 0 || matrixA[0].length == 0 || matrixB[0].length == 0) { throw new IllegalArgumentException("Input matrices must not be empty"); } // Validate the matrix dimensions if (matrixA[0].length != matrixB.length) { throw new IllegalArgumentException("Matrices cannot be multiplied: incompatible dimensions."); } int rowsA = matrixA.length; int colsA = matrixA[0].length; int colsB = matrixB[0].length; // Initialize the result matrix with zeros double[][] result = new double[rowsA][colsB]; // Perform matrix multiplication for (int i = 0; i < rowsA; i++) { for (int j = 0; j < colsB; j++) { for (int k = 0; k < colsA; k++) { result[i][j] += matrixA[i][k] * matrixB[k][j]; } } } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/LUDecomposition.java
src/main/java/com/thealgorithms/matrix/LUDecomposition.java
package com.thealgorithms.matrix; /** * LU Decomposition algorithm * -------------------------- * Decomposes a square matrix a into a product of two matrices: * a = l * u * where: * - l is a lower triangular matrix with 1s on its diagonal * - u is an upper triangular matrix * * Reference: * https://en.wikipedia.org/wiki/lu_decomposition */ public final class LUDecomposition { private LUDecomposition() { } /** * A helper class to store both l and u matrices */ public static class LU { double[][] l; double[][] u; LU(double[][] l, double[][] u) { this.l = l; this.u = u; } } /** * Performs LU Decomposition on a square matrix a * * @param a input square matrix * @return LU object containing l and u matrices */ public static LU decompose(double[][] a) { int n = a.length; double[][] l = new double[n][n]; double[][] u = new double[n][n]; for (int i = 0; i < n; i++) { // upper triangular matrix for (int k = i; k < n; k++) { double sum = 0; for (int j = 0; j < i; j++) { sum += l[i][j] * u[j][k]; } u[i][k] = a[i][k] - sum; } // lower triangular matrix for (int k = i; k < n; k++) { if (i == k) { l[i][i] = 1; // diagonal as 1 } else { double sum = 0; for (int j = 0; j < i; j++) { sum += l[k][j] * u[j][i]; } l[k][i] = (a[k][i] - sum) / u[i][i]; } } } return new LU(l, u); } /** * Utility function to print a matrix * * @param m matrix to print */ public static void printMatrix(double[][] m) { for (double[] row : m) { System.out.print("["); for (int j = 0; j < row.length; j++) { System.out.printf("%7.3f", row[j]); if (j < row.length - 1) { System.out.print(", "); } } System.out.println("]"); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/InverseOfMatrix.java
src/main/java/com/thealgorithms/matrix/InverseOfMatrix.java
package com.thealgorithms.matrix; /** * This class provides methods to compute the inverse of a square matrix * using Gaussian elimination. For more details, refer to: * https://en.wikipedia.org/wiki/Invertible_matrix */ public final class InverseOfMatrix { private InverseOfMatrix() { } public static double[][] invert(double[][] a) { int n = a.length; double[][] x = new double[n][n]; double[][] b = new double[n][n]; int[] index = new int[n]; // Initialize the identity matrix for (int i = 0; i < n; ++i) { b[i][i] = 1; } // Perform Gaussian elimination gaussian(a, index); // Update matrix b with the ratios stored during elimination for (int i = 0; i < n - 1; ++i) { for (int j = i + 1; j < n; ++j) { for (int k = 0; k < n; ++k) { b[index[j]][k] -= a[index[j]][i] * b[index[i]][k]; } } } // Perform backward substitution to find the inverse for (int i = 0; i < n; ++i) { x[n - 1][i] = b[index[n - 1]][i] / a[index[n - 1]][n - 1]; for (int j = n - 2; j >= 0; --j) { x[j][i] = b[index[j]][i]; for (int k = j + 1; k < n; ++k) { x[j][i] -= a[index[j]][k] * x[k][i]; } x[j][i] /= a[index[j]][j]; } } return x; } /** * Method to carry out the partial-pivoting Gaussian * elimination. Here index[] stores pivoting order. **/ private static void gaussian(double[][] a, int[] index) { int n = index.length; double[] c = new double[n]; // Initialize the index array for (int i = 0; i < n; ++i) { index[i] = i; } // Find the rescaling factors for each row for (int i = 0; i < n; ++i) { double c1 = 0; for (int j = 0; j < n; ++j) { double c0 = Math.abs(a[i][j]); if (c0 > c1) { c1 = c0; } } c[i] = c1; } // Perform pivoting for (int j = 0; j < n - 1; ++j) { double pi1 = 0; int k = j; for (int i = j; i < n; ++i) { double pi0 = Math.abs(a[index[i]][j]) / c[index[i]]; if (pi0 > pi1) { pi1 = pi0; k = i; } } // Swap rows int temp = index[j]; index[j] = index[k]; index[k] = temp; for (int i = j + 1; i < n; ++i) { double pj = a[index[i]][j] / a[index[j]][j]; // Record pivoting ratios below the diagonal a[index[i]][j] = pj; // Modify other elements accordingly for (int l = j + 1; l < n; ++l) { a[index[i]][l] -= pj * a[index[j]][l]; } } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/MirrorOfMatrix.java
src/main/java/com/thealgorithms/matrix/MirrorOfMatrix.java
package com.thealgorithms.matrix; // Problem Statement import com.thealgorithms.matrix.utils.MatrixUtil; /* We have given an array of m x n (where m is the number of rows and n is the number of columns). Print the new matrix in such a way that the new matrix is the mirror image of the original matrix. The Original matrix is: | The Mirror matrix is: 1 2 3 | 3 2 1 4 5 6 | 6 5 4 7 8 9 | 9 8 7 @author - Aman (https://github.com/Aman28801) */ public final class MirrorOfMatrix { private MirrorOfMatrix() { } public static double[][] mirrorMatrix(final double[][] originalMatrix) { MatrixUtil.validateInputMatrix(originalMatrix); int numRows = originalMatrix.length; int numCols = originalMatrix[0].length; double[][] mirroredMatrix = new double[numRows][numCols]; for (int i = 0; i < numRows; i++) { mirroredMatrix[i] = MatrixUtil.reverseRow(originalMatrix[i]); } return mirroredMatrix; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/MedianOfMatrix.java
src/main/java/com/thealgorithms/matrix/MedianOfMatrix.java
package com.thealgorithms.matrix; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Median of Matrix (https://medium.com/@vaibhav.yadav8101/median-in-a-row-wise-sorted-matrix-901737f3e116) * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ public final class MedianOfMatrix { private MedianOfMatrix() { } public static int median(Iterable<List<Integer>> matrix) { List<Integer> flattened = new ArrayList<>(); for (List<Integer> row : matrix) { if (row != null) { flattened.addAll(row); } } if (flattened.isEmpty()) { throw new IllegalArgumentException("Matrix must contain at least one element."); } Collections.sort(flattened); return flattened.get((flattened.size() - 1) / 2); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/PrintAMatrixInSpiralOrder.java
src/main/java/com/thealgorithms/matrix/PrintAMatrixInSpiralOrder.java
package com.thealgorithms.matrix; import java.util.ArrayList; import java.util.List; /** * Utility class to print a matrix in spiral order. * <p> * Given a 2D array (matrix), this class provides a method to return the * elements * of the matrix in spiral order, starting from the top-left corner and moving * clockwise. * </p> * * @author Sadiul Hakim (https://github.com/sadiul-hakim) */ public class PrintAMatrixInSpiralOrder { /** * Returns the elements of the given matrix in spiral order. * * @param matrix the 2D array to traverse in spiral order * @param row the number of rows in the matrix * @param col the number of columns in the matrix * @return a list containing the elements of the matrix in spiral order * * <p> * Example: * * <pre> * int[][] matrix = { * {1, 2, 3}, * {4, 5, 6}, * {7, 8, 9} * }; * print(matrix, 3, 3) returns [1, 2, 3, 6, 9, 8, 7, 4, 5] * </pre> * </p> */ public List<Integer> print(int[][] matrix, int row, int col) { // r traverses matrix row wise from first int r = 0; // c traverses matrix column wise from first int c = 0; int i; List<Integer> result = new ArrayList<>(); while (r < row && c < col) { // print first row of matrix for (i = c; i < col; i++) { result.add(matrix[r][i]); } // increase r by one because first row printed r++; // print last column for (i = r; i < row; i++) { result.add(matrix[i][col - 1]); } // decrease col by one because last column has been printed col--; // print rows from last except printed elements if (r < row) { for (i = col - 1; i >= c; i--) { result.add(matrix[row - 1][i]); } row--; } // print columns from first except printed elements if (c < col) { for (i = row - 1; i >= r; i--) { result.add(matrix[i][c]); } c++; } } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/SolveSystem.java
src/main/java/com/thealgorithms/matrix/SolveSystem.java
package com.thealgorithms.matrix; /** * This class implements an algorithm for solving a system of equations of the form Ax=b using gaussian elimination and back substitution. * * @link <a href="https://en.wikipedia.org/wiki/Gaussian_elimination">Gaussian Elimination Wiki</a> * @see InverseOfMatrix finds the full of inverse of a matrice, but is not required to solve a system. */ public final class SolveSystem { private SolveSystem() { } /** * Problem: Given a matrix A and vector b, solve the linear system Ax = b for the vector x.\ * <p> * <b>This OVERWRITES the input matrix to save on memory</b> * * @param matrix - a square matrix of doubles * @param constants - an array of constant * @return solutions */ public static double[] solveSystem(double[][] matrix, double[] constants) { final double tol = 0.00000001; // tolerance for round off for (int k = 0; k < matrix.length - 1; k++) { // find the largest value in column (to avoid zero pivots) double maxVal = Math.abs(matrix[k][k]); int maxIdx = k; for (int j = k + 1; j < matrix.length; j++) { if (Math.abs(matrix[j][k]) > maxVal) { maxVal = matrix[j][k]; maxIdx = j; } } if (Math.abs(maxVal) < tol) { // hope the matrix works out continue; } // swap rows double[] temp = matrix[k]; matrix[k] = matrix[maxIdx]; matrix[maxIdx] = temp; double tempConst = constants[k]; constants[k] = constants[maxIdx]; constants[maxIdx] = tempConst; for (int i = k + 1; i < matrix.length; i++) { // compute multipliers and save them in the column matrix[i][k] /= matrix[k][k]; for (int j = k + 1; j < matrix.length; j++) { matrix[i][j] -= matrix[i][k] * matrix[k][j]; } constants[i] -= matrix[i][k] * constants[k]; } } // back substitution double[] x = new double[constants.length]; System.arraycopy(constants, 0, x, 0, constants.length); for (int i = matrix.length - 1; i >= 0; i--) { double sum = 0; for (int j = i + 1; j < matrix.length; j++) { sum += matrix[i][j] * x[j]; } x[i] = constants[i] - sum; if (Math.abs(matrix[i][i]) > tol) { x[i] /= matrix[i][i]; } else { throw new IllegalArgumentException("Matrix was found to be singular"); } } return x; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/MatrixRank.java
src/main/java/com/thealgorithms/matrix/MatrixRank.java
package com.thealgorithms.matrix; import static com.thealgorithms.matrix.utils.MatrixUtil.validateInputMatrix; /** * This class provides a method to compute the rank of a matrix. * In linear algebra, the rank of a matrix is the maximum number of linearly independent rows or columns in the matrix. * For example, consider the following 3x3 matrix: * 1 2 3 * 2 4 6 * 3 6 9 * Despite having 3 rows and 3 columns, this matrix only has a rank of 1 because all rows (and columns) are multiples of each other. * It's a fundamental concept that gives key insights into the structure of the matrix. * It's important to note that the rank is not only defined for square matrices but for any m x n matrix. * * @author Anup Omkar */ public final class MatrixRank { private MatrixRank() { } private static final double EPSILON = 1e-10; /** * @brief Computes the rank of the input matrix * * @param matrix The input matrix * @return The rank of the input matrix */ public static int computeRank(double[][] matrix) { validateInputMatrix(matrix); int numRows = matrix.length; int numColumns = matrix[0].length; int rank = 0; boolean[] rowMarked = new boolean[numRows]; double[][] matrixCopy = deepCopy(matrix); for (int colIndex = 0; colIndex < numColumns; ++colIndex) { int pivotRow = findPivotRow(matrixCopy, rowMarked, colIndex); if (pivotRow != numRows) { ++rank; rowMarked[pivotRow] = true; normalizePivotRow(matrixCopy, pivotRow, colIndex); eliminateRows(matrixCopy, pivotRow, colIndex); } } return rank; } private static boolean isZero(double value) { return Math.abs(value) < EPSILON; } private static double[][] deepCopy(double[][] matrix) { int numRows = matrix.length; int numColumns = matrix[0].length; double[][] matrixCopy = new double[numRows][numColumns]; for (int rowIndex = 0; rowIndex < numRows; ++rowIndex) { System.arraycopy(matrix[rowIndex], 0, matrixCopy[rowIndex], 0, numColumns); } return matrixCopy; } /** * @brief The pivot row is the row in the matrix that is used to eliminate other rows and reduce the matrix to its row echelon form. * The pivot row is selected as the first row (from top to bottom) where the value in the current column (the pivot column) is not zero. * This row is then used to "eliminate" other rows, by subtracting multiples of the pivot row from them, so that all other entries in the pivot column become zero. * This process is repeated for each column, each time selecting a new pivot row, until the matrix is in row echelon form. * The number of pivot rows (rows with a leading entry, or pivot) then gives the rank of the matrix. * * @param matrix The input matrix * @param rowMarked An array indicating which rows have been marked * @param colIndex The column index * @return The pivot row index, or the number of rows if no suitable pivot row was found */ private static int findPivotRow(double[][] matrix, boolean[] rowMarked, int colIndex) { int numRows = matrix.length; for (int pivotRow = 0; pivotRow < numRows; ++pivotRow) { if (!rowMarked[pivotRow] && !isZero(matrix[pivotRow][colIndex])) { return pivotRow; } } return numRows; } /** * @brief This method divides all values in the pivot row by the value in the given column. * This ensures that the pivot value itself will be 1, which simplifies further calculations. * * @param matrix The input matrix * @param pivotRow The pivot row index * @param colIndex The column index */ private static void normalizePivotRow(double[][] matrix, int pivotRow, int colIndex) { int numColumns = matrix[0].length; for (int nextCol = colIndex + 1; nextCol < numColumns; ++nextCol) { matrix[pivotRow][nextCol] /= matrix[pivotRow][colIndex]; } } /** * @brief This method subtracts multiples of the pivot row from all other rows, * so that all values in the given column of other rows will be zero. * This is a key step in reducing the matrix to row echelon form. * * @param matrix The input matrix * @param pivotRow The pivot row index * @param colIndex The column index */ private static void eliminateRows(double[][] matrix, int pivotRow, int colIndex) { int numRows = matrix.length; int numColumns = matrix[0].length; for (int otherRow = 0; otherRow < numRows; ++otherRow) { if (otherRow != pivotRow && !isZero(matrix[otherRow][colIndex])) { for (int col2 = colIndex + 1; col2 < numColumns; ++col2) { matrix[otherRow][col2] -= matrix[pivotRow][col2] * matrix[otherRow][colIndex]; } } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/StochasticMatrix.java
src/main/java/com/thealgorithms/matrix/StochasticMatrix.java
package com.thealgorithms.matrix; /** * Utility class to check whether a matrix is stochastic. * A matrix is stochastic if all its elements are non-negative * and the sum of each row or column is equal to 1. *Reference: https://en.wikipedia.org/wiki/Stochastic_matrix */ public final class StochasticMatrix { private static final double TOLERANCE = 1e-9; private StochasticMatrix() { // Utility class } /** * Checks if a matrix is row-stochastic. * * @param matrix the matrix to check * @return true if the matrix is row-stochastic * @throws IllegalArgumentException if matrix is null or empty */ public static boolean isRowStochastic(double[][] matrix) { validateMatrix(matrix); for (double[] row : matrix) { double sum = 0.0; for (double value : row) { if (value < 0) { return false; } sum += value; } if (Math.abs(sum - 1.0) > TOLERANCE) { return false; } } return true; } /** * Checks if a matrix is column-stochastic. * * @param matrix the matrix to check * @return true if the matrix is column-stochastic * @throws IllegalArgumentException if matrix is null or empty */ public static boolean isColumnStochastic(double[][] matrix) { validateMatrix(matrix); int rows = matrix.length; int cols = matrix[0].length; for (int j = 0; j < cols; j++) { double sum = 0.0; for (int i = 0; i < rows; i++) { if (matrix[i][j] < 0) { return false; } sum += matrix[i][j]; } if (Math.abs(sum - 1.0) > TOLERANCE) { return false; } } return true; } private static void validateMatrix(double[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { throw new IllegalArgumentException("Matrix must not be null or empty"); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/MatrixTranspose.java
src/main/java/com/thealgorithms/matrix/MatrixTranspose.java
package com.thealgorithms.matrix; /** * * * <h1>Find the Transpose of Matrix!</h1> * * Simply take input from the user and print the matrix before the transpose and * after the transpose. * * <p> * <b>Note:</b> Giving proper comments in your program makes it more user * friendly and it is assumed as a high quality code. * * @author Rajat-Jain29 * @version 11.0.9 * @since 2014-03-31 */ public final class MatrixTranspose { private MatrixTranspose() { } /** * Calculate the transpose of the given matrix. * * @param matrix The matrix to be transposed * @throws IllegalArgumentException if the matrix is empty * @throws NullPointerException if the matrix is null * @return The transposed matrix */ public static int[][] transpose(int[][] matrix) { if (matrix == null || matrix.length == 0) { throw new IllegalArgumentException("Matrix is empty"); } int rows = matrix.length; int cols = matrix[0].length; int[][] transposedMatrix = new int[cols][rows]; for (int i = 0; i < cols; i++) { for (int j = 0; j < rows; j++) { transposedMatrix[i][j] = matrix[j][i]; } } return transposedMatrix; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/matrixexponentiation/Fibonacci.java
src/main/java/com/thealgorithms/matrix/matrixexponentiation/Fibonacci.java
package com.thealgorithms.matrix.matrixexponentiation; import com.thealgorithms.matrix.utils.MatrixUtil; import java.math.BigDecimal; /** * @author Anirudh Buvanesh (https://github.com/anirudhb11) For more information * see https://www.geeksforgeeks.org/matrix-exponentiation/ * */ public final class Fibonacci { private Fibonacci() { } // Exponentiation matrix for Fibonacci sequence private static final BigDecimal ONE = BigDecimal.valueOf(1); private static final BigDecimal ZERO = BigDecimal.valueOf(0); private static final BigDecimal[][] FIB_MATRIX = {{ONE, ONE}, {ONE, ZERO}}; private static final BigDecimal[][] IDENTITY_MATRIX = {{ONE, ZERO}, {ZERO, ONE}}; /** * Calculates the fibonacci number using matrix exponentiaition technique * * @param n The input n for which we have to determine the fibonacci number * Outputs the nth * fibonacci number * @return a 2 X 1 array as { {F_n+1}, {F_n} } */ public static BigDecimal[][] fib(int n) { if (n == 0) { return IDENTITY_MATRIX; } else { BigDecimal[][] cachedResult = fib(n / 2); BigDecimal[][] matrixExpResult = MatrixUtil.multiply(cachedResult, cachedResult).get(); if (n % 2 == 0) { return matrixExpResult; } else { return MatrixUtil.multiply(FIB_MATRIX, matrixExpResult).get(); } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/matrix/utils/MatrixUtil.java
src/main/java/com/thealgorithms/matrix/utils/MatrixUtil.java
package com.thealgorithms.matrix.utils; import java.math.BigDecimal; import java.util.Optional; import java.util.function.BiFunction; import java.util.stream.IntStream; /** * @author: caos321 * @date: 31 October 2021 (Sunday) */ public final class MatrixUtil { private MatrixUtil() { } private static boolean isValid(final BigDecimal[][] matrix) { return matrix != null && matrix.length > 0 && matrix[0].length > 0; } private static boolean hasEqualSizes(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return isValid(matrix1) && isValid(matrix2) && matrix1.length == matrix2.length && matrix1[0].length == matrix2[0].length; } private static boolean canMultiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return isValid(matrix1) && isValid(matrix2) && matrix1[0].length == matrix2.length; } public static void validateInputMatrix(double[][] matrix) { if (matrix == null) { throw new IllegalArgumentException("The input matrix cannot be null"); } if (matrix.length == 0) { throw new IllegalArgumentException("The input matrix cannot be empty"); } if (!hasValidRows(matrix)) { throw new IllegalArgumentException("The input matrix cannot have null or empty rows"); } if (isJaggedMatrix(matrix)) { throw new IllegalArgumentException("The input matrix cannot be jagged"); } } private static boolean hasValidRows(double[][] matrix) { for (double[] row : matrix) { if (row == null || row.length == 0) { return false; } } return true; } /** * @brief Checks if the input matrix is a jagged matrix. * Jagged matrix is a matrix where the number of columns in each row is not the same. * * @param matrix The input matrix * @return True if the input matrix is a jagged matrix, false otherwise */ private static boolean isJaggedMatrix(double[][] matrix) { int numColumns = matrix[0].length; for (double[] row : matrix) { if (row.length != numColumns) { return true; } } return false; } private static Optional<BigDecimal[][]> operate(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2, final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation) { if (!hasEqualSizes(matrix1, matrix2)) { return Optional.empty(); } final int rowSize = matrix1.length; final int columnSize = matrix1[0].length; final BigDecimal[][] result = new BigDecimal[rowSize][columnSize]; IntStream.range(0, rowSize).forEach(rowIndex -> IntStream.range(0, columnSize).forEach(columnIndex -> { final BigDecimal value1 = matrix1[rowIndex][columnIndex]; final BigDecimal value2 = matrix2[rowIndex][columnIndex]; result[rowIndex][columnIndex] = operation.apply(value1, value2); })); return Optional.of(result); } public static Optional<BigDecimal[][]> add(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return operate(matrix1, matrix2, BigDecimal::add); } public static Optional<BigDecimal[][]> subtract(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return operate(matrix1, matrix2, BigDecimal::subtract); } public static Optional<BigDecimal[][]> multiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { if (!canMultiply(matrix1, matrix2)) { return Optional.empty(); } final int size = matrix1[0].length; final int matrix1RowSize = matrix1.length; final int matrix2ColumnSize = matrix2[0].length; final BigDecimal[][] result = new BigDecimal[matrix1RowSize][matrix2ColumnSize]; IntStream.range(0, matrix1RowSize) .forEach(rowIndex -> IntStream.range(0, matrix2ColumnSize) .forEach(columnIndex -> result[rowIndex][columnIndex] = IntStream.range(0, size) .mapToObj(index -> { final BigDecimal value1 = matrix1[rowIndex][index]; final BigDecimal value2 = matrix2[index][columnIndex]; return value1.multiply(value2); }) .reduce(BigDecimal.ZERO, BigDecimal::add))); return Optional.of(result); } public static double[] reverseRow(final double[] inRow) { double[] res = new double[inRow.length]; for (int i = 0; i < inRow.length; ++i) { res[i] = inRow[inRow.length - 1 - i]; } return res; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/geometry/DDALine.java
src/main/java/com/thealgorithms/geometry/DDALine.java
package com.thealgorithms.geometry; import java.awt.Point; import java.util.ArrayList; import java.util.List; /** * The {@code DDALine} class implements the Digital Differential Analyzer (DDA) * line drawing algorithm. It computes points along a line between two given * endpoints using floating-point arithmetic. * * The algorithm is straightforward but less efficient compared to * Bresenham’s line algorithm, since it relies on floating-point operations. * * For more information, please visit {@link https://en.wikipedia.org/wiki/Digital_differential_analyzer_(graphics_algorithm)} */ public final class DDALine { private DDALine() { // Prevent instantiation } /** * Finds the list of points forming a line between two endpoints using DDA. * * @param x0 the x-coordinate of the starting point * @param y0 the y-coordinate of the starting point * @param x1 the x-coordinate of the ending point * @param y1 the y-coordinate of the ending point * @return an unmodifiable {@code List<Point>} containing all points on the line */ public static List<Point> findLine(int x0, int y0, int x1, int y1) { int dx = x1 - x0; int dy = y1 - y0; int steps = Math.max(Math.abs(dx), Math.abs(dy)); // number of steps double xIncrement = dx / (double) steps; double yIncrement = dy / (double) steps; double x = x0; double y = y0; List<Point> line = new ArrayList<>(steps + 1); for (int i = 0; i <= steps; i++) { line.add(new Point((int) Math.round(x), (int) Math.round(y))); x += xIncrement; y += yIncrement; } return line; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/geometry/ConvexHull.java
src/main/java/com/thealgorithms/geometry/ConvexHull.java
package com.thealgorithms.geometry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * A class providing algorithms to compute the convex hull of a set of points * using brute-force and recursive methods. * * Convex hull: The smallest convex polygon that contains all the given points. * * Algorithms provided: * 1. Brute-Force Method * 2. Recursive (Divide-and-Conquer) Method * * @author Hardvan */ public final class ConvexHull { private ConvexHull() { } private static boolean checkPointOrientation(Point i, Point j, Point k) { int detK = Point.orientation(i, j, k); if (detK > 0) { return true; // pointsLeftOfIJ } else if (detK < 0) { return false; // pointsRightOfIJ } else { return k.compareTo(i) >= 0 && k.compareTo(j) <= 0; } } public static List<Point> convexHullBruteForce(List<Point> points) { Set<Point> convexSet = new TreeSet<>(Comparator.naturalOrder()); for (int i = 0; i < points.size() - 1; i++) { for (int j = i + 1; j < points.size(); j++) { boolean allPointsOnOneSide = true; boolean leftSide = checkPointOrientation(points.get(i), points.get(j), points.get((i + 1) % points.size())); for (int k = 0; k < points.size(); k++) { if (k != i && k != j && checkPointOrientation(points.get(i), points.get(j), points.get(k)) != leftSide) { allPointsOnOneSide = false; break; } } if (allPointsOnOneSide) { convexSet.add(points.get(i)); convexSet.add(points.get(j)); } } } return new ArrayList<>(convexSet); } /** * Computes the convex hull using a recursive divide-and-conquer approach. * Returns points in counter-clockwise order starting from the bottom-most, left-most point. * * @param points the input points * @return the convex hull points in counter-clockwise order */ public static List<Point> convexHullRecursive(List<Point> points) { if (points.size() < 3) { List<Point> result = new ArrayList<>(points); Collections.sort(result); return result; } Collections.sort(points); Set<Point> convexSet = new HashSet<>(); Point leftMostPoint = points.getFirst(); Point rightMostPoint = points.getLast(); convexSet.add(leftMostPoint); convexSet.add(rightMostPoint); List<Point> upperHull = new ArrayList<>(); List<Point> lowerHull = new ArrayList<>(); for (int i = 1; i < points.size() - 1; i++) { int det = Point.orientation(leftMostPoint, rightMostPoint, points.get(i)); if (det > 0) { upperHull.add(points.get(i)); } else if (det < 0) { lowerHull.add(points.get(i)); } } constructHull(upperHull, leftMostPoint, rightMostPoint, convexSet); constructHull(lowerHull, rightMostPoint, leftMostPoint, convexSet); // Convert to list and sort in counter-clockwise order return sortCounterClockwise(new ArrayList<>(convexSet)); } private static void constructHull(Collection<Point> points, Point left, Point right, Set<Point> convexSet) { if (!points.isEmpty()) { Point extremePoint = null; int extremePointDistance = Integer.MIN_VALUE; List<Point> candidatePoints = new ArrayList<>(); for (Point p : points) { int det = Point.orientation(left, right, p); if (det > 0) { candidatePoints.add(p); if (det > extremePointDistance) { extremePointDistance = det; extremePoint = p; } } } if (extremePoint != null) { constructHull(candidatePoints, left, extremePoint, convexSet); convexSet.add(extremePoint); constructHull(candidatePoints, extremePoint, right, convexSet); } } } /** * Sorts convex hull points in counter-clockwise order starting from * the bottom-most, left-most point. * * @param hullPoints the unsorted convex hull points * @return the points sorted in counter-clockwise order */ private static List<Point> sortCounterClockwise(List<Point> hullPoints) { if (hullPoints.size() <= 2) { Collections.sort(hullPoints); return hullPoints; } // Find the bottom-most, left-most point (pivot) Point pivot = hullPoints.getFirst(); for (Point p : hullPoints) { if (p.y() < pivot.y() || (p.y() == pivot.y() && p.x() < pivot.x())) { pivot = p; } } // Sort other points by polar angle with respect to pivot final Point finalPivot = pivot; List<Point> sorted = new ArrayList<>(hullPoints); sorted.remove(finalPivot); sorted.sort((p1, p2) -> { int crossProduct = Point.orientation(finalPivot, p1, p2); if (crossProduct == 0) { // Collinear points: sort by distance from pivot (closer first for convex hull) long dist1 = distanceSquared(finalPivot, p1); long dist2 = distanceSquared(finalPivot, p2); return Long.compare(dist1, dist2); } // Positive cross product means p2 is counter-clockwise from p1 // We want counter-clockwise order, so if p2 is CCW from p1, p1 should come first return -crossProduct; }); // Build result with pivot first, filtering out intermediate collinear points List<Point> result = new ArrayList<>(); result.add(finalPivot); if (!sorted.isEmpty()) { // This loop iterates through the points sorted by angle. // For points that are collinear with the pivot, we only want the one that is farthest away. // The sort places closer points first. for (int i = 0; i < sorted.size() - 1; i++) { // Check the orientation of the pivot, the current point, and the next point. int orientation = Point.orientation(finalPivot, sorted.get(i), sorted.get(i + 1)); // If the orientation is not 0, it means the next point (i+1) is at a new angle. // Therefore, the current point (i) must be the farthest point at its angle. We keep it. if (orientation != 0) { result.add(sorted.get(i)); } // If the orientation is 0, the points are collinear. We discard the current point (i) // because it is closer to the pivot than the next point (i+1). } // Always add the very last point from the sorted list. It is either the only point // at its angle, or it's the farthest among a set of collinear points. result.add(sorted.getLast()); } return result; } /** * Computes the squared distance between two points to avoid floating point operations. */ private static long distanceSquared(Point p1, Point p2) { long dx = (long) p1.x() - p2.x(); long dy = (long) p1.y() - p2.y(); return dx * dx + dy * dy; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/geometry/WusLine.java
src/main/java/com/thealgorithms/geometry/WusLine.java
package com.thealgorithms.geometry; import java.awt.Point; import java.util.ArrayList; import java.util.List; /** * The {@code WusLine} class implements Xiaolin Wu's line drawing algorithm, * which produces anti-aliased lines by varying pixel brightness * according to the line's proximity to pixel centers. * * This implementation returns the pixel coordinates along with * their associated intensity values (in range [0.0, 1.0]), allowing * rendering systems to blend accordingly. * * The algorithm works by: * - Computing a line's intersection with pixel boundaries * - Assigning intensity values based on distance from pixel centers * - Drawing pairs of pixels perpendicular to the line's direction * * Reference: Xiaolin Wu, "An Efficient Antialiasing Technique", * Computer Graphics (SIGGRAPH '91 Proceedings). * */ public final class WusLine { private WusLine() { // Utility class; prevent instantiation. } /** * Represents a pixel and its intensity for anti-aliased rendering. * * The intensity value determines how bright the pixel should be drawn, * with 1.0 being fully opaque and 0.0 being fully transparent. */ public static class Pixel { /** The pixel's coordinate on the screen. */ public final Point point; /** The pixel's intensity value, clamped to the range [0.0, 1.0]. */ public final double intensity; /** * Constructs a new Pixel with the given coordinates and intensity. * * @param x the x-coordinate of the pixel * @param y the y-coordinate of the pixel * @param intensity the brightness/opacity of the pixel, will be clamped to [0.0, 1.0] */ public Pixel(int x, int y, double intensity) { this.point = new Point(x, y); this.intensity = Math.clamp(intensity, 0.0, 1.0); } } /** * Internal class to hold processed endpoint data. */ private static class EndpointData { final int xPixel; final int yPixel; final double yEnd; final double xGap; EndpointData(int xPixel, int yPixel, double yEnd, double xGap) { this.xPixel = xPixel; this.yPixel = yPixel; this.yEnd = yEnd; this.xGap = xGap; } } /** * Draws an anti-aliased line using Wu's algorithm. * * The algorithm produces smooth lines by drawing pairs of pixels at each * x-coordinate (or y-coordinate for steep lines), with intensities based on * the line's distance from pixel centers. * * @param x0 the x-coordinate of the line's start point * @param y0 the y-coordinate of the line's start point * @param x1 the x-coordinate of the line's end point * @param y1 the y-coordinate of the line's end point * @return a list of {@link Pixel} objects representing the anti-aliased line, * ordered from start to end */ public static List<Pixel> drawLine(int x0, int y0, int x1, int y1) { List<Pixel> pixels = new ArrayList<>(); // Determine if the line is steep (more vertical than horizontal) boolean steep = Math.abs(y1 - y0) > Math.abs(x1 - x0); if (steep) { // For steep lines, swap x and y coordinates to iterate along y-axis int temp = x0; x0 = y0; y0 = temp; temp = x1; x1 = y1; y1 = temp; } if (x0 > x1) { // Ensure we always draw from left to right int temp = x0; x0 = x1; x1 = temp; temp = y0; y0 = y1; y1 = temp; } // Calculate the line's slope double deltaX = x1 - (double) x0; double deltaY = y1 - (double) y0; double gradient = (deltaX == 0) ? 1.0 : deltaY / deltaX; // Process the first endpoint EndpointData firstEndpoint = processEndpoint(x0, y0, gradient, true); addEndpointPixels(pixels, firstEndpoint, steep); // Process the second endpoint EndpointData secondEndpoint = processEndpoint(x1, y1, gradient, false); addEndpointPixels(pixels, secondEndpoint, steep); // Draw the main line between endpoints drawMainLine(pixels, firstEndpoint, secondEndpoint, gradient, steep); return pixels; } /** * Processes a line endpoint to determine its pixel coordinates and intensities. * * @param x the x-coordinate of the endpoint * @param y the y-coordinate of the endpoint * @param gradient the slope of the line * @param isStart true if this is the start endpoint, false if it's the end * @return an {@link EndpointData} object containing processed endpoint information */ private static EndpointData processEndpoint(double x, double y, double gradient, boolean isStart) { double xEnd = round(x); double yEnd = y + gradient * (xEnd - x); double xGap = isStart ? rfpart(x + 0.5) : fpart(x + 0.5); int xPixel = (int) xEnd; int yPixel = (int) Math.floor(yEnd); return new EndpointData(xPixel, yPixel, yEnd, xGap); } /** * Adds the two endpoint pixels (one above, one below the line) to the pixel list. * * @param pixels the list to add pixels to * @param endpoint the endpoint data containing coordinates and gaps * @param steep true if the line is steep (coordinates should be swapped) */ private static void addEndpointPixels(List<Pixel> pixels, EndpointData endpoint, boolean steep) { double fractionalY = fpart(endpoint.yEnd); double complementFractionalY = rfpart(endpoint.yEnd); if (steep) { pixels.add(new Pixel(endpoint.yPixel, endpoint.xPixel, complementFractionalY * endpoint.xGap)); pixels.add(new Pixel(endpoint.yPixel + 1, endpoint.xPixel, fractionalY * endpoint.xGap)); } else { pixels.add(new Pixel(endpoint.xPixel, endpoint.yPixel, complementFractionalY * endpoint.xGap)); pixels.add(new Pixel(endpoint.xPixel, endpoint.yPixel + 1, fractionalY * endpoint.xGap)); } } /** * Draws the main portion of the line between the two endpoints. * * @param pixels the list to add pixels to * @param firstEndpoint the processed start endpoint * @param secondEndpoint the processed end endpoint * @param gradient the slope of the line * @param steep true if the line is steep (coordinates should be swapped) */ private static void drawMainLine(List<Pixel> pixels, EndpointData firstEndpoint, EndpointData secondEndpoint, double gradient, boolean steep) { // Start y-intersection after the first endpoint double intersectionY = firstEndpoint.yEnd + gradient; // Iterate through x-coordinates between the endpoints for (int x = firstEndpoint.xPixel + 1; x < secondEndpoint.xPixel; x++) { int yFloor = (int) Math.floor(intersectionY); double fractionalPart = fpart(intersectionY); double complementFractionalPart = rfpart(intersectionY); if (steep) { pixels.add(new Pixel(yFloor, x, complementFractionalPart)); pixels.add(new Pixel(yFloor + 1, x, fractionalPart)); } else { pixels.add(new Pixel(x, yFloor, complementFractionalPart)); pixels.add(new Pixel(x, yFloor + 1, fractionalPart)); } intersectionY += gradient; } } /** * Returns the fractional part of a number. * * @param x the input number * @return the fractional part (always in range [0.0, 1.0)) */ private static double fpart(double x) { return x - Math.floor(x); } /** * Returns the reverse fractional part of a number (1 - fractional part). * * @param x the input number * @return 1.0 minus the fractional part (always in range (0.0, 1.0]) */ private static double rfpart(double x) { return 1.0 - fpart(x); } /** * Rounds a number to the nearest integer. * * @param x the input number * @return the nearest integer value as a double */ private static double round(double x) { return Math.floor(x + 0.5); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/geometry/MidpointCircle.java
src/main/java/com/thealgorithms/geometry/MidpointCircle.java
package com.thealgorithms.geometry; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Class to represent the Midpoint Circle Algorithm. * This algorithm calculates points on the circumference of a circle * using integer arithmetic for efficient computation. */ public final class MidpointCircle { private MidpointCircle() { // Private Constructor to prevent instantiation. } /** * Generates points on the circumference of a circle using the midpoint circle algorithm. * * @param centerX The x-coordinate of the circle's center. * @param centerY The y-coordinate of the circle's center. * @param radius The radius of the circle. * @return A list of points on the circle, each represented as an int[] with 2 elements [x, y]. */ public static List<int[]> generateCirclePoints(int centerX, int centerY, int radius) { List<int[]> points = new ArrayList<>(); // Special case for radius 0, only the center point should be added. if (radius == 0) { points.add(new int[] {centerX, centerY}); return points; } // Start at (radius, 0) int x = radius; int y = 0; // Decision parameter int p = 1 - radius; // Add the initial points in all octants addSymmetricPoints(points, centerX, centerY, x, y); // Iterate while x > y while (x > y) { y++; if (p <= 0) { // Midpoint is inside or on the circle p = p + 2 * y + 1; } else { // Midpoint is outside the circle x--; p = p + 2 * y - 2 * x + 1; } // Add points for this (x, y) addSymmetricPoints(points, centerX, centerY, x, y); } return points; } /** * Adds the symmetric points in all octants of the circle based on the current x and y values. * * @param points The list to which symmetric points will be added. * @param centerX The x-coordinate of the circle's center. * @param centerY The y-coordinate of the circle's center. * @param x The current x-coordinate on the circumference. * @param y The current y-coordinate on the circumference. */ private static void addSymmetricPoints(Collection<int[]> points, int centerX, int centerY, int x, int y) { // Octant symmetry points points.add(new int[] {centerX + x, centerY + y}); points.add(new int[] {centerX - x, centerY + y}); points.add(new int[] {centerX + x, centerY - y}); points.add(new int[] {centerX - x, centerY - y}); points.add(new int[] {centerX + y, centerY + x}); points.add(new int[] {centerX - y, centerY + x}); points.add(new int[] {centerX + y, centerY - x}); points.add(new int[] {centerX - y, centerY - x}); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/geometry/Point.java
src/main/java/com/thealgorithms/geometry/Point.java
package com.thealgorithms.geometry; import java.util.Comparator; public record Point(int x, int y) implements Comparable<Point> { @Override public int compareTo(Point other) { int cmpY = Integer.compare(this.y, other.y); return cmpY != 0 ? cmpY : Integer.compare(this.x, other.x); } @Override public String toString() { return String.format("(%d, %d)", x, y); } public Comparator<Point> polarOrder() { return new PolarOrder(); } public static int orientation(Point a, Point b, Point c) { return Integer.compare((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x), 0); } private final class PolarOrder implements Comparator<Point> { @Override public int compare(Point p1, Point p2) { int dx1 = p1.x - x; int dy1 = p1.y - y; int dx2 = p2.x - x; int dy2 = p2.y - y; if (dy1 >= 0 && dy2 < 0) { return -1; // p1 above p2 } else if (dy2 >= 0 && dy1 < 0) { return 1; // p1 below p2 } else if (dy1 == 0 && dy2 == 0) { // Collinear and horizontal return Integer.compare(dx2, dx1); } else { return -orientation(Point.this, p1, p2); // Compare orientation } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/geometry/Haversine.java
src/main/java/com/thealgorithms/geometry/Haversine.java
package com.thealgorithms.geometry; /** * This Class implements the Haversine formula to calculate the distance between two points on a sphere (like Earth) from their latitudes and longitudes. * * The Haversine formula is used in navigation and mapping to find the great-circle distance, * which is the shortest distance between two points along the surface of a sphere. It is often * used to calculate the "as the crow flies" distance between two geographical locations. * * The formula is reliable for all distances, including small ones, and avoids issues with * numerical instability that can affect other methods. * * @see "https://en.wikipedia.org/wiki/Haversine_formula" - Wikipedia */ public final class Haversine { // Average radius of Earth in kilometers private static final double EARTH_RADIUS_KM = 6371.0; /** * Private constructor to prevent instantiation of this utility class. */ private Haversine() { } /** * Calculates the great-circle distance between two points on the earth * (specified in decimal degrees). * * @param lat1 Latitude of the first point in decimal degrees. * @param lon1 Longitude of the first point in decimal degrees. * @param lat2 Latitude of the second point in decimal degrees. * @param lon2 Longitude of the second point in decimal degrees. * @return The distance between the two points in kilometers. */ public static double haversine(double lat1, double lon1, double lat2, double lon2) { // Convert latitude and longitude from degrees to radians double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); // Apply the Haversine formula double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1Rad) * Math.cos(lat2Rad); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return EARTH_RADIUS_KM * c; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/geometry/GrahamScan.java
src/main/java/com/thealgorithms/geometry/GrahamScan.java
package com.thealgorithms.geometry; import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; /** * A Java program that computes the convex hull using the Graham Scan algorithm. * The time complexity is O(n) in the best case and O(n log(n)) in the worst case. * The space complexity is O(n). * This algorithm is applicable only to integral coordinates. * * References: * https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/geometry/graham_scan_algorithm.cpp * https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/geometry/graham_scan_functions.hpp * https://algs4.cs.princeton.edu/99hull/GrahamScan.java.html */ public class GrahamScan { private final Stack<Point> hull = new Stack<>(); public GrahamScan(Point[] points) { // Pre-process points: sort by y-coordinate, then by polar order with respect to the first point Arrays.sort(points); Arrays.sort(points, 1, points.length, points[0].polarOrder()); hull.push(points[0]); // Find the first point not equal to points[0] (firstNonEqualIndex) // and the first point not collinear firstNonCollinearIndex with the previous points int firstNonEqualIndex; for (firstNonEqualIndex = 1; firstNonEqualIndex < points.length; firstNonEqualIndex++) { if (!points[0].equals(points[firstNonEqualIndex])) { break; } } if (firstNonEqualIndex == points.length) { return; } int firstNonCollinearIndex; for (firstNonCollinearIndex = firstNonEqualIndex + 1; firstNonCollinearIndex < points.length; firstNonCollinearIndex++) { if (Point.orientation(points[0], points[firstNonEqualIndex], points[firstNonCollinearIndex]) != 0) { break; } } hull.push(points[firstNonCollinearIndex - 1]); // Process the remaining points and update the hull for (int i = firstNonCollinearIndex; i < points.length; i++) { Point top = hull.pop(); while (Point.orientation(hull.peek(), top, points[i]) <= 0) { top = hull.pop(); } hull.push(top); hull.push(points[i]); } } /** * @return An iterable collection of points representing the convex hull. */ public Iterable<Point> hull() { return new ArrayList<>(hull); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/geometry/BresenhamLine.java
src/main/java/com/thealgorithms/geometry/BresenhamLine.java
package com.thealgorithms.geometry; import java.awt.Point; import java.util.ArrayList; import java.util.List; /** * The {@code BresenhamLine} class implements the Bresenham's line algorithm, * which is an efficient way to determine the points of a straight line * between two given points in a 2D space. * * <p>This algorithm uses integer arithmetic to calculate the points, * making it suitable for rasterization in computer graphics.</p> * * For more information, please visit {@link https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm} */ public final class BresenhamLine { private BresenhamLine() { // Private constructor to prevent instantiation. } /** * Finds the list of points that form a straight line between two endpoints. * * @param x0 the x-coordinate of the starting point * @param y0 the y-coordinate of the starting point * @param x1 the x-coordinate of the ending point * @param y1 the y-coordinate of the ending point * @return a {@code List<Point>} containing all points on the line */ public static List<Point> findLine(int x0, int y0, int x1, int y1) { List<Point> line = new ArrayList<>(); // Calculate differences and steps for each axis int dx = Math.abs(x1 - x0); // Change in x int dy = Math.abs(y1 - y0); // Change in y int sx = (x0 < x1) ? 1 : -1; // Step in x direction int sy = (y0 < y1) ? 1 : -1; // Step in y direction int err = dx - dy; // Initial error term // Loop until we reach the endpoint while (true) { line.add(new Point(x0, y0)); // Add current point to the line // Check if we've reached the endpoint if (x0 == x1 && y0 == y1) { break; // Exit loop if endpoint is reached } // Calculate error term doubled for decision making final int e2 = err * 2; // Adjust x coordinate if necessary if (e2 > -dy) { err -= dy; // Update error term x0 += sx; // Move to next point in x direction } // Adjust y coordinate if necessary if (e2 < dx) { err += dx; // Update error term y0 += sy; // Move to next point in y direction } } return line; // Return the list of points forming the line } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/geometry/MidpointEllipse.java
src/main/java/com/thealgorithms/geometry/MidpointEllipse.java
package com.thealgorithms.geometry; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * The MidpointEllipse class implements the Midpoint Ellipse Drawing Algorithm. * This algorithm efficiently computes the points on an ellipse by dividing it into two regions * and using decision parameters to determine the next point to plot. */ public final class MidpointEllipse { private MidpointEllipse() { // Private constructor to prevent instantiation } /** * Draws an ellipse using the Midpoint Ellipse Algorithm. * * @param centerX the x-coordinate of the center of the ellipse * @param centerY the y-coordinate of the center of the ellipse * @param a the length of the semi-major axis (horizontal radius) * @param b the length of the semi-minor axis (vertical radius) * @return a list of points (represented as int arrays) that form the ellipse */ public static List<int[]> drawEllipse(int centerX, int centerY, int a, int b) { List<int[]> points = new ArrayList<>(); // Handle degenerate cases with early returns if (a == 0 && b == 0) { points.add(new int[] {centerX, centerY}); // Only the center point return points; } if (a == 0) { // Semi-major axis is zero, create a vertical line for (int y = centerY - b; y <= centerY + b; y++) { points.add(new int[] {centerX, y}); } return points; // Early return } if (b == 0) { // Semi-minor axis is zero, create a horizontal line for (int x = centerX - a; x <= centerX + a; x++) { points.add(new int[] {x, centerY}); } return points; // Early return } // Normal case: Non-degenerate ellipse computeEllipsePoints(points, centerX, centerY, a, b); return points; // Return all calculated points of the ellipse } /** * Computes points of a non-degenerate ellipse using the Midpoint Ellipse Algorithm. * * @param points the list to which points will be added * @param centerX the x-coordinate of the center of the ellipse * @param centerY the y-coordinate of the center of the ellipse * @param a the length of the semi-major axis (horizontal radius) * @param b the length of the semi-minor axis (vertical radius) */ private static void computeEllipsePoints(Collection<int[]> points, int centerX, int centerY, int a, int b) { int x = 0; // Initial x-coordinate int y = b; // Initial y-coordinate // Region 1: Initial decision parameter double d1 = (b * b) - (a * a * b) + (0.25 * a * a); // Decision variable for region 1 double dx = 2.0 * b * b * x; // Change in x double dy = 2.0 * a * a * y; // Change in y // Region 1: When the slope is less than 1 while (dx < dy) { addEllipsePoints(points, centerX, centerY, x, y); // Update decision parameter and variables if (d1 < 0) { x++; dx += (2 * b * b); // Update x change d1 += dx + (b * b); // Update decision parameter } else { x++; y--; dx += (2 * b * b); // Update x change dy -= (2 * a * a); // Update y change d1 += dx - dy + (b * b); // Update decision parameter } } // Region 2: Initial decision parameter for the second region double d2 = b * b * (x + 0.5) * (x + 0.5) + a * a * (y - 1) * (y - 1) - a * a * b * b; // Region 2: When the slope is greater than or equal to 1 while (y >= 0) { addEllipsePoints(points, centerX, centerY, x, y); // Update decision parameter and variables if (d2 > 0) { y--; dy -= (2 * a * a); // Update y change d2 += (a * a) - dy; // Update decision parameter } else { y--; x++; dx += (2 * b * b); // Update x change dy -= (2 * a * a); // Update y change d2 += dx - dy + (a * a); // Update decision parameter } } } /** * Adds points for all four quadrants of the ellipse based on symmetry. * * @param points the list to which points will be added * @param centerX the x-coordinate of the center of the ellipse * @param centerY the y-coordinate of the center of the ellipse * @param x the x-coordinate relative to the center * @param y the y-coordinate relative to the center */ private static void addEllipsePoints(Collection<int[]> points, int centerX, int centerY, int x, int y) { points.add(new int[] {centerX + x, centerY + y}); points.add(new int[] {centerX - x, centerY + y}); points.add(new int[] {centerX + x, centerY - y}); points.add(new int[] {centerX - x, centerY - y}); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/geometry/BentleyOttmann.java
src/main/java/com/thealgorithms/geometry/BentleyOttmann.java
package com.thealgorithms.geometry; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Objects; import java.util.PriorityQueue; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Implementation of the Bentley–Ottmann algorithm for finding all intersection * points among a set of line segments in O((n + k) log n) time. * * <p>Uses a sweep-line approach with an event queue and status structure to * efficiently detect intersections in 2D plane geometry.</p> * * @see <a href="https://en.wikipedia.org/wiki/Bentley%E2%80%93Ottmann_algorithm"> * Bentley–Ottmann algorithm</a> */ public final class BentleyOttmann { private BentleyOttmann() { } private static final double EPS = 1e-9; private static double currentSweepX; /** * Represents a line segment with two endpoints. */ public static class Segment { final Point2D.Double p1; final Point2D.Double p2; final int id; // Unique identifier for each segment Segment(Point2D.Double p1, Point2D.Double p2) { this.p1 = p1; this.p2 = p2; this.id = segmentCounter++; } private static int segmentCounter = 0; /** * Computes the y-coordinate of this segment at a given x value. */ double getY(double x) { if (Math.abs(p2.x - p1.x) < EPS) { // Vertical segment: return midpoint y return (p1.y + p2.y) / 2.0; } double t = (x - p1.x) / (p2.x - p1.x); return p1.y + t * (p2.y - p1.y); } Point2D.Double leftPoint() { return p1.x < p2.x ? p1 : p1.x > p2.x ? p2 : p1.y < p2.y ? p1 : p2; } Point2D.Double rightPoint() { return p1.x > p2.x ? p1 : p1.x < p2.x ? p2 : p1.y > p2.y ? p1 : p2; } @Override public String toString() { return String.format("S%d[(%.2f, %.2f), (%.2f, %.2f)]", id, p1.x, p1.y, p2.x, p2.y); } } /** * Event types for the sweep line algorithm. */ private enum EventType { START, END, INTERSECTION } /** * Represents an event in the event queue. */ private static class Event implements Comparable<Event> { final Point2D.Double point; final EventType type; final Set<Segment> segments; // Segments involved in this event Event(Point2D.Double point, EventType type) { this.point = point; this.type = type; this.segments = new HashSet<>(); } void addSegment(Segment s) { segments.add(s); } @Override public int compareTo(Event other) { // Sort by x-coordinate, then by y-coordinate int cmp = Double.compare(this.point.x, other.point.x); if (cmp == 0) { cmp = Double.compare(this.point.y, other.point.y); } if (cmp == 0) { // Process END events before START events at same point cmp = this.type.compareTo(other.type); } return cmp; } @Override public boolean equals(Object o) { if (!(o instanceof Event e)) { return false; } return pointsEqual(this.point, e.point); } @Override public int hashCode() { return Objects.hash(Math.round(point.x * 1e6), Math.round(point.y * 1e6)); } } /** * Comparator for segments in the status structure (sweep line). * Orders segments by their y-coordinate at the current sweep line position. */ private static final class StatusComparator implements Comparator<Segment> { @Override public int compare(Segment s1, Segment s2) { if (s1.id == s2.id) { return 0; } double y1 = s1.getY(currentSweepX); double y2 = s2.getY(currentSweepX); int cmp = Double.compare(y1, y2); if (Math.abs(y1 - y2) < EPS) { // If y-coordinates are equal, use segment id for consistency return Integer.compare(s1.id, s2.id); } return cmp; } } /** * Finds all intersection points among a set of line segments. * * <p>An intersection point is reported when two or more segments cross or touch. * For overlapping segments, only actual crossing/touching points are reported, * not all points along the overlap.</p> * * @param segments list of line segments represented as pairs of points * @return a set of intersection points where segments meet or cross * @throws IllegalArgumentException if the list is null or contains null points */ public static Set<Point2D.Double> findIntersections(List<Segment> segments) { if (segments == null) { throw new IllegalArgumentException("Segment list must not be null"); } Segment.segmentCounter = 0; // Reset counter Set<Point2D.Double> intersections = new HashSet<>(); PriorityQueue<Event> eventQueue = new PriorityQueue<>(); TreeSet<Segment> status = new TreeSet<>(new StatusComparator()); Map<Point2D.Double, Event> eventMap = new HashMap<>(); // Initialize event queue with segment start and end points for (Segment s : segments) { Point2D.Double left = s.leftPoint(); Point2D.Double right = s.rightPoint(); Event startEvent = getOrCreateEvent(eventMap, left, EventType.START); startEvent.addSegment(s); Event endEvent = getOrCreateEvent(eventMap, right, EventType.END); endEvent.addSegment(s); } // Add all unique events to the queue for (Event e : eventMap.values()) { if (!e.segments.isEmpty()) { eventQueue.add(e); } } // Process events while (!eventQueue.isEmpty()) { Event event = eventQueue.poll(); currentSweepX = event.point.x; handleEvent(event, status, eventQueue, eventMap, intersections); } return intersections; } private static Event getOrCreateEvent(Map<Point2D.Double, Event> eventMap, Point2D.Double point, EventType type) { // Find existing event at this point for (Map.Entry<Point2D.Double, Event> entry : eventMap.entrySet()) { if (pointsEqual(entry.getKey(), point)) { return entry.getValue(); } } // Create new event Event event = new Event(point, type); eventMap.put(point, event); return event; } private static void handleEvent(Event event, TreeSet<Segment> status, PriorityQueue<Event> eventQueue, Map<Point2D.Double, Event> eventMap, Set<Point2D.Double> intersections) { Point2D.Double p = event.point; Set<Segment> segmentsAtPoint = new HashSet<>(event.segments); // Check segments in status structure (much smaller than allSegments) for (Segment s : status) { if (pointsEqual(s.p1, p) || pointsEqual(s.p2, p) || (onSegment(s, p) && !pointsEqual(s.p1, p) && !pointsEqual(s.p2, p))) { segmentsAtPoint.add(s); } } // If 2 or more segments meet at this point, it's an intersection if (segmentsAtPoint.size() >= 2) { intersections.add(p); } // Categorize segments Set<Segment> upperSegs = new HashSet<>(); // Segments starting at p Set<Segment> lowerSegs = new HashSet<>(); // Segments ending at p Set<Segment> containingSegs = new HashSet<>(); // Segments containing p in interior for (Segment s : segmentsAtPoint) { if (pointsEqual(s.leftPoint(), p)) { upperSegs.add(s); } else if (pointsEqual(s.rightPoint(), p)) { lowerSegs.add(s); } else { containingSegs.add(s); } } // Remove ending segments and segments containing p from status status.removeAll(lowerSegs); status.removeAll(containingSegs); // Update sweep line position slightly past the event currentSweepX = p.x + EPS; // Add starting segments and re-add containing segments status.addAll(upperSegs); status.addAll(containingSegs); if (upperSegs.isEmpty() && containingSegs.isEmpty()) { // Find neighbors and check for new intersections Segment sl = getNeighbor(status, lowerSegs, true); Segment sr = getNeighbor(status, lowerSegs, false); if (sl != null && sr != null) { findNewEvent(sl, sr, p, eventQueue, eventMap); } } else { Set<Segment> unionSegs = new HashSet<>(upperSegs); unionSegs.addAll(containingSegs); Segment leftmost = getLeftmost(unionSegs, status); Segment rightmost = getRightmost(unionSegs, status); if (leftmost != null) { Segment sl = status.lower(leftmost); if (sl != null) { findNewEvent(sl, leftmost, p, eventQueue, eventMap); } } if (rightmost != null) { Segment sr = status.higher(rightmost); if (sr != null) { findNewEvent(rightmost, sr, p, eventQueue, eventMap); } } } } private static Segment getNeighbor(NavigableSet<Segment> status, Set<Segment> removed, boolean lower) { if (removed.isEmpty()) { return null; } Segment ref = removed.iterator().next(); return lower ? status.lower(ref) : status.higher(ref); } private static Segment getLeftmost(Set<Segment> segments, SortedSet<Segment> status) { Segment leftmost = null; for (Segment s : segments) { if (leftmost == null || Objects.requireNonNull(status.comparator()).compare(s, leftmost) < 0) { leftmost = s; } } return leftmost; } private static Segment getRightmost(Set<Segment> segments, SortedSet<Segment> status) { Segment rightmost = null; for (Segment s : segments) { if (status.comparator() != null && (rightmost == null || status.comparator().compare(s, rightmost) > 0)) { rightmost = s; } } return rightmost; } private static void findNewEvent(Segment s1, Segment s2, Point2D.Double currentPoint, PriorityQueue<Event> eventQueue, Map<Point2D.Double, Event> eventMap) { Point2D.Double intersection = getIntersection(s1, s2); if (intersection != null && intersection.x > currentPoint.x - EPS && !pointsEqual(intersection, currentPoint)) { // Check if event already exists boolean exists = false; for (Map.Entry<Point2D.Double, Event> entry : eventMap.entrySet()) { if (pointsEqual(entry.getKey(), intersection)) { exists = true; Event existingEvent = entry.getValue(); existingEvent.addSegment(s1); existingEvent.addSegment(s2); break; } } if (!exists) { Event newEvent = new Event(intersection, EventType.INTERSECTION); newEvent.addSegment(s1); newEvent.addSegment(s2); eventMap.put(intersection, newEvent); eventQueue.add(newEvent); } } } private static Point2D.Double getIntersection(Segment s1, Segment s2) { double x1 = s1.p1.x; double y1 = s1.p1.y; double x2 = s1.p2.x; double y2 = s1.p2.y; double x3 = s2.p1.x; double y3 = s2.p1.y; double x4 = s2.p2.x; double y4 = s2.p2.y; double denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (Math.abs(denom) < EPS) { // Parallel or collinear if (areCollinear(s1, s2)) { // For collinear segments, check if they overlap // Return any overlapping point List<Point2D.Double> overlapPoints = new ArrayList<>(); if (onSegment(s1, s2.p1)) { overlapPoints.add(s2.p1); } if (onSegment(s1, s2.p2)) { overlapPoints.add(s2.p2); } if (onSegment(s2, s1.p1)) { overlapPoints.add(s1.p1); } if (onSegment(s2, s1.p2)) { overlapPoints.add(s1.p2); } // Remove duplicates and return the first point if (!overlapPoints.isEmpty()) { // Find the point that's not an endpoint of both segments for (Point2D.Double pt : overlapPoints) { boolean isS1Endpoint = pointsEqual(pt, s1.p1) || pointsEqual(pt, s1.p2); boolean isS2Endpoint = pointsEqual(pt, s2.p1) || pointsEqual(pt, s2.p2); // If it's an endpoint of both, it's a touching point if (isS1Endpoint && isS2Endpoint) { return pt; } } // Return the first overlap point return overlapPoints.getFirst(); } } return null; } double t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denom; double u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / denom; if (t >= -EPS && t <= 1 + EPS && u >= -EPS && u <= 1 + EPS) { double px = x1 + t * (x2 - x1); double py = y1 + t * (y2 - y1); return new Point2D.Double(px, py); } return null; } private static boolean areCollinear(Segment s1, Segment s2) { double cross1 = crossProduct(s1.p1, s1.p2, s2.p1); double cross2 = crossProduct(s1.p1, s1.p2, s2.p2); return Math.abs(cross1) < EPS && Math.abs(cross2) < EPS; } private static double crossProduct(Point2D.Double a, Point2D.Double b, Point2D.Double c) { return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); } private static boolean onSegment(Segment s, Point2D.Double p) { return p.x >= Math.min(s.p1.x, s.p2.x) - EPS && p.x <= Math.max(s.p1.x, s.p2.x) + EPS && p.y >= Math.min(s.p1.y, s.p2.y) - EPS && p.y <= Math.max(s.p1.y, s.p2.y) + EPS && Math.abs(crossProduct(s.p1, s.p2, p)) < EPS; } private static boolean pointsEqual(Point2D.Double p1, Point2D.Double p2) { return Math.abs(p1.x - p2.x) < EPS && Math.abs(p1.y - p2.y) < EPS; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/NumberToWords.java
src/main/java/com/thealgorithms/conversions/NumberToWords.java
package com.thealgorithms.conversions; import java.math.BigDecimal; /** A Java-based utility for converting numeric values into their English word representations. Whether you need to convert a small number, a large number with millions and billions, or even a number with decimal places, this utility has you covered. * */ public final class NumberToWords { private NumberToWords() { } private static final String[] UNITS = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; private static final String[] TENS = {"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; private static final String[] POWERS = {"", "Thousand", "Million", "Billion", "Trillion"}; private static final String ZERO = "Zero"; private static final String POINT = " Point"; private static final String NEGATIVE = "Negative "; public static String convert(BigDecimal number) { if (number == null) { return "Invalid Input"; } // Check for negative sign boolean isNegative = number.signum() < 0; // Split the number into whole and fractional parts BigDecimal[] parts = number.abs().divideAndRemainder(BigDecimal.ONE); BigDecimal wholePart = parts[0]; // Keep whole part as BigDecimal String fractionalPartStr = parts[1].compareTo(BigDecimal.ZERO) > 0 ? parts[1].toPlainString().substring(2) : ""; // Get fractional part only if it exists // Convert whole part to words StringBuilder result = new StringBuilder(); if (isNegative) { result.append(NEGATIVE); } result.append(convertWholeNumberToWords(wholePart)); // Convert fractional part to words if (!fractionalPartStr.isEmpty()) { result.append(POINT); for (char digit : fractionalPartStr.toCharArray()) { int digitValue = Character.getNumericValue(digit); result.append(" ").append(digitValue == 0 ? ZERO : UNITS[digitValue]); } } return result.toString().trim(); } private static String convertWholeNumberToWords(BigDecimal number) { if (number.compareTo(BigDecimal.ZERO) == 0) { return ZERO; } StringBuilder words = new StringBuilder(); int power = 0; while (number.compareTo(BigDecimal.ZERO) > 0) { // Get the last three digits BigDecimal[] divisionResult = number.divideAndRemainder(BigDecimal.valueOf(1000)); int chunk = divisionResult[1].intValue(); if (chunk > 0) { String chunkWords = convertChunk(chunk); if (power > 0) { words.insert(0, POWERS[power] + " "); } words.insert(0, chunkWords + " "); } number = divisionResult[0]; // Continue with the remaining part power++; } return words.toString().trim(); } private static String convertChunk(int number) { String chunkWords; if (number < 20) { chunkWords = UNITS[number]; } else if (number < 100) { chunkWords = TENS[number / 10] + (number % 10 > 0 ? " " + UNITS[number % 10] : ""); } else { chunkWords = UNITS[number / 100] + " Hundred" + (number % 100 > 0 ? " " + convertChunk(number % 100) : ""); } return chunkWords; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/TimeConverter.java
src/main/java/com/thealgorithms/conversions/TimeConverter.java
package com.thealgorithms.conversions; import java.util.Locale; import java.util.Map; /** * A utility class to convert between different units of time. * * <p>This class supports conversions between the following units: * <ul> * <li>seconds</li> * <li>minutes</li> * <li>hours</li> * <li>days</li> * <li>weeks</li> * <li>months (approximated as 30.44 days)</li> * <li>years (approximated as 365.25 days)</li> * </ul> * * <p>The conversion is based on predefined constants in seconds. * Results are rounded to three decimal places for consistency. * * <p>This class is final and cannot be instantiated. * * @see <a href="https://en.wikipedia.org/wiki/Unit_of_time">Wikipedia: Unit of time</a> */ public final class TimeConverter { private TimeConverter() { // Prevent instantiation } /** * Supported time units with their equivalent in seconds. */ private enum TimeUnit { SECONDS(1.0), MINUTES(60.0), HOURS(3600.0), DAYS(86400.0), WEEKS(604800.0), MONTHS(2629800.0), // 30.44 days YEARS(31557600.0); // 365.25 days private final double seconds; TimeUnit(double seconds) { this.seconds = seconds; } public double toSeconds(double value) { return value * seconds; } public double fromSeconds(double secondsValue) { return secondsValue / seconds; } } private static final Map<String, TimeUnit> UNIT_LOOKUP = Map.ofEntries(Map.entry("seconds", TimeUnit.SECONDS), Map.entry("minutes", TimeUnit.MINUTES), Map.entry("hours", TimeUnit.HOURS), Map.entry("days", TimeUnit.DAYS), Map.entry("weeks", TimeUnit.WEEKS), Map.entry("months", TimeUnit.MONTHS), Map.entry("years", TimeUnit.YEARS)); /** * Converts a time value from one unit to another. * * @param timeValue the numeric value of time to convert; must be non-negative * @param unitFrom the unit of the input value (e.g., "minutes", "hours") * @param unitTo the unit to convert into (e.g., "seconds", "days") * @return the converted value in the target unit, rounded to three decimals * @throws IllegalArgumentException if {@code timeValue} is negative * @throws IllegalArgumentException if either {@code unitFrom} or {@code unitTo} is not supported */ public static double convertTime(double timeValue, String unitFrom, String unitTo) { if (timeValue < 0) { throw new IllegalArgumentException("timeValue must be a non-negative number."); } TimeUnit from = resolveUnit(unitFrom); TimeUnit to = resolveUnit(unitTo); double secondsValue = from.toSeconds(timeValue); double converted = to.fromSeconds(secondsValue); return Math.round(converted * 1000.0) / 1000.0; } private static TimeUnit resolveUnit(String unit) { if (unit == null) { throw new IllegalArgumentException("Unit cannot be null."); } TimeUnit resolved = UNIT_LOOKUP.get(unit.toLowerCase(Locale.ROOT)); if (resolved == null) { throw new IllegalArgumentException("Invalid unit '" + unit + "'. Supported units are: " + UNIT_LOOKUP.keySet()); } return resolved; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/EndianConverter.java
src/main/java/com/thealgorithms/conversions/EndianConverter.java
package com.thealgorithms.conversions; /** * Utility class for converting integers between big-endian and little-endian formats. * <p> * Endianness defines how byte sequences represent multi-byte data types: * <ul> * <li><b>Big-endian</b>: The most significant byte (MSB) comes first.</li> * <li><b>Little-endian</b>: The least significant byte (LSB) comes first.</li> * </ul> * <p> * Example conversion: * <ul> * <li>Big-endian to little-endian: {@code 0x12345678} → {@code 0x78563412}</li> * <li>Little-endian to big-endian: {@code 0x78563412} → {@code 0x12345678}</li> * </ul> * * <p>Note: Both conversions in this utility are equivalent since reversing the bytes is symmetric.</p> * * <p>This class only supports 32-bit integers.</p> * * @author Hardvan */ public final class EndianConverter { private EndianConverter() { } /** * Converts a 32-bit integer from big-endian to little-endian. * * @param value the integer in big-endian format * @return the integer in little-endian format */ public static int bigToLittleEndian(int value) { return Integer.reverseBytes(value); } /** * Converts a 32-bit integer from little-endian to big-endian. * * @param value the integer in little-endian format * @return the integer in big-endian format */ public static int littleToBigEndian(int value) { return Integer.reverseBytes(value); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java
src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java
package com.thealgorithms.conversions; import java.util.Map; /** * A utility class to convert integers to their English word representation. * * <p>The class supports conversion of numbers from 0 to 2,147,483,647 * (the maximum value of a 32-bit signed integer). It divides the number * into groups of three digits (thousands, millions, billions, etc.) and * translates each group into words.</p> * * <h2>Example Usage</h2> * <pre> * IntegerToEnglish.integerToEnglishWords(12345); * // Output: "Twelve Thousand Three Hundred Forty Five" * </pre> * * <p>This class uses two maps:</p> * <ul> * <li>BASE_NUMBERS_MAP: Holds English words for numbers 0-20, multiples of 10 up to 90, and 100.</li> * <li>THOUSAND_POWER_MAP: Maps powers of 1000 (e.g., Thousand, Million, Billion).</li> * </ul> */ public final class IntegerToEnglish { private static final Map<Integer, String> BASE_NUMBERS_MAP = Map.ofEntries(Map.entry(0, ""), Map.entry(1, "One"), Map.entry(2, "Two"), Map.entry(3, "Three"), Map.entry(4, "Four"), Map.entry(5, "Five"), Map.entry(6, "Six"), Map.entry(7, "Seven"), Map.entry(8, "Eight"), Map.entry(9, "Nine"), Map.entry(10, "Ten"), Map.entry(11, "Eleven"), Map.entry(12, "Twelve"), Map.entry(13, "Thirteen"), Map.entry(14, "Fourteen"), Map.entry(15, "Fifteen"), Map.entry(16, "Sixteen"), Map.entry(17, "Seventeen"), Map.entry(18, "Eighteen"), Map.entry(19, "Nineteen"), Map.entry(20, "Twenty"), Map.entry(30, "Thirty"), Map.entry(40, "Forty"), Map.entry(50, "Fifty"), Map.entry(60, "Sixty"), Map.entry(70, "Seventy"), Map.entry(80, "Eighty"), Map.entry(90, "Ninety"), Map.entry(100, "Hundred")); private static final Map<Integer, String> THOUSAND_POWER_MAP = Map.ofEntries(Map.entry(1, "Thousand"), Map.entry(2, "Million"), Map.entry(3, "Billion")); private IntegerToEnglish() { } /** * Converts numbers less than 1000 into English words. * * @param number the integer value (0-999) to convert * @return the English word representation of the input number */ private static String convertToWords(int number) { int remainder = number % 100; StringBuilder result = new StringBuilder(); if (remainder <= 20) { result.append(BASE_NUMBERS_MAP.get(remainder)); } else if (BASE_NUMBERS_MAP.containsKey(remainder)) { result.append(BASE_NUMBERS_MAP.get(remainder)); } else { int tensDigit = remainder / 10; int onesDigit = remainder % 10; String tens = BASE_NUMBERS_MAP.getOrDefault(tensDigit * 10, ""); String ones = BASE_NUMBERS_MAP.getOrDefault(onesDigit, ""); result.append(tens); if (ones != null && !ones.isEmpty()) { result.append(" ").append(ones); } } int hundredsDigit = number / 100; if (hundredsDigit > 0) { if (result.length() > 0) { result.insert(0, " "); } result.insert(0, String.format("%s Hundred", BASE_NUMBERS_MAP.get(hundredsDigit))); } return result.toString().trim(); } /** * Converts a non-negative integer to its English word representation. * * @param number the integer to convert (0-2,147,483,647) * @return the English word representation of the input number */ public static String integerToEnglishWords(int number) { if (number == 0) { return "Zero"; } StringBuilder result = new StringBuilder(); int index = 0; while (number > 0) { int remainder = number % 1000; number /= 1000; if (remainder > 0) { String subResult = convertToWords(remainder); if (!subResult.isEmpty()) { if (index > 0) { subResult += " " + THOUSAND_POWER_MAP.get(index); } if (result.length() > 0) { result.insert(0, " "); } result.insert(0, subResult); } } index++; } return result.toString().trim(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java
src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java
package com.thealgorithms.conversions; /** * Utility class for converting a hexadecimal string to its decimal representation. * <p> * A hexadecimal number uses the base-16 numeral system, with the following characters: * <ul> * <li>Digits: 0-9</li> * <li>Letters: A-F (case-insensitive)</li> * </ul> * Each character represents a power of 16. For example: * <pre> * Hexadecimal "A1" = 10*16^1 + 1*16^0 = 161 (decimal) * </pre> * * <p>This class provides a method to perform the conversion without using built-in Java utilities.</p> */ public final class HexaDecimalToDecimal { private HexaDecimalToDecimal() { } /** * Converts a hexadecimal string to its decimal integer equivalent. * <p>The input string is case-insensitive, and must contain valid hexadecimal characters [0-9, A-F].</p> * * @param hex the hexadecimal string to convert * @return the decimal integer representation of the input hexadecimal string * @throws IllegalArgumentException if the input string contains invalid characters */ public static int getHexaToDec(String hex) { String digits = "0123456789ABCDEF"; hex = hex.toUpperCase(); int val = 0; for (int i = 0; i < hex.length(); i++) { int d = digits.indexOf(hex.charAt(i)); if (d == -1) { throw new IllegalArgumentException("Invalid hexadecimal character: " + hex.charAt(i)); } val = 16 * val + d; } return val; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/CoordinateConverter.java
src/main/java/com/thealgorithms/conversions/CoordinateConverter.java
package com.thealgorithms.conversions; /** * A utility class to convert between Cartesian and Polar coordinate systems. * * <p>This class provides methods to perform the following conversions: * <ul> * <li>Cartesian to Polar coordinates</li> * <li>Polar to Cartesian coordinates</li> * </ul> * * <p>The class is final and cannot be instantiated. */ public final class CoordinateConverter { private CoordinateConverter() { // Prevent instantiation } /** * Converts Cartesian coordinates to Polar coordinates. * * @param x the x-coordinate in the Cartesian system; must be a finite number * @param y the y-coordinate in the Cartesian system; must be a finite number * @return an array where the first element is the radius (r) and the second element is the angle (theta) in degrees * @throws IllegalArgumentException if x or y is not a finite number */ public static double[] cartesianToPolar(double x, double y) { if (!Double.isFinite(x) || !Double.isFinite(y)) { throw new IllegalArgumentException("x and y must be finite numbers."); } double r = Math.sqrt(x * x + y * y); double theta = Math.toDegrees(Math.atan2(y, x)); return new double[] {r, theta}; } /** * Converts Polar coordinates to Cartesian coordinates. * * @param r the radius in the Polar system; must be non-negative * @param thetaDegrees the angle (theta) in degrees in the Polar system; must be a finite number * @return an array where the first element is the x-coordinate and the second element is the y-coordinate in the Cartesian system * @throws IllegalArgumentException if r is negative or thetaDegrees is not a finite number */ public static double[] polarToCartesian(double r, double thetaDegrees) { if (r < 0) { throw new IllegalArgumentException("Radius (r) must be non-negative."); } if (!Double.isFinite(thetaDegrees)) { throw new IllegalArgumentException("Theta (angle) must be a finite number."); } double theta = Math.toRadians(thetaDegrees); double x = r * Math.cos(theta); double y = r * Math.sin(theta); return new double[] {x, y}; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/AffineConverter.java
src/main/java/com/thealgorithms/conversions/AffineConverter.java
package com.thealgorithms.conversions; /** * A utility class to perform affine transformations of the form: * y = slope * x + intercept. * * This class supports inversion and composition of affine transformations. * It is immutable, meaning each instance represents a fixed transformation. */ public final class AffineConverter { private final double slope; private final double intercept; /** * Constructs an AffineConverter with the given slope and intercept. * * @param inSlope The slope of the affine transformation. * @param inIntercept The intercept (constant term) of the affine transformation. * @throws IllegalArgumentException if either parameter is NaN. */ public AffineConverter(final double inSlope, final double inIntercept) { if (Double.isNaN(inSlope) || Double.isNaN(inIntercept)) { throw new IllegalArgumentException("Slope and intercept must be valid numbers."); } slope = inSlope; intercept = inIntercept; } /** * Converts the given input value using the affine transformation: * result = slope * inValue + intercept. * * @param inValue The input value to convert. * @return The transformed value. */ public double convert(final double inValue) { return slope * inValue + intercept; } /** * Returns a new AffineConverter representing the inverse of the current transformation. * The inverse of y = slope * x + intercept is x = (y - intercept) / slope. * * @return A new AffineConverter representing the inverse transformation. * @throws AssertionError if the slope is zero, as the inverse would be undefined. */ public AffineConverter invert() { assert slope != 0.0 : "Slope cannot be zero for inversion."; return new AffineConverter(1.0 / slope, -intercept / slope); } /** * Composes this affine transformation with another, returning a new AffineConverter. * If this transformation is f(x) and the other is g(x), the result is f(g(x)). * * @param other Another AffineConverter to compose with. * @return A new AffineConverter representing the composition of the two transformations. */ public AffineConverter compose(final AffineConverter other) { double newSlope = slope * other.slope; double newIntercept = slope * other.intercept + intercept; return new AffineConverter(newSlope, newIntercept); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java
src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java
package com.thealgorithms.conversions; /** * Utility class for converting hexadecimal numbers to binary representation. * <p> * A hexadecimal number consists of digits from {@code [0-9]} and {@code [A-F]} (case-insensitive), * while binary representation uses only {@code [0, 1]}. * <p> * This class provides methods to: * <ul> * <li>Convert a hexadecimal string to its binary string equivalent.</li> * <li>Ensure the binary output is padded to 8 bits (1 byte).</li> * </ul> * <p> * Example: * <ul> * <li>{@code "A1"} → {@code "10100001"}</li> * <li>{@code "1"} → {@code "00000001"}</li> * </ul> * * <p>This class assumes that the input hexadecimal string is valid.</p> */ public class HexaDecimalToBinary { /** * Converts a hexadecimal string to its binary string equivalent. * The binary output is padded to a minimum of 8 bits (1 byte). * Steps: * <ol> * <li>Convert the hexadecimal string to an integer.</li> * <li>Convert the integer to a binary string.</li> * <li>Pad the binary string to ensure it is at least 8 bits long.</li> * <li>Return the padded binary string.</li> * </ol> * * @param numHex the hexadecimal string (e.g., "A1", "7F") * @throws NumberFormatException if the input string is not a valid hexadecimal number * @return the binary string representation, padded to 8 bits (e.g., "10100001") */ public String convert(String numHex) { int conHex = Integer.parseInt(numHex, 16); String binary = Integer.toBinaryString(conHex); return completeDigits(binary); } /** * Pads the binary string to ensure it is at least 8 bits long. * If the binary string is shorter than 8 bits, it adds leading zeros. * * @param binNum the binary string to pad * @return the padded binary string with a minimum length of 8 */ public String completeDigits(String binNum) { final int byteSize = 8; StringBuilder binNumBuilder = new StringBuilder(binNum); while (binNumBuilder.length() < byteSize) { binNumBuilder.insert(0, "0"); } binNum = binNumBuilder.toString(); return binNum; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/IPv6Converter.java
src/main/java/com/thealgorithms/conversions/IPv6Converter.java
package com.thealgorithms.conversions; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; /** * A utility class for converting between IPv6 and IPv4 addresses. * * - Converts IPv4 to IPv6-mapped IPv6 address. * - Extracts IPv4 address from IPv6-mapped IPv6. * - Handles exceptions for invalid inputs. * * @author Hardvan */ public final class IPv6Converter { private IPv6Converter() { } /** * Converts an IPv4 address (e.g., "192.0.2.128") to an IPv6-mapped IPv6 address. * Example: IPv4 "192.0.2.128" -> IPv6 "::ffff:192.0.2.128" * * @param ipv4Address The IPv4 address in string format. * @return The corresponding IPv6-mapped IPv6 address. * @throws UnknownHostException If the IPv4 address is invalid. * @throws IllegalArgumentException If the IPv6 address is not a mapped IPv4 address. */ public static String ipv4ToIpv6(String ipv4Address) throws UnknownHostException { if (ipv4Address == null || ipv4Address.isEmpty()) { throw new UnknownHostException("IPv4 address is empty."); } InetAddress ipv4 = InetAddress.getByName(ipv4Address); byte[] ipv4Bytes = ipv4.getAddress(); // Create IPv6-mapped IPv6 address (starts with ::ffff:) byte[] ipv6Bytes = new byte[16]; ipv6Bytes[10] = (byte) 0xff; ipv6Bytes[11] = (byte) 0xff; System.arraycopy(ipv4Bytes, 0, ipv6Bytes, 12, 4); // Manually format to "::ffff:x.x.x.x" format StringBuilder ipv6String = new StringBuilder("::ffff:"); for (int i = 12; i < 16; i++) { ipv6String.append(ipv6Bytes[i] & 0xFF); if (i < 15) { ipv6String.append('.'); } } return ipv6String.toString(); } /** * Extracts the IPv4 address from an IPv6-mapped IPv6 address. * Example: IPv6 "::ffff:192.0.2.128" -> IPv4 "192.0.2.128" * * @param ipv6Address The IPv6 address in string format. * @return The extracted IPv4 address. * @throws UnknownHostException If the IPv6 address is invalid or not a mapped IPv4 address. */ public static String ipv6ToIpv4(String ipv6Address) throws UnknownHostException { InetAddress ipv6 = InetAddress.getByName(ipv6Address); byte[] ipv6Bytes = ipv6.getAddress(); // Check if the address is an IPv6-mapped IPv4 address if (isValidIpv6MappedIpv4(ipv6Bytes)) { byte[] ipv4Bytes = Arrays.copyOfRange(ipv6Bytes, 12, 16); InetAddress ipv4 = InetAddress.getByAddress(ipv4Bytes); return ipv4.getHostAddress(); } else { throw new IllegalArgumentException("Not a valid IPv6-mapped IPv4 address."); } } /** * Helper function to check if the given byte array represents * an IPv6-mapped IPv4 address (prefix 0:0:0:0:0:ffff). * * @param ipv6Bytes Byte array representation of the IPv6 address. * @return True if the address is IPv6-mapped IPv4, otherwise false. */ private static boolean isValidIpv6MappedIpv4(byte[] ipv6Bytes) { // IPv6-mapped IPv4 addresses are 16 bytes long, with the first 10 bytes set to 0, // followed by 0xff, 0xff, and the last 4 bytes representing the IPv4 address. if (ipv6Bytes.length != 16) { return false; } for (int i = 0; i < 10; i++) { if (ipv6Bytes[i] != 0) { return false; } } return ipv6Bytes[10] == (byte) 0xff && ipv6Bytes[11] == (byte) 0xff; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
package com.thealgorithms.conversions; /** * This class provides methods to convert a decimal number to a binary number. */ final class DecimalToBinary { private static final int BINARY_BASE = 2; private static final int DECIMAL_MULTIPLIER = 10; private DecimalToBinary() { } /** * Converts a decimal number to a binary number using a conventional algorithm. * @param decimalNumber the decimal number to convert * @return the binary representation of the decimal number */ public static int convertUsingConventionalAlgorithm(int decimalNumber) { int binaryNumber = 0; int position = 1; while (decimalNumber > 0) { int remainder = decimalNumber % BINARY_BASE; binaryNumber += remainder * position; position *= DECIMAL_MULTIPLIER; decimalNumber /= BINARY_BASE; } return binaryNumber; } /** * Converts a decimal number to a binary number using a bitwise algorithm. * @param decimalNumber the decimal number to convert * @return the binary representation of the decimal number */ public static int convertUsingBitwiseAlgorithm(int decimalNumber) { int binaryNumber = 0; int position = 1; while (decimalNumber > 0) { int leastSignificantBit = decimalNumber & 1; binaryNumber += leastSignificantBit * position; position *= DECIMAL_MULTIPLIER; decimalNumber >>= 1; } return binaryNumber; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java
src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java
package com.thealgorithms.conversions; /** * This class converts a Binary number to a Decimal number */ final class BinaryToDecimal { private static final int BINARY_BASE = 2; private BinaryToDecimal() { } /** * Converts a binary number to its decimal equivalent. * * @param binaryNumber The binary number to convert. * @return The decimal equivalent of the binary number. * @throws IllegalArgumentException If the binary number contains digits other than 0 and 1. */ public static long binaryToDecimal(long binaryNumber) { long decimalValue = 0; long power = 0; while (binaryNumber != 0) { long digit = binaryNumber % 10; if (digit > 1) { throw new IllegalArgumentException("Incorrect binary digit: " + digit); } decimalValue += (long) (digit * Math.pow(BINARY_BASE, power++)); binaryNumber /= 10; } return decimalValue; } /** * Converts a binary String to its decimal equivalent using bitwise operators. * * @param binary The binary number to convert. * @return The decimal equivalent of the binary number. * @throws IllegalArgumentException If the binary number contains digits other than 0 and 1. */ public static long binaryStringToDecimal(String binary) { boolean isNegative = binary.charAt(0) == '-'; if (isNegative) { binary = binary.substring(1); } long decimalValue = 0; for (char bit : binary.toCharArray()) { if (bit != '0' && bit != '1') { throw new IllegalArgumentException("Incorrect binary digit: " + bit); } // shift left by 1 (multiply by 2) and add bit value decimalValue = (decimalValue << 1) | (bit - '0'); } return isNegative ? -decimalValue : decimalValue; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/OctalToBinary.java
src/main/java/com/thealgorithms/conversions/OctalToBinary.java
package com.thealgorithms.conversions; /** * A utility class to convert an octal (base-8) number into its binary (base-2) representation. * * <p>This class provides methods to: * <ul> * <li>Convert an octal number to its binary equivalent</li> * <li>Convert individual octal digits to binary</li> * </ul> * * <h2>Octal to Binary Conversion:</h2> * <p>An octal number is converted to binary by converting each octal digit to its 3-bit binary equivalent. * The result is a long representing the full binary equivalent of the octal number.</p> * * <h2>Example Usage</h2> * <pre> * long binary = OctalToBinary.convertOctalToBinary(52); // Output: 101010 (52 in octal is 101010 in binary) * </pre> * * @author Bama Charan Chhandogi * @see <a href="https://en.wikipedia.org/wiki/Octal">Octal Number System</a> * @see <a href="https://en.wikipedia.org/wiki/Binary_number">Binary Number System</a> */ public final class OctalToBinary { private OctalToBinary() { } /** * Converts an octal number to its binary representation. * * <p>Each octal digit is individually converted to its 3-bit binary equivalent, and the binary * digits are concatenated to form the final binary number.</p> * * @param octalNumber the octal number to convert (non-negative integer) * @return the binary equivalent as a long */ public static long convertOctalToBinary(int octalNumber) { long binaryNumber = 0; int digitPosition = 1; while (octalNumber != 0) { int octalDigit = octalNumber % 10; long binaryDigit = convertOctalDigitToBinary(octalDigit); binaryNumber += binaryDigit * digitPosition; octalNumber /= 10; digitPosition *= 1000; } return binaryNumber; } /** * Converts a single octal digit (0-7) to its binary equivalent. * * <p>For example: * <ul> * <li>Octal digit 7 is converted to binary 111</li> * <li>Octal digit 3 is converted to binary 011</li> * </ul> * </p> * * @param octalDigit a single octal digit (0-7) * @return the binary equivalent as a long */ public static long convertOctalDigitToBinary(int octalDigit) { long binaryDigit = 0; int binaryMultiplier = 1; while (octalDigit != 0) { int octalDigitRemainder = octalDigit % 2; binaryDigit += octalDigitRemainder * binaryMultiplier; octalDigit /= 2; binaryMultiplier *= 10; } return binaryDigit; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/UnitsConverter.java
src/main/java/com/thealgorithms/conversions/UnitsConverter.java
package com.thealgorithms.conversions; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.lang3.tuple.Pair; /** * A class that handles unit conversions using affine transformations. * * <p>The {@code UnitsConverter} allows converting values between different units using * pre-defined affine conversion formulas. Each conversion is represented by an * {@link AffineConverter} that defines the scaling and offset for the conversion. * * <p>For each unit, both direct conversions (e.g., Celsius to Fahrenheit) and inverse * conversions (e.g., Fahrenheit to Celsius) are generated automatically. It also computes * transitive conversions (e.g., Celsius to Kelvin via Fahrenheit if both conversions exist). * * <p>Key features include: * <ul> * <li>Automatic handling of inverse conversions (e.g., Fahrenheit to Celsius).</li> * <li>Compositional conversions, meaning if conversions between A -> B and B -> C exist, * it can automatically generate A -> C conversion.</li> * <li>Supports multiple unit systems as long as conversions are provided in pairs.</li> * </ul> * * <h2>Example Usage</h2> * <pre> * Map&lt;Pair&lt;String, String&gt;, AffineConverter&gt; basicConversions = Map.ofEntries( * entry(Pair.of("Celsius", "Fahrenheit"), new AffineConverter(9.0 / 5.0, 32.0)), * entry(Pair.of("Kelvin", "Celsius"), new AffineConverter(1.0, -273.15)) * ); * * UnitsConverter converter = new UnitsConverter(basicConversions); * double result = converter.convert("Celsius", "Fahrenheit", 100.0); * // Output: 212.0 (Celsius to Fahrenheit conversion of 100°C) * </pre> * * <h2>Exception Handling</h2> * <ul> * <li>If the input unit and output unit are the same, an {@link IllegalArgumentException} is thrown.</li> * <li>If a conversion between the requested units does not exist, a {@link NoSuchElementException} is thrown.</li> * </ul> */ public final class UnitsConverter { private final Map<Pair<String, String>, AffineConverter> conversions; private final Set<String> units; private static void putIfNeeded(Map<Pair<String, String>, AffineConverter> conversions, final String inputUnit, final String outputUnit, final AffineConverter converter) { if (!inputUnit.equals(outputUnit)) { final var key = Pair.of(inputUnit, outputUnit); conversions.putIfAbsent(key, converter); } } private static Map<Pair<String, String>, AffineConverter> addInversions(final Map<Pair<String, String>, AffineConverter> knownConversions) { Map<Pair<String, String>, AffineConverter> res = new HashMap<Pair<String, String>, AffineConverter>(); for (final var curConversion : knownConversions.entrySet()) { final var inputUnit = curConversion.getKey().getKey(); final var outputUnit = curConversion.getKey().getValue(); putIfNeeded(res, inputUnit, outputUnit, curConversion.getValue()); putIfNeeded(res, outputUnit, inputUnit, curConversion.getValue().invert()); } return res; } private static Map<Pair<String, String>, AffineConverter> addCompositions(final Map<Pair<String, String>, AffineConverter> knownConversions) { Map<Pair<String, String>, AffineConverter> res = new HashMap<Pair<String, String>, AffineConverter>(); for (final var first : knownConversions.entrySet()) { final var firstKey = first.getKey(); putIfNeeded(res, firstKey.getKey(), firstKey.getValue(), first.getValue()); for (final var second : knownConversions.entrySet()) { final var secondKey = second.getKey(); if (firstKey.getValue().equals(secondKey.getKey())) { final var newConversion = second.getValue().compose(first.getValue()); putIfNeeded(res, firstKey.getKey(), secondKey.getValue(), newConversion); } } } return res; } private static Map<Pair<String, String>, AffineConverter> addAll(final Map<Pair<String, String>, AffineConverter> knownConversions) { final var res = addInversions(knownConversions); return addCompositions(res); } private static Map<Pair<String, String>, AffineConverter> computeAllConversions(final Map<Pair<String, String>, AffineConverter> basicConversions) { var tmp = basicConversions; var res = addAll(tmp); while (res.size() != tmp.size()) { tmp = res; res = addAll(tmp); } return res; } private static Set<String> extractUnits(final Map<Pair<String, String>, AffineConverter> conversions) { Set<String> res = new HashSet<>(); for (final var conversion : conversions.entrySet()) { res.add(conversion.getKey().getKey()); } return res; } /** * Constructor for {@code UnitsConverter}. * * <p>Accepts a map of basic conversions and automatically generates inverse and * transitive conversions. * * @param basicConversions the initial set of unit conversions to add. */ public UnitsConverter(final Map<Pair<String, String>, AffineConverter> basicConversions) { conversions = computeAllConversions(basicConversions); units = extractUnits(conversions); } /** * Converts a value from one unit to another. * * @param inputUnit the unit of the input value. * @param outputUnit the unit to convert the value into. * @param value the value to convert. * @return the converted value in the target unit. * @throws IllegalArgumentException if inputUnit equals outputUnit. * @throws NoSuchElementException if no conversion exists between the units. */ public double convert(final String inputUnit, final String outputUnit, final double value) { if (inputUnit.equals(outputUnit)) { throw new IllegalArgumentException("inputUnit must be different from outputUnit."); } final var conversionKey = Pair.of(inputUnit, outputUnit); return conversions.computeIfAbsent(conversionKey, k -> { throw new NoSuchElementException("No converter for: " + k); }).convert(value); } /** * Retrieves the set of all units supported by this converter. * * @return a set of available units. */ public Set<String> availableUnits() { return units; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java
src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java
package com.thealgorithms.conversions; import java.util.ArrayList; import java.util.List; /** * Class that provides methods to convert a decimal number to a string representation * in any specified base between 2 and 36. * * @author Varun Upadhyay (<a href="https://github.com/varunu28">...</a>) */ public final class DecimalToAnyBase { private static final int MIN_BASE = 2; private static final int MAX_BASE = 36; private static final char ZERO_CHAR = '0'; private static final char A_CHAR = 'A'; private static final int DIGIT_OFFSET = 10; private DecimalToAnyBase() { } /** * Converts a decimal number to a string representation in the specified base. * For example, converting the decimal number 10 to base 2 would return "1010". * * @param decimal the decimal number to convert * @param base the base to convert to (must be between {@value #MIN_BASE} and {@value #MAX_BASE}) * @return the string representation of the number in the specified base * @throws IllegalArgumentException if the base is out of the supported range */ public static String convertToAnyBase(int decimal, int base) { if (base < MIN_BASE || base > MAX_BASE) { throw new IllegalArgumentException("Base must be between " + MIN_BASE + " and " + MAX_BASE); } if (decimal == 0) { return String.valueOf(ZERO_CHAR); } List<Character> digits = new ArrayList<>(); while (decimal > 0) { digits.add(convertToChar(decimal % base)); decimal /= base; } StringBuilder result = new StringBuilder(digits.size()); for (int i = digits.size() - 1; i >= 0; i--) { result.append(digits.get(i)); } return result.toString(); } /** * Converts an integer value to its corresponding character in the specified base. * This method is used to convert values from 0 to 35 into their appropriate character representation. * For example, 0-9 are represented as '0'-'9', and 10-35 are represented as 'A'-'Z'. * * @param value the integer value to convert (should be less than the base value) * @return the character representing the value in the specified base */ private static char convertToChar(int value) { if (value >= 0 && value <= 9) { return (char) (ZERO_CHAR + value); } else { return (char) (A_CHAR + value - DIGIT_OFFSET); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/DecimalToHexadecimal.java
src/main/java/com/thealgorithms/conversions/DecimalToHexadecimal.java
package com.thealgorithms.conversions; /** * This class provides a method to convert a decimal number to a hexadecimal string. */ final class DecimalToHexadecimal { private static final int SIZE_OF_INT_IN_HALF_BYTES = 8; private static final int NUMBER_OF_BITS_IN_HALF_BYTE = 4; private static final int HALF_BYTE_MASK = 0x0F; private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private DecimalToHexadecimal() { } /** * Converts a decimal number to a hexadecimal string. * @param decimal the decimal number to convert * @return the hexadecimal representation of the decimal number */ public static String decToHex(int decimal) { StringBuilder hexBuilder = new StringBuilder(SIZE_OF_INT_IN_HALF_BYTES); for (int i = SIZE_OF_INT_IN_HALF_BYTES - 1; i >= 0; --i) { int currentHalfByte = decimal & HALF_BYTE_MASK; hexBuilder.insert(0, HEX_DIGITS[currentHalfByte]); decimal >>= NUMBER_OF_BITS_IN_HALF_BYTE; } return removeLeadingZeros(hexBuilder.toString().toLowerCase()); } private static String removeLeadingZeros(String str) { if (str == null || str.isEmpty()) { return str; } int i = 0; while (i < str.length() && str.charAt(i) == '0') { i++; } return i == str.length() ? "0" : str.substring(i); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/IPConverter.java
src/main/java/com/thealgorithms/conversions/IPConverter.java
package com.thealgorithms.conversions; /** * Converts an IPv4 address to its binary equivalent and vice-versa. * IP to Binary: Converts an IPv4 address to its binary equivalent. * Example: 127.3.4.5 -> 01111111.00000011.00000100.00000101 * * Binary to IP: Converts a binary equivalent to an IPv4 address. * Example: 01111111.00000011.00000100.00000101 -> 127.3.4.5 * * @author Hardvan */ public final class IPConverter { private IPConverter() { } /** * Converts an IPv4 address to its binary equivalent. * @param ip The IPv4 address to convert. * @return The binary equivalent of the IPv4 address. */ public static String ipToBinary(String ip) { StringBuilder binary = new StringBuilder(); for (String octet : ip.split("\\.")) { binary.append(octetToBinary(Integer.parseInt(octet))).append("."); } return binary.substring(0, binary.length() - 1); } /** * Converts a single octet to its 8-bit binary representation. * @param octet The octet to convert (0-255). * @return The 8-bit binary representation as a String. */ private static String octetToBinary(int octet) { char[] binary = {'0', '0', '0', '0', '0', '0', '0', '0'}; for (int i = 7; i >= 0; i--) { if ((octet & 1) == 1) { binary[i] = '1'; } octet >>>= 1; } return new String(binary); } /** * Converts a binary equivalent to an IPv4 address. * @param binary The binary equivalent to convert. * @return The IPv4 address of the binary equivalent. */ public static String binaryToIP(String binary) { StringBuilder ip = new StringBuilder(); for (String octet : binary.split("\\.")) { ip.append(Integer.parseInt(octet, 2)).append("."); } return ip.substring(0, ip.length() - 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/HexToOct.java
src/main/java/com/thealgorithms/conversions/HexToOct.java
package com.thealgorithms.conversions; /** * Converts any Hexadecimal Number to Octal * * @author Tanmay Joshi */ public final class HexToOct { private HexToOct() { } /** * Converts a Hexadecimal number to a Decimal number. * * @param hex The Hexadecimal number as a String. * @return The Decimal equivalent as an integer. */ public static int hexToDecimal(String hex) { String hexDigits = "0123456789ABCDEF"; hex = hex.toUpperCase(); int decimalValue = 0; for (int i = 0; i < hex.length(); i++) { char hexChar = hex.charAt(i); int digitValue = hexDigits.indexOf(hexChar); decimalValue = 16 * decimalValue + digitValue; } return decimalValue; } /** * Converts a Decimal number to an Octal number. * * @param decimal The Decimal number as an integer. * @return The Octal equivalent as an integer. */ public static int decimalToOctal(int decimal) { int octalValue = 0; int placeValue = 1; while (decimal > 0) { int remainder = decimal % 8; octalValue += remainder * placeValue; decimal /= 8; placeValue *= 10; } return octalValue; } /** * Converts a Hexadecimal number to an Octal number. * * @param hex The Hexadecimal number as a String. * @return The Octal equivalent as an integer. */ public static int hexToOctal(String hex) { int decimalValue = hexToDecimal(hex); return decimalToOctal(decimalValue); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/RomanToInteger.java
src/main/java/com/thealgorithms/conversions/RomanToInteger.java
package com.thealgorithms.conversions; import java.util.HashMap; import java.util.Map; /** * A utility class to convert Roman numerals into integers. * * <p>Roman numerals are based on seven symbols given below: * <ul> * <li>I = 1</li> * <li>V = 5</li> * <li>X = 10</li> * <li>L = 50</li> * <li>C = 100</li> * <li>D = 500</li> * <li>M = 1000</li> * </ul> * * <p>If a smaller numeral appears before a larger numeral, it is subtracted. * Otherwise, it is added. For example: * <pre> * MCMXCIV = 1000 + (1000 - 100) + (100 - 10) + (5 - 1) = 1994 * </pre> */ public final class RomanToInteger { private static final Map<Character, Integer> ROMAN_TO_INT = new HashMap<>() { { put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000); } }; private RomanToInteger() { } /** * Converts a single Roman numeral character to its integer value. * * @param symbol the Roman numeral character * @return the corresponding integer value * @throws IllegalArgumentException if the symbol is not a valid Roman numeral */ private static int romanSymbolToInt(final char symbol) { return ROMAN_TO_INT.computeIfAbsent(symbol, c -> { throw new IllegalArgumentException("Unknown Roman symbol: " + c); }); } /** * Converts a Roman numeral string to its integer equivalent. * Steps: * <ol> * <li>Iterate over the string from right to left.</li> * <li>For each character, convert it to an integer value.</li> * <li>If the current value is greater than or equal to the max previous value, add it.</li> * <li>Otherwise, subtract it from the sum.</li> * <li>Update the max previous value.</li> * <li>Return the sum.</li> * </ol> * * @param roman the Roman numeral string * @return the integer value of the Roman numeral * @throws IllegalArgumentException if the input contains invalid Roman characters * @throws NullPointerException if the input is {@code null} */ public static int romanToInt(String roman) { if (roman == null) { throw new NullPointerException("Input cannot be null"); } roman = roman.toUpperCase(); int sum = 0; int maxPrevValue = 0; for (int i = roman.length() - 1; i >= 0; i--) { int currentValue = romanSymbolToInt(roman.charAt(i)); if (currentValue >= maxPrevValue) { sum += currentValue; maxPrevValue = currentValue; } else { sum -= currentValue; } } return sum; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
package com.thealgorithms.conversions; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Scanner; /** * Class for converting from "any" base to "any" other base, when "any" means * from 2-36. Works by going from base 1 to decimal to base 2. Includes * auxiliary method for determining whether a number is valid for a given base. * * @author Michael Rolland * @version 2017.10.10 */ public final class AnyBaseToAnyBase { private AnyBaseToAnyBase() { } /** * Smallest and largest base you want to accept as valid input */ static final int MINIMUM_BASE = 2; static final int MAXIMUM_BASE = 36; public static void main(String[] args) { Scanner in = new Scanner(System.in); String n; int b1; int b2; while (true) { try { System.out.print("Enter number: "); n = in.next(); System.out.print("Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); b1 = in.nextInt(); if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) { System.out.println("Invalid base!"); continue; } if (!validForBase(n, b1)) { System.out.println("The number is invalid for this base!"); continue; } System.out.print("Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): "); b2 = in.nextInt(); if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) { System.out.println("Invalid base!"); continue; } break; } catch (InputMismatchException e) { System.out.println("Invalid input."); in.next(); } } System.out.println(base2base(n, b1, b2)); in.close(); } /** * Checks if a number (as a String) is valid for a given base. */ 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', }; // digitsForBase contains all the valid digits for the base given char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base); // Convert character array into set for convenience of contains() method HashSet<Character> digitsList = new HashSet<>(); for (int i = 0; i < digitsForBase.length; i++) { digitsList.add(digitsForBase[i]); } // Check that every digit in n is within the list of valid digits for that base. for (char c : n.toCharArray()) { if (!digitsList.contains(c)) { return false; } } return true; } /** * Method to convert any integer from base b1 to base b2. Works by * converting from b1 to decimal, then decimal to b2. * * @param n The integer to be converted. * @param b1 Beginning base. * @param b2 End base. * @return n in base b2. */ public static String base2base(String n, int b1, int b2) { // Declare variables: decimal value of n, // character of base b1, character of base b2, // and the string that will be returned. int decimalValue = 0; int charB2; char charB1; StringBuilder output = new StringBuilder(); // Go through every character of n for (int i = 0; i < n.length(); i++) { // store the character in charB1 charB1 = n.charAt(i); // if it is a non-number, convert it to a decimal value >9 and store it in charB2 if (charB1 >= 'A' && charB1 <= 'Z') { charB2 = 10 + (charB1 - 'A'); } // Else, store the integer value in charB2 else { charB2 = charB1 - '0'; } // Convert the digit to decimal and add it to the // decimalValue of n decimalValue = decimalValue * b1 + charB2; } // Converting the decimal value to base b2: // A number is converted from decimal to another base // by continuously dividing by the base and recording // the remainder until the quotient is zero. The number in the // new base is the remainders, with the last remainder // being the left-most digit. if (0 == decimalValue) { return "0"; } // While the quotient is NOT zero: while (decimalValue != 0) { // If the remainder is a digit < 10, simply add it to // the left side of the new number. if (decimalValue % b2 < 10) { output.insert(0, decimalValue % b2); } // If the remainder is >= 10, add a character with the // corresponding value to the new number. (A = 10, B = 11, C = 12, ...) else { output.insert(0, (char) ((decimalValue % b2) + 55)); } // Divide by the new base again decimalValue /= b2; } return output.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java
src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java
package com.thealgorithms.conversions; import java.util.Arrays; /** * The RGB color model is an additive color model in which red, green, and blue * light are added together in various ways to reproduce a broad array of * colors. The name of the model comes from the initials of the three additive * primary colors, red, green, and blue. Meanwhile, the HSV representation * models how colors appear under light. In it, colors are represented using * three components: hue, saturation and (brightness-)value. This class provides * methods for converting colors from one representation to the other. * (description adapted from <a href="https://en.wikipedia.org/wiki/RGB_color_model">[1]</a> and * <a href="https://en.wikipedia.org/wiki/HSL_and_HSV">[2]</a>). */ public final class RgbHsvConversion { private RgbHsvConversion() { } public static void main(String[] args) { // Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html // Test hsvToRgb-method assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] {0, 0, 0}); assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] {255, 255, 255}); assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] {255, 0, 0}); assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] {255, 255, 0}); assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] {0, 255, 0}); assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] {0, 0, 255}); assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] {255, 0, 255}); assert Arrays.equals(hsvToRgb(180, 0.5, 0.5), new int[] {64, 128, 128}); assert Arrays.equals(hsvToRgb(234, 0.14, 0.88), new int[] {193, 196, 224}); assert Arrays.equals(hsvToRgb(330, 0.75, 0.5), new int[] {128, 32, 80}); // 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}); } /** * Conversion from the HSV-representation to the RGB-representation. * * @param hue Hue of the color. * @param saturation Saturation of the color. * @param value Brightness-value of the color. * @return The tuple of RGB-components. */ 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"); } if (saturation < 0 || saturation > 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"); } double chroma = value * saturation; double hueSection = hue / 60; double secondLargestComponent = chroma * (1 - Math.abs(hueSection % 2 - 1)); double matchValue = value - chroma; return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent); } /** * Conversion from the RGB-representation to the HSV-representation. * * @param red Red-component of the color. * @param green Green-component of the color. * @param blue Blue-component of the color. * @return The tuple of HSV-components. */ 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"); } if (green < 0 || green > 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"); } double dRed = (double) red / 255; double dGreen = (double) green / 255; double dBlue = (double) blue / 255; double value = Math.max(Math.max(dRed, dGreen), dBlue); double chroma = value - Math.min(Math.min(dRed, dGreen), dBlue); double saturation = value == 0 ? 0 : chroma / value; double hue; if (chroma == 0) { hue = 0; } else if (value == dRed) { hue = 60 * (0 + (dGreen - dBlue) / chroma); } else if (value == dGreen) { hue = 60 * (2 + (dBlue - dRed) / chroma); } else { hue = 60 * (4 + (dRed - dGreen) / chroma); } hue = (hue + 360) % 360; return new double[] {hue, saturation, value}; } private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) { boolean bHue = Math.abs(hsv1[0] - hsv2[0]) < 0.2; boolean bSaturation = Math.abs(hsv1[1] - hsv2[1]) < 0.002; boolean bValue = Math.abs(hsv1[2] - hsv2[2]) < 0.002; return bHue && bSaturation && bValue; } private static int[] getRgbBySection(double hueSection, double chroma, double matchValue, double secondLargestComponent) { int red; int green; int blue; if (hueSection >= 0 && hueSection <= 1) { red = convertToInt(chroma + matchValue); green = convertToInt(secondLargestComponent + matchValue); blue = convertToInt(matchValue); } else if (hueSection > 1 && hueSection <= 2) { red = convertToInt(secondLargestComponent + matchValue); green = convertToInt(chroma + matchValue); blue = convertToInt(matchValue); } else if (hueSection > 2 && hueSection <= 3) { red = convertToInt(matchValue); green = convertToInt(chroma + matchValue); blue = convertToInt(secondLargestComponent + matchValue); } else if (hueSection > 3 && hueSection <= 4) { red = convertToInt(matchValue); green = convertToInt(secondLargestComponent + matchValue); blue = convertToInt(chroma + matchValue); } else if (hueSection > 4 && hueSection <= 5) { red = convertToInt(secondLargestComponent + matchValue); green = convertToInt(matchValue); blue = convertToInt(chroma + matchValue); } else { red = convertToInt(chroma + matchValue); green = convertToInt(matchValue); blue = convertToInt(secondLargestComponent + matchValue); } return new int[] {red, green, blue}; } private static int convertToInt(double input) { return (int) Math.round(255 * input); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java
src/main/java/com/thealgorithms/conversions/OctalToDecimal.java
package com.thealgorithms.conversions; /** * Class for converting an octal number to a decimal number. Octal numbers are based on 8, using digits from 0 to 7. * */ public final class OctalToDecimal { private static final int OCTAL_BASE = 8; private OctalToDecimal() { } /** * Converts a given octal number (as a string) to its decimal representation. * If the input is not a valid octal number (i.e., contains characters other than 0-7), * the method throws an IllegalArgumentException. * * @param inputOctal The octal number as a string * @return The decimal equivalent of the octal number * @throws IllegalArgumentException if the input is not a valid octal number */ public static int convertOctalToDecimal(String inputOctal) { if (inputOctal == null || inputOctal.isEmpty()) { throw new IllegalArgumentException("Input cannot be null or empty"); } int decimalValue = 0; for (int i = 0; i < inputOctal.length(); i++) { char currentChar = inputOctal.charAt(i); if (currentChar < '0' || currentChar > '7') { throw new IllegalArgumentException("Incorrect input: Expecting an octal number (digits 0-7)"); } int currentDigit = currentChar - '0'; decimalValue = decimalValue * OCTAL_BASE + currentDigit; } return decimalValue; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
package com.thealgorithms.conversions; /** * Converts turkish character to latin character * * @author Özgün Gökşenli */ public final class TurkishToLatinConversion { private TurkishToLatinConversion() { } /** * This method converts a turkish character to latin character. * Steps: * 1. Define turkish characters and their corresponding latin characters * 2. Replace all turkish characters with their corresponding latin characters * 3. Return the converted string * * @param param String parameter * @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', }; for (int i = 0; i < turkishChars.length; i++) { param = param.replaceAll(String.valueOf(turkishChars[i]), String.valueOf(latinChars[i])); } return param; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/AnytoAny.java
src/main/java/com/thealgorithms/conversions/AnytoAny.java
package com.thealgorithms.conversions; /** * A utility class for converting numbers from any base to any other base. * * This class provides a method to convert a source number from a given base * to a destination number in another base. Valid bases range from 2 to 10. */ public final class AnytoAny { private AnytoAny() { } /** * Converts a number from a source base to a destination base. * * @param sourceNumber The number in the source base (as an integer). * @param sourceBase The base of the source number (between 2 and 10). * @param destBase The base to which the number should be converted (between 2 and 10). * @throws IllegalArgumentException if the bases are not between 2 and 10. * @return The converted number in the destination base (as an integer). */ public static int convertBase(int sourceNumber, int sourceBase, int destBase) { if (sourceBase < 2 || sourceBase > 10 || destBase < 2 || destBase > 10) { throw new IllegalArgumentException("Bases must be between 2 and 10."); } int decimalValue = toDecimal(sourceNumber, sourceBase); return fromDecimal(decimalValue, destBase); } /** * Converts a number from a given base to its decimal representation (base 10). * * @param number The number in the original base. * @param base The base of the given number. * @return The decimal representation of the number. */ private static int toDecimal(int number, int base) { int decimalValue = 0; int multiplier = 1; while (number != 0) { decimalValue += (number % 10) * multiplier; multiplier *= base; number /= 10; } return decimalValue; } /** * Converts a decimal (base 10) number to a specified base. * * @param decimal The decimal number to convert. * @param base The destination base for conversion. * @return The number in the specified base. */ private static int fromDecimal(int decimal, int base) { int result = 0; int multiplier = 1; while (decimal != 0) { result += (decimal % base) * multiplier; multiplier *= 10; decimal /= base; } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/AnyBaseToDecimal.java
src/main/java/com/thealgorithms/conversions/AnyBaseToDecimal.java
package com.thealgorithms.conversions; /** * @author Varun Upadhyay (<a href="https://github.com/varunu28">...</a>) */ public final class AnyBaseToDecimal { private static final int CHAR_OFFSET_FOR_DIGIT = '0'; private static final int CHAR_OFFSET_FOR_UPPERCASE = 'A' - 10; private AnyBaseToDecimal() { } /** * Convert any radix to a decimal number. * * @param input the string to be converted * @param radix the radix (base) of the input string * @return the decimal equivalent of the input string * @throws NumberFormatException if the input string or radix is invalid */ public static int convertToDecimal(String input, int radix) { int result = 0; int power = 1; for (int i = input.length() - 1; i >= 0; i--) { int digit = valOfChar(input.charAt(i)); if (digit >= radix) { throw new NumberFormatException("For input string: " + input); } result += digit * power; power *= radix; } return result; } /** * Convert a character to its integer value. * * @param character the character to be converted * @return the integer value represented by the character * @throws NumberFormatException if the character is not an uppercase letter or a digit */ private static int valOfChar(char character) { if (Character.isDigit(character)) { return character - CHAR_OFFSET_FOR_DIGIT; } else if (Character.isUpperCase(character)) { return character - CHAR_OFFSET_FOR_UPPERCASE; } else { throw new NumberFormatException("invalid character:" + character); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/WordsToNumber.java
src/main/java/com/thealgorithms/conversions/WordsToNumber.java
package com.thealgorithms.conversions; import java.io.Serial; import java.math.BigDecimal; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** A Java-based utility for converting English word representations of numbers into their numeric form. This utility supports whole numbers, decimals, large values up to trillions, and even scientific notation where applicable. It ensures accurate parsing while handling edge cases like negative numbers, improper word placements, and ambiguous inputs. * */ public final class WordsToNumber { private WordsToNumber() { } private enum NumberWord { ZERO("zero", 0), ONE("one", 1), TWO("two", 2), THREE("three", 3), FOUR("four", 4), FIVE("five", 5), SIX("six", 6), SEVEN("seven", 7), EIGHT("eight", 8), NINE("nine", 9), TEN("ten", 10), ELEVEN("eleven", 11), TWELVE("twelve", 12), THIRTEEN("thirteen", 13), FOURTEEN("fourteen", 14), FIFTEEN("fifteen", 15), SIXTEEN("sixteen", 16), SEVENTEEN("seventeen", 17), EIGHTEEN("eighteen", 18), NINETEEN("nineteen", 19), TWENTY("twenty", 20), THIRTY("thirty", 30), FORTY("forty", 40), FIFTY("fifty", 50), SIXTY("sixty", 60), SEVENTY("seventy", 70), EIGHTY("eighty", 80), NINETY("ninety", 90); private final String word; private final int value; NumberWord(String word, int value) { this.word = word; this.value = value; } public static Integer getValue(String word) { for (NumberWord num : values()) { if (word.equals(num.word)) { return num.value; } } return null; } } private enum PowerOfTen { THOUSAND("thousand", new BigDecimal("1000")), MILLION("million", new BigDecimal("1000000")), BILLION("billion", new BigDecimal("1000000000")), TRILLION("trillion", new BigDecimal("1000000000000")); private final String word; private final BigDecimal value; PowerOfTen(String word, BigDecimal value) { this.word = word; this.value = value; } public static BigDecimal getValue(String word) { for (PowerOfTen power : values()) { if (word.equals(power.word)) { return power.value; } } return null; } } public static String convert(String numberInWords) { if (numberInWords == null) { throw new WordsToNumberException(WordsToNumberException.ErrorType.NULL_INPUT, ""); } ArrayDeque<String> wordDeque = preprocessWords(numberInWords); BigDecimal completeNumber = convertWordQueueToBigDecimal(wordDeque); return completeNumber.toString(); } public static BigDecimal convertToBigDecimal(String numberInWords) { String conversionResult = convert(numberInWords); return new BigDecimal(conversionResult); } private static ArrayDeque<String> preprocessWords(String numberInWords) { String[] wordSplitArray = numberInWords.trim().split("[ ,-]"); ArrayDeque<String> wordDeque = new ArrayDeque<>(); for (String word : wordSplitArray) { if (word.isEmpty()) { continue; } wordDeque.add(word.toLowerCase()); } if (wordDeque.isEmpty()) { throw new WordsToNumberException(WordsToNumberException.ErrorType.NULL_INPUT, ""); } return wordDeque; } private static void handleConjunction(boolean prevNumWasHundred, boolean prevNumWasPowerOfTen, ArrayDeque<String> wordDeque) { if (wordDeque.isEmpty()) { throw new WordsToNumberException(WordsToNumberException.ErrorType.INVALID_CONJUNCTION, ""); } String nextWord = wordDeque.pollFirst(); String afterNextWord = wordDeque.peekFirst(); wordDeque.addFirst(nextWord); Integer number = NumberWord.getValue(nextWord); boolean isPrevWordValid = prevNumWasHundred || prevNumWasPowerOfTen; boolean isNextWordValid = number != null && (number >= 10 || afterNextWord == null || "point".equals(afterNextWord)); if (!isPrevWordValid || !isNextWordValid) { throw new WordsToNumberException(WordsToNumberException.ErrorType.INVALID_CONJUNCTION, ""); } } private static BigDecimal handleHundred(BigDecimal currentChunk, String word, boolean prevNumWasPowerOfTen) { boolean currentChunkIsZero = currentChunk.compareTo(BigDecimal.ZERO) == 0; if (currentChunk.compareTo(BigDecimal.TEN) >= 0 || prevNumWasPowerOfTen) { throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD, word); } if (currentChunkIsZero) { currentChunk = currentChunk.add(BigDecimal.ONE); } return currentChunk.multiply(BigDecimal.valueOf(100)); } private static void handlePowerOfTen(List<BigDecimal> chunks, BigDecimal currentChunk, BigDecimal powerOfTen, String word, boolean prevNumWasPowerOfTen) { boolean currentChunkIsZero = currentChunk.compareTo(BigDecimal.ZERO) == 0; if (currentChunkIsZero || prevNumWasPowerOfTen) { throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD, word); } BigDecimal nextChunk = currentChunk.multiply(powerOfTen); if (!(chunks.isEmpty() || isAdditionSafe(chunks.getLast(), nextChunk))) { throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD, word); } chunks.add(nextChunk); } private static BigDecimal handleNumber(Collection<BigDecimal> chunks, BigDecimal currentChunk, String word, Integer number) { boolean currentChunkIsZero = currentChunk.compareTo(BigDecimal.ZERO) == 0; if (number == 0 && !(currentChunkIsZero && chunks.isEmpty())) { throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD, word); } BigDecimal bigDecimalNumber = BigDecimal.valueOf(number); if (!currentChunkIsZero && !isAdditionSafe(currentChunk, bigDecimalNumber)) { throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD, word); } return currentChunk.add(bigDecimalNumber); } private static void handlePoint(Collection<BigDecimal> chunks, BigDecimal currentChunk, ArrayDeque<String> wordDeque) { boolean currentChunkIsZero = currentChunk.compareTo(BigDecimal.ZERO) == 0; if (!currentChunkIsZero) { chunks.add(currentChunk); } String decimalPart = convertDecimalPart(wordDeque); chunks.add(new BigDecimal(decimalPart)); } private static void handleNegative(boolean isNegative) { if (isNegative) { throw new WordsToNumberException(WordsToNumberException.ErrorType.MULTIPLE_NEGATIVES, ""); } throw new WordsToNumberException(WordsToNumberException.ErrorType.INVALID_NEGATIVE, ""); } private static BigDecimal convertWordQueueToBigDecimal(ArrayDeque<String> wordDeque) { BigDecimal currentChunk = BigDecimal.ZERO; List<BigDecimal> chunks = new ArrayList<>(); boolean isNegative = "negative".equals(wordDeque.peek()); if (isNegative) { wordDeque.poll(); } boolean prevNumWasHundred = false; boolean prevNumWasPowerOfTen = false; while (!wordDeque.isEmpty()) { String word = wordDeque.poll(); switch (word) { case "and" -> { handleConjunction(prevNumWasHundred, prevNumWasPowerOfTen, wordDeque); continue; } case "hundred" -> { currentChunk = handleHundred(currentChunk, word, prevNumWasPowerOfTen); prevNumWasHundred = true; continue; } default -> { } } prevNumWasHundred = false; BigDecimal powerOfTen = PowerOfTen.getValue(word); if (powerOfTen != null) { handlePowerOfTen(chunks, currentChunk, powerOfTen, word, prevNumWasPowerOfTen); currentChunk = BigDecimal.ZERO; prevNumWasPowerOfTen = true; continue; } prevNumWasPowerOfTen = false; Integer number = NumberWord.getValue(word); if (number != null) { currentChunk = handleNumber(chunks, currentChunk, word, number); continue; } switch (word) { case "point" -> { handlePoint(chunks, currentChunk, wordDeque); currentChunk = BigDecimal.ZERO; continue; } case "negative" -> { handleNegative(isNegative); } default -> { } } throw new WordsToNumberException(WordsToNumberException.ErrorType.UNKNOWN_WORD, word); } if (currentChunk.compareTo(BigDecimal.ZERO) != 0) { chunks.add(currentChunk); } BigDecimal completeNumber = combineChunks(chunks); return isNegative ? completeNumber.multiply(BigDecimal.valueOf(-1)) : completeNumber; } private static boolean isAdditionSafe(BigDecimal currentChunk, BigDecimal number) { int chunkDigitCount = currentChunk.toString().length(); int numberDigitCount = number.toString().length(); return chunkDigitCount > numberDigitCount; } private static String convertDecimalPart(ArrayDeque<String> wordDeque) { StringBuilder decimalPart = new StringBuilder("."); while (!wordDeque.isEmpty()) { String word = wordDeque.poll(); Integer number = NumberWord.getValue(word); if (number == null) { throw new WordsToNumberException(WordsToNumberException.ErrorType.UNEXPECTED_WORD_AFTER_POINT, word); } decimalPart.append(number); } boolean missingNumbers = decimalPart.length() == 1; if (missingNumbers) { throw new WordsToNumberException(WordsToNumberException.ErrorType.MISSING_DECIMAL_NUMBERS, ""); } return decimalPart.toString(); } private static BigDecimal combineChunks(List<BigDecimal> chunks) { BigDecimal completeNumber = BigDecimal.ZERO; for (BigDecimal chunk : chunks) { completeNumber = completeNumber.add(chunk); } return completeNumber; } } class WordsToNumberException extends RuntimeException { @Serial private static final long serialVersionUID = 1L; enum ErrorType { NULL_INPUT("'null' or empty input provided"), UNKNOWN_WORD("Unknown Word: "), UNEXPECTED_WORD("Unexpected Word: "), UNEXPECTED_WORD_AFTER_POINT("Unexpected Word (after Point): "), MISSING_DECIMAL_NUMBERS("Decimal part is missing numbers."), MULTIPLE_NEGATIVES("Multiple 'Negative's detected."), INVALID_NEGATIVE("Incorrect 'negative' placement"), INVALID_CONJUNCTION("Incorrect 'and' placement"); private final String message; ErrorType(String message) { this.message = message; } public String formatMessage(String details) { return "Invalid Input. " + message + (details.isEmpty() ? "" : details); } } public final ErrorType errorType; WordsToNumberException(ErrorType errorType, String details) { super(errorType.formatMessage(details)); this.errorType = errorType; } public ErrorType getErrorType() { return errorType; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/PhoneticAlphabetConverter.java
src/main/java/com/thealgorithms/conversions/PhoneticAlphabetConverter.java
package com.thealgorithms.conversions; import java.util.HashMap; import java.util.Map; /** * Converts text to the NATO phonetic alphabet. * Examples: * "ABC" -> "Alpha Bravo Charlie" * "Hello" -> "Hotel Echo Lima Lima Oscar" * "123" -> "One Two Three" * "A1B2C3" -> "Alpha One Bravo Two Charlie Three" * * @author Hardvan */ public final class PhoneticAlphabetConverter { private PhoneticAlphabetConverter() { } private static final Map<Character, String> PHONETIC_MAP = new HashMap<>(); static { PHONETIC_MAP.put('A', "Alpha"); PHONETIC_MAP.put('B', "Bravo"); PHONETIC_MAP.put('C', "Charlie"); PHONETIC_MAP.put('D', "Delta"); PHONETIC_MAP.put('E', "Echo"); PHONETIC_MAP.put('F', "Foxtrot"); PHONETIC_MAP.put('G', "Golf"); PHONETIC_MAP.put('H', "Hotel"); PHONETIC_MAP.put('I', "India"); PHONETIC_MAP.put('J', "Juliett"); PHONETIC_MAP.put('K', "Kilo"); PHONETIC_MAP.put('L', "Lima"); PHONETIC_MAP.put('M', "Mike"); PHONETIC_MAP.put('N', "November"); PHONETIC_MAP.put('O', "Oscar"); PHONETIC_MAP.put('P', "Papa"); PHONETIC_MAP.put('Q', "Quebec"); PHONETIC_MAP.put('R', "Romeo"); PHONETIC_MAP.put('S', "Sierra"); PHONETIC_MAP.put('T', "Tango"); PHONETIC_MAP.put('U', "Uniform"); PHONETIC_MAP.put('V', "Victor"); PHONETIC_MAP.put('W', "Whiskey"); PHONETIC_MAP.put('X', "X-ray"); PHONETIC_MAP.put('Y', "Yankee"); PHONETIC_MAP.put('Z', "Zulu"); PHONETIC_MAP.put('0', "Zero"); PHONETIC_MAP.put('1', "One"); PHONETIC_MAP.put('2', "Two"); PHONETIC_MAP.put('3', "Three"); PHONETIC_MAP.put('4', "Four"); PHONETIC_MAP.put('5', "Five"); PHONETIC_MAP.put('6', "Six"); PHONETIC_MAP.put('7', "Seven"); PHONETIC_MAP.put('8', "Eight"); PHONETIC_MAP.put('9', "Nine"); } /** * Converts text to the NATO phonetic alphabet. * Steps: * 1. Convert the text to uppercase. * 2. Iterate over each character in the text. * 3. Get the phonetic equivalent of the character from the map. * 4. Append the phonetic equivalent to the result. * 5. Append a space to separate the phonetic equivalents. * 6. Return the result. * * @param text the text to convert * @return the NATO phonetic alphabet */ public static String textToPhonetic(String text) { StringBuilder phonetic = new StringBuilder(); for (char c : text.toUpperCase().toCharArray()) { if (Character.isWhitespace(c)) { continue; } phonetic.append(PHONETIC_MAP.getOrDefault(c, String.valueOf(c))).append(" "); } return phonetic.toString().trim(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/UnitConversions.java
src/main/java/com/thealgorithms/conversions/UnitConversions.java
package com.thealgorithms.conversions; import static java.util.Map.entry; import java.util.Map; import org.apache.commons.lang3.tuple.Pair; /** * A utility class to perform unit conversions between different measurement systems. * * <p>Currently, the class supports temperature conversions between several scales: * Celsius, Fahrenheit, Kelvin, Réaumur, Delisle, and Rankine. * * <h2>Example Usage</h2> * <pre> * double result = UnitConversions.TEMPERATURE.convert("Celsius", "Fahrenheit", 100.0); * // Output: 212.0 (Celsius to Fahrenheit conversion of 100°C) * </pre> * * <p>This class makes use of an {@link UnitsConverter} that handles the conversion logic * based on predefined affine transformations. These transformations include scaling factors * and offsets for temperature conversions. * * <h2>Temperature Scales Supported</h2> * <ul> * <li>Celsius</li> * <li>Fahrenheit</li> * <li>Kelvin</li> * <li>Réaumur</li> * <li>Delisle</li> * <li>Rankine</li> * </ul> */ public final class UnitConversions { private UnitConversions() { } /** * A preconfigured instance of {@link UnitsConverter} for temperature conversions. * The converter handles conversions between the following temperature units: * <ul> * <li>Kelvin to Celsius</li> * <li>Celsius to Fahrenheit</li> * <li>Réaumur to Celsius</li> * <li>Delisle to Celsius</li> * <li>Rankine to Kelvin</li> * </ul> */ public static final UnitsConverter TEMPERATURE = new UnitsConverter(Map.ofEntries(entry(Pair.of("Kelvin", "Celsius"), new AffineConverter(1.0, -273.15)), entry(Pair.of("Celsius", "Fahrenheit"), new AffineConverter(9.0 / 5.0, 32.0)), entry(Pair.of("Réaumur", "Celsius"), new AffineConverter(5.0 / 4.0, 0.0)), entry(Pair.of("Delisle", "Celsius"), new AffineConverter(-2.0 / 3.0, 100.0)), entry(Pair.of("Rankine", "Kelvin"), new AffineConverter(5.0 / 9.0, 0.0)))); }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/Base64.java
src/main/java/com/thealgorithms/conversions/Base64.java
package com.thealgorithms.conversions; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; /** * Base64 is a group of binary-to-text encoding schemes that represent binary data * in an ASCII string format by translating it into a radix-64 representation. * Each base64 digit represents exactly 6 bits of data. * * Base64 encoding is commonly used when there is a need to encode binary data * that needs to be stored and transferred over media that are designed to deal * with textual data. * * Wikipedia Reference: https://en.wikipedia.org/wiki/Base64 * Author: Nithin U. * Github: https://github.com/NithinU2802 */ public final class Base64 { // Base64 character set private static final String BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static final char PADDING_CHAR = '='; private Base64() { } /** * Encodes the given byte array to a Base64 encoded string. * * @param input the byte array to encode * @return the Base64 encoded string * @throws IllegalArgumentException if input is null */ public static String encode(byte[] input) { if (input == null) { throw new IllegalArgumentException("Input cannot be null"); } if (input.length == 0) { return ""; } StringBuilder result = new StringBuilder(); int padding = 0; // Process input in groups of 3 bytes for (int i = 0; i < input.length; i += 3) { // Get up to 3 bytes int byte1 = input[i] & 0xFF; int byte2 = (i + 1 < input.length) ? (input[i + 1] & 0xFF) : 0; int byte3 = (i + 2 < input.length) ? (input[i + 2] & 0xFF) : 0; // Calculate padding needed if (i + 1 >= input.length) { padding = 2; } else if (i + 2 >= input.length) { padding = 1; } // Combine 3 bytes into a 24-bit number int combined = (byte1 << 16) | (byte2 << 8) | byte3; // Extract four 6-bit groups result.append(BASE64_CHARS.charAt((combined >> 18) & 0x3F)); result.append(BASE64_CHARS.charAt((combined >> 12) & 0x3F)); result.append(BASE64_CHARS.charAt((combined >> 6) & 0x3F)); result.append(BASE64_CHARS.charAt(combined & 0x3F)); } // Replace padding characters if (padding > 0) { result.setLength(result.length() - padding); for (int i = 0; i < padding; i++) { result.append(PADDING_CHAR); } } return result.toString(); } /** * Encodes the given string to a Base64 encoded string using UTF-8 encoding. * * @param input the string to encode * @return the Base64 encoded string * @throws IllegalArgumentException if input is null */ public static String encode(String input) { if (input == null) { throw new IllegalArgumentException("Input cannot be null"); } return encode(input.getBytes(StandardCharsets.UTF_8)); } /** * Decodes the given Base64 encoded string to a byte array. * * @param input the Base64 encoded string to decode * @return the decoded byte array * @throws IllegalArgumentException if input is null or contains invalid Base64 characters */ public static byte[] decode(String input) { if (input == null) { throw new IllegalArgumentException("Input cannot be null"); } if (input.isEmpty()) { return new byte[0]; } // Strict RFC 4648 compliance: length must be a multiple of 4 if (input.length() % 4 != 0) { throw new IllegalArgumentException("Invalid Base64 input length; must be multiple of 4"); } // Validate padding: '=' can only appear at the end (last 1 or 2 chars) int firstPadding = input.indexOf('='); if (firstPadding != -1 && firstPadding < input.length() - 2) { throw new IllegalArgumentException("Padding '=' can only appear at the end (last 1 or 2 characters)"); } List<Byte> result = new ArrayList<>(); // Process input in groups of 4 characters for (int i = 0; i < input.length(); i += 4) { // Get up to 4 characters int char1 = getBase64Value(input.charAt(i)); int char2 = getBase64Value(input.charAt(i + 1)); int char3 = input.charAt(i + 2) == '=' ? 0 : getBase64Value(input.charAt(i + 2)); int char4 = input.charAt(i + 3) == '=' ? 0 : getBase64Value(input.charAt(i + 3)); // Combine four 6-bit groups into a 24-bit number int combined = (char1 << 18) | (char2 << 12) | (char3 << 6) | char4; // Extract three 8-bit bytes result.add((byte) ((combined >> 16) & 0xFF)); if (input.charAt(i + 2) != '=') { result.add((byte) ((combined >> 8) & 0xFF)); } if (input.charAt(i + 3) != '=') { result.add((byte) (combined & 0xFF)); } } // Convert List<Byte> to byte[] byte[] resultArray = new byte[result.size()]; for (int i = 0; i < result.size(); i++) { resultArray[i] = result.get(i); } return resultArray; } /** * Decodes the given Base64 encoded string to a string using UTF-8 encoding. * * @param input the Base64 encoded string to decode * @return the decoded string * @throws IllegalArgumentException if input is null or contains invalid Base64 characters */ public static String decodeToString(String input) { if (input == null) { throw new IllegalArgumentException("Input cannot be null"); } byte[] decodedBytes = decode(input); return new String(decodedBytes, StandardCharsets.UTF_8); } /** * Gets the numeric value of a Base64 character. * * @param c the Base64 character * @return the numeric value (0-63) * @throws IllegalArgumentException if character is not a valid Base64 character */ private static int getBase64Value(char c) { if (c >= 'A' && c <= 'Z') { return c - 'A'; } else if (c >= 'a' && c <= 'z') { return c - 'a' + 26; } else if (c >= '0' && c <= '9') { return c - '0' + 52; } else if (c == '+') { return 62; } else if (c == '/') { return 63; } else { throw new IllegalArgumentException("Invalid Base64 character: " + c); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/DecimalToOctal.java
src/main/java/com/thealgorithms/conversions/DecimalToOctal.java
package com.thealgorithms.conversions; /** * This class converts Decimal numbers to Octal Numbers */ public final class DecimalToOctal { private static final int OCTAL_BASE = 8; private static final int INITIAL_OCTAL_VALUE = 0; private static final int INITIAL_PLACE_VALUE = 1; private DecimalToOctal() { } /** * Converts a decimal number to its octal equivalent. * * @param decimal The decimal number to convert. * @return The octal equivalent as an integer. * @throws IllegalArgumentException if the decimal number is negative. */ public static int convertToOctal(int decimal) { if (decimal < 0) { throw new IllegalArgumentException("Decimal number cannot be negative."); } int octal = INITIAL_OCTAL_VALUE; int placeValue = INITIAL_PLACE_VALUE; while (decimal != 0) { int remainder = decimal % OCTAL_BASE; octal += remainder * placeValue; decimal /= OCTAL_BASE; placeValue *= 10; } return octal; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/BinaryToOctal.java
src/main/java/com/thealgorithms/conversions/BinaryToOctal.java
package com.thealgorithms.conversions; public final class BinaryToOctal { private static final int BITS_PER_OCTAL_DIGIT = 3; private static final int BINARY_BASE = 2; private static final int DECIMAL_BASE = 10; private BinaryToOctal() { } /** * This method converts a binary number to an octal number. * * @param binary The binary number * @return The octal number * @throws IllegalArgumentException if the input is not a valid binary number */ public static String convertBinaryToOctal(int binary) { if (binary == 0) { return "0"; } if (!String.valueOf(binary).matches("[01]+")) { throw new IllegalArgumentException("Input is not a valid binary number."); } StringBuilder octal = new StringBuilder(); int currentBit; int bitValueMultiplier = 1; while (binary != 0) { int octalDigit = 0; for (int i = 0; i < BITS_PER_OCTAL_DIGIT && binary != 0; i++) { currentBit = binary % DECIMAL_BASE; binary /= DECIMAL_BASE; octalDigit += currentBit * bitValueMultiplier; bitValueMultiplier *= BINARY_BASE; } octal.insert(0, octalDigit); bitValueMultiplier = 1; // Reset multiplier for the next group } return octal.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java
src/main/java/com/thealgorithms/conversions/IntegerToRoman.java
package com.thealgorithms.conversions; /** * A utility class to convert integers into Roman numerals. * * <p>Roman numerals follow these rules: * <ul> * <li>I = 1</li> * <li>IV = 4</li> * <li>V = 5</li> * <li>IX = 9</li> * <li>X = 10</li> * <li>XL = 40</li> * <li>L = 50</li> * <li>XC = 90</li> * <li>C = 100</li> * <li>D = 500</li> * <li>M = 1000</li> * </ul> * * <p>Conversion is based on repeatedly subtracting the largest possible Roman numeral value * from the input number until it reaches zero. For example, 1994 is converted as: * <pre> * 1994 -> MCMXCIV (1000 + 900 + 90 + 4) * </pre> */ public final class IntegerToRoman { // Array of Roman numeral values in descending order private static final int[] ALL_ROMAN_NUMBERS_IN_ARABIC = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; // Corresponding Roman numeral symbols private static final String[] ALL_ROMAN_NUMBERS = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; private IntegerToRoman() { } /** * Converts an integer to its Roman numeral representation. * Steps: * <ol> * <li>Iterate over the Roman numeral values in descending order</li> * <li>Calculate how many times a numeral fits</li> * <li>Append the corresponding symbol</li> * <li>Subtract the value from the number</li> * <li>Repeat until the number is zero</li> * <li>Return the Roman numeral representation</li> * </ol> * * @param num the integer value to convert (must be greater than 0) * @return the Roman numeral representation of the input integer * or an empty string if the input is non-positive */ public static String integerToRoman(int num) { if (num <= 0) { return ""; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < ALL_ROMAN_NUMBERS_IN_ARABIC.length; i++) { int times = num / ALL_ROMAN_NUMBERS_IN_ARABIC[i]; builder.append(ALL_ROMAN_NUMBERS[i].repeat(Math.max(0, times))); num -= times * ALL_ROMAN_NUMBERS_IN_ARABIC[i]; } return builder.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java
src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java
package com.thealgorithms.conversions; /** * Class for converting an Octal number to its Hexadecimal equivalent. * * @author Tanmay Joshi */ public final class OctalToHexadecimal { private static final int OCTAL_BASE = 8; private static final int HEX_BASE = 16; private static final String HEX_DIGITS = "0123456789ABCDEF"; private OctalToHexadecimal() { } /** * Converts an Octal number (as a string) to its Decimal equivalent. * * @param octalNumber The Octal number as a string * @return The Decimal equivalent of the Octal number * @throws IllegalArgumentException if the input contains invalid octal digits */ public static int octalToDecimal(String octalNumber) { if (octalNumber == null || octalNumber.isEmpty()) { throw new IllegalArgumentException("Input cannot be null or empty"); } int decimalValue = 0; for (int i = 0; i < octalNumber.length(); i++) { char currentChar = octalNumber.charAt(i); if (currentChar < '0' || currentChar > '7') { throw new IllegalArgumentException("Incorrect octal digit: " + currentChar); } int currentDigit = currentChar - '0'; decimalValue = decimalValue * OCTAL_BASE + currentDigit; } return decimalValue; } /** * Converts a Decimal number to its Hexadecimal equivalent. * * @param decimalNumber The Decimal number * @return The Hexadecimal equivalent of the Decimal number */ public static String decimalToHexadecimal(int decimalNumber) { if (decimalNumber == 0) { return "0"; } StringBuilder hexValue = new StringBuilder(); while (decimalNumber > 0) { int digit = decimalNumber % HEX_BASE; hexValue.insert(0, HEX_DIGITS.charAt(digit)); decimalNumber /= HEX_BASE; } return hexValue.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/TemperatureConverter.java
src/main/java/com/thealgorithms/conversions/TemperatureConverter.java
package com.thealgorithms.conversions; /** * A utility class to convert between different temperature units. * * <p>This class supports conversions between the following units: * <ul> * <li>Celsius</li> * <li>Fahrenheit</li> * <li>Kelvin</li> * </ul> * * <p>This class is final and cannot be instantiated. * * @author krishna-medapati (https://github.com/krishna-medapati) * @see <a href="https://en.wikipedia.org/wiki/Conversion_of_scales_of_temperature">Wikipedia: Temperature Conversion</a> */ public final class TemperatureConverter { private TemperatureConverter() { } public static double celsiusToFahrenheit(double celsius) { return celsius * 9.0 / 5.0 + 32.0; } public static double celsiusToKelvin(double celsius) { return celsius + 273.15; } public static double fahrenheitToCelsius(double fahrenheit) { return (fahrenheit - 32.0) * 5.0 / 9.0; } public static double fahrenheitToKelvin(double fahrenheit) { return (fahrenheit - 32.0) * 5.0 / 9.0 + 273.15; } public static double kelvinToCelsius(double kelvin) { return kelvin - 273.15; } public static double kelvinToFahrenheit(double kelvin) { return (kelvin - 273.15) * 9.0 / 5.0 + 32.0; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java
src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java
package com.thealgorithms.conversions; import java.util.HashMap; import java.util.Map; /** * Converts text to Morse code and vice-versa. * Text to Morse code: Each letter is separated by a space and each word is separated by a pipe (|). * Example: "HELLO WORLD" -> ".... . .-.. .-.. --- | .-- --- .-. .-.. -.." * * Morse code to text: Each letter is separated by a space and each word is separated by a pipe (|). * Example: ".... . .-.. .-.. --- | .-- --- .-. .-.. -.." -> "HELLO WORLD" * * Applications: Used in radio communications and algorithmic challenges. * * @author Hardvan */ public final class MorseCodeConverter { private MorseCodeConverter() { } private static final Map<Character, String> MORSE_MAP = new HashMap<>(); private static final Map<String, Character> REVERSE_MAP = new HashMap<>(); static { MORSE_MAP.put('A', ".-"); MORSE_MAP.put('B', "-..."); MORSE_MAP.put('C', "-.-."); MORSE_MAP.put('D', "-.."); MORSE_MAP.put('E', "."); MORSE_MAP.put('F', "..-."); MORSE_MAP.put('G', "--."); MORSE_MAP.put('H', "...."); MORSE_MAP.put('I', ".."); MORSE_MAP.put('J', ".---"); MORSE_MAP.put('K', "-.-"); MORSE_MAP.put('L', ".-.."); MORSE_MAP.put('M', "--"); MORSE_MAP.put('N', "-."); MORSE_MAP.put('O', "---"); MORSE_MAP.put('P', ".--."); MORSE_MAP.put('Q', "--.-"); MORSE_MAP.put('R', ".-."); MORSE_MAP.put('S', "..."); MORSE_MAP.put('T', "-"); MORSE_MAP.put('U', "..-"); MORSE_MAP.put('V', "...-"); MORSE_MAP.put('W', ".--"); MORSE_MAP.put('X', "-..-"); MORSE_MAP.put('Y', "-.--"); MORSE_MAP.put('Z', "--.."); // Build reverse map for decoding MORSE_MAP.forEach((k, v) -> REVERSE_MAP.put(v, k)); } /** * Converts text to Morse code. * Each letter is separated by a space and each word is separated by a pipe (|). * * @param text The text to convert to Morse code. * @return The Morse code representation of the text. */ public static String textToMorse(String text) { StringBuilder morse = new StringBuilder(); String[] words = text.toUpperCase().split(" "); for (int i = 0; i < words.length; i++) { for (char c : words[i].toCharArray()) { morse.append(MORSE_MAP.getOrDefault(c, "")).append(" "); } if (i < words.length - 1) { morse.append("| "); } } return morse.toString().trim(); } /** * Converts Morse code to text. * Each letter is separated by a space and each word is separated by a pipe (|). * * @param morse The Morse code to convert to text. * @return The text representation of the Morse code. */ public static String morseToText(String morse) { StringBuilder text = new StringBuilder(); String[] words = morse.split(" \\| "); for (int i = 0; i < words.length; i++) { for (String code : words[i].split(" ")) { text.append(REVERSE_MAP.getOrDefault(code, '?')); } if (i < words.length - 1) { text.append(" "); } } return text.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false