Repository: TheAlgorithms/Java
Pull request #5537 (2024-10-03 05:26:25)

Add `Infix To Prefix` new algorithm with unit tests
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5537?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `82.14286%` with `5 lines` in your changes missing coverage. Please review.
> Project coverage is 52.65%. Comparing base [(`013d122`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/013d122e7dcb302bc47aca78f451f0ed043b6a45?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`a3c67fe`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/a3c67fe6095f3a9ff9d642a80eadeebf2a9f6b1b?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5537?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...n/java/com/thealgorithms/stacks/InfixToPrefix.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5537?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fstacks%2FInfixToPrefix.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9zdGFja3MvSW5maXhUb1ByZWZpeC5qYXZh) | 82.14% | [2 Missing and 3 partials :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5537?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5537      +/-   ##
============================================
+ Coverage     52.60%   52.65%   +0.05%     
- Complexity     3287     3300      +13     
============================================
  Files           528      529       +1     
  Lines         15324    15352      +28     
  Branches       2913     2920       +7     
============================================
+ Hits           8061     8084      +23     
- Misses         6931     6933       +2     
- Partials        332      335       +3     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5537?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

Hardvan: I have implemented the suggested changes @alxkm .

Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 3e210b57..4fb91699 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -268,6 +268,7 @@
           * greedyalgorithms
             * [ActivitySelection](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/ActivitySelection.java)
             * [CoinChange](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/CoinChange.java)
+            * [DigitSeparation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/DigitSeparation.java)
             * [FractionalKnapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java)
             * [GaleShapley](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/GaleShapley.java)
             * [JobSequencing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java)
@@ -545,6 +546,7 @@
             * [DecimalToAnyUsingStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/DecimalToAnyUsingStack.java)
             * [DuplicateBrackets](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/DuplicateBrackets.java)
             * [InfixToPostfix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/InfixToPostfix.java)
+            * [InfixToPrefix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/InfixToPrefix.java)
             * [LargestRectangle](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/LargestRectangle.java)
             * [MaximumMinimumWindow](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/MaximumMinimumWindow.java)
             * [NextGreaterElement](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/NextGreaterElement.java)
@@ -759,6 +761,7 @@
           * greedyalgorithms
             * [ActivitySelectionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/ActivitySelectionTest.java)
             * [CoinChangeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/CoinChangeTest.java)
+            * [DigitSeparationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/DigitSeparationTest.java)
             * [FractionalKnapsackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackTest.java)
             * [GaleShapleyTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/GaleShapleyTest.java)
             * [JobSequencingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java)
@@ -976,6 +979,7 @@
             * [DecimalToAnyUsingStackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/DecimalToAnyUsingStackTest.java)
             * [DuplicateBracketsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/DuplicateBracketsTest.java)
             * [InfixToPostfixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java)
+            * [InfixToPrefixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java)
             * [LargestRectangleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/LargestRectangleTest.java)
             * [NextGreaterElementTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java)
             * [NextSmallerElementTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/NextSmallerElementTest.java)
diff --git a/src/main/java/com/thealgorithms/stacks/InfixToPrefix.java b/src/main/java/com/thealgorithms/stacks/InfixToPrefix.java
new file mode 100644
index 00000000..3d90d14e
--- /dev/null
+++ b/src/main/java/com/thealgorithms/stacks/InfixToPrefix.java
@@ -0,0 +1,92 @@
+package com.thealgorithms.stacks;
+
+import java.util.Stack;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public final class InfixToPrefix {
+    private InfixToPrefix() {
+    }
+
+    /**
+     * Convert an infix expression to a prefix expression using stack.
+     *
+     * @param infixExpression the infix expression to convert
+     * @return the prefix expression
+     * @throws IllegalArgumentException if the infix expression has unbalanced brackets
+     * @throws NullPointerException     if the infix expression is null
+     */
+    public static String infix2Prefix(String infixExpression) throws IllegalArgumentException {
+        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> stack = new Stack<>();
+        // Reverse the infix expression for prefix conversion
+        String reversedInfix = new StringBuilder(infixExpression).reverse().toString();
+        for (char element : reversedInfix.toCharArray()) {
+            if (Character.isLetterOrDigit(element)) {
+                output.append(element);
+            } else if (element == ')') {
+                stack.push(element);
+            } else if (element == '(') {
+                while (!stack.isEmpty() && stack.peek() != ')') {
+                    output.append(stack.pop());
+                }
+                stack.pop();
+            } else {
+                while (!stack.isEmpty() && precedence(element) < precedence(stack.peek())) {
+                    output.append(stack.pop());
+                }
+                stack.push(element);
+            }
+        }
+        while (!stack.isEmpty()) {
+            output.append(stack.pop());
+        }
+
+        // Reverse the result to get the prefix expression
+        return output.reverse().toString();
+    }
+
+    /**
+     * Determines the precedence of an operator.
+     *
+     * @param operator the operator whose precedence is to be determined
+     * @return the precedence of the operator
+     */
+    private static int precedence(char operator) {
+        switch (operator) {
+        case '+':
+        case '-':
+            return 0;
+        case '*':
+        case '/':
+            return 1;
+        case '^':
+            return 2;
+        default:
+            return -1;
+        }
+    }
+
+    /**
+     * Filters out all characters from the input string except brackets.
+     *
+     * @param input the input string to filter
+     * @return a string containing only brackets from the input string
+     */
+    private static String filterBrackets(String input) {
+        Pattern pattern = Pattern.compile("[^(){}\\[\\]<>]");
+        Matcher matcher = pattern.matcher(input);
+        return matcher.replaceAll("");
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java b/src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java
new file mode 100644
index 00000000..91be8a63
--- /dev/null
+++ b/src/test/java/com/thealgorithms/stacks/InfixToPrefixTest.java
@@ -0,0 +1,44 @@
+package com.thealgorithms.stacks;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class InfixToPrefixTest {
+
+    @ParameterizedTest
+    @MethodSource("provideValidExpressions")
+    void testValidExpressions(String infix, String expectedPrefix) throws Exception {
+        assertEquals(expectedPrefix, InfixToPrefix.infix2Prefix(infix));
+    }
+
+    @Test
+    void testEmptyString() {
+        // Assuming that an empty string returns an empty prefix or throws an exception
+        assertEquals("", InfixToPrefix.infix2Prefix(""));
+    }
+
+    @Test
+    void testNullValue() {
+        // Assuming that a null input throws a NullPointerException
+        assertThrows(NullPointerException.class, () -> InfixToPrefix.infix2Prefix(null));
+    }
+
+    private static Stream<Arguments> provideValidExpressions() {
+        return Stream.of(Arguments.of("3+2", "+32"), // Simple addition
+            Arguments.of("1+(2+3)", "+1+23"), // Parentheses
+            Arguments.of("(3+4)*5-6", "-*+3456"), // Nested operations
+            Arguments.of("a+b*c", "+a*bc"), // Multiplication precedence
+            Arguments.of("a+b*c/d", "+a/*bcd"), // Division precedence
+            Arguments.of("a+b*c-d", "-+a*bcd"), // Subtraction precedence
+            Arguments.of("a+b*c/d-e", "-+a/*bcde"), // Mixed precedence
+            Arguments.of("a+b*(c-d)", "+a*b-cd"), // Parentheses precedence
+            Arguments.of("a+b*(c-d)/e", "+a/*b-cde") // Mixed precedence with parentheses
+        );
+    }
+}