Repository: TheAlgorithms/Java
Pull request #5552 (2024-10-03 14:22:08)

Add `PrefixToInfix.java` new algorithm
<!--
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/5552?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 53.02%. Comparing base [(`842ff52`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/842ff5294f5e97dfd1e4c09f9d9e01a89ac16e32?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`19268f0`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/19268f04a5c5bb66001dfcec918bc38779b2b609?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).
> Report is 8 commits behind head on master.

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


```diff
@@             Coverage Diff              @@
##             master    #5552      +/-   ##
============================================
+ Coverage     52.31%   53.02%   +0.71%     
- Complexity     3259     3321      +62     
============================================
  Files           526      530       +4     
  Lines         15205    15359     +154     
  Branches       2892     2928      +36     
============================================
+ Hits           7954     8144     +190     
+ Misses         6924     6881      -43     
- Partials        327      334       +7     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5552?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, and added the test for `stack size != 1` before the return statement.

Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 4fb91699..3662a8cd 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -552,6 +552,7 @@
             * [NextGreaterElement](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/NextGreaterElement.java)
             * [NextSmallerElement](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java)
             * [PostfixToInfix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java)
+            * [PrefixToInfix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java)
             * [StackPostfixNotation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java)
           * strings
             * [AhoCorasick](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/AhoCorasick.java)
@@ -984,6 +985,7 @@
             * [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)
             * [PostfixToInfixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/PostfixToInfixTest.java)
+            * [PrefixToInfixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java)
             * [StackPostfixNotationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java)
           * strings
             * [AhoCorasickTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/AhoCorasickTest.java)
diff --git a/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java b/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java
new file mode 100644
index 00000000..41eb974b
--- /dev/null
+++ b/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java
@@ -0,0 +1,69 @@
+package com.thealgorithms.stacks;
+
+import java.util.Stack;
+
+/**
+ * Converts a prefix expression to an infix expression using a stack.
+ *
+ * The input prefix expression should consist of
+ * valid operands (letters or digits) and operators (+, -, *, /, ^).
+ * Parentheses are not required in the prefix string.
+ */
+public final class PrefixToInfix {
+    private PrefixToInfix() {
+    }
+
+    /**
+     * Determines if a given character is a valid arithmetic operator.
+     *
+     * @param token the character to check
+     * @return true if the character is an operator, false otherwise
+     */
+    public static boolean isOperator(char token) {
+        return token == '+' || token == '-' || token == '/' || token == '*' || token == '^';
+    }
+
+    /**
+     * Converts a valid prefix expression to an infix expression.
+     *
+     * @param prefix the prefix expression to convert
+     * @return the equivalent infix expression
+     * @throws NullPointerException     if the prefix expression is null
+     */
+    public static String getPrefixToInfix(String prefix) {
+        if (prefix == null) {
+            throw new NullPointerException("Null prefix expression");
+        }
+        if (prefix.isEmpty()) {
+            return "";
+        }
+
+        Stack<String> stack = new Stack<>();
+
+        // Iterate over the prefix expression from right to left
+        for (int i = prefix.length() - 1; i >= 0; i--) {
+            char token = prefix.charAt(i);
+
+            if (isOperator(token)) {
+                // Pop two operands from stack
+                String operandA = stack.pop();
+                String operandB = stack.pop();
+
+                // Form the infix expression with parentheses
+                String infix = "(" + operandA + token + operandB + ")";
+
+                // Push the resulting infix expression back onto the stack
+                stack.push(infix);
+            } else {
+                // Push operand onto stack
+                stack.push(Character.toString(token));
+            }
+        }
+
+        if (stack.size() != 1) {
+            throw new ArithmeticException("Malformed prefix expression");
+        }
+
+        return stack.pop(); // final element on the stack is the full infix expression
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java b/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.java
new file mode 100644
index 00000000..83fd09e1
--- /dev/null
+++ b/src/test/java/com/thealgorithms/stacks/PrefixToInfixTest.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;
+
+class PrefixToInfixTest {
+
+    @ParameterizedTest
+    @MethodSource("provideValidPrefixToInfixTestCases")
+    void testValidPrefixToInfixConversion(String prefix, String expectedInfix) {
+        assertEquals(expectedInfix, PrefixToInfix.getPrefixToInfix(prefix));
+    }
+
+    static Stream<Arguments> provideValidPrefixToInfixTestCases() {
+        return Stream.of(Arguments.of("A", "A"), // Single operand
+            Arguments.of("+AB", "(A+B)"), // Addition
+            Arguments.of("*+ABC", "((A+B)*C)"), // Addition and multiplication
+            Arguments.of("-+A*BCD", "((A+(B*C))-D)"), // Mixed operators
+            Arguments.of("/-A*BC+DE", "((A-(B*C))/(D+E))"), // Mixed operators
+            Arguments.of("^+AB*CD", "((A+B)^(C*D))") // Mixed operators
+        );
+    }
+
+    @Test
+    void testEmptyPrefixExpression() {
+        assertEquals("", PrefixToInfix.getPrefixToInfix(""));
+    }
+
+    @Test
+    void testNullPrefixExpression() {
+        assertThrows(NullPointerException.class, () -> PrefixToInfix.getPrefixToInfix(null));
+    }
+
+    @Test
+    void testMalformedPrefixExpression() {
+        assertThrows(ArithmeticException.class, () -> PrefixToInfix.getPrefixToInfix("+ABC"));
+    }
+}