Repository: TheAlgorithms/Java
Pull request #5754 (2024-10-13 06:50:40)

feat: Add `PostfixEvaluator` new algorithm with Junit 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/5754?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 `77.77778%` with `4 lines` in your changes missing coverage. Please review.
> Project coverage is 63.97%. Comparing base [(`6682c7c`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/6682c7c76e2bf016e2e7b51a6027ac30d354b13e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`1ecc1fc`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/1ecc1fcaaab0804bf0e2721d1d29e0c29d01293b?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/5754?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...ava/com/thealgorithms/stacks/PostfixEvaluator.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5754?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fstacks%2FPostfixEvaluator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9zdGFja3MvUG9zdGZpeEV2YWx1YXRvci5qYXZh) | 77.77% | [2 Missing and 2 partials :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5754?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    #5754      +/-   ##
============================================
+ Coverage     63.96%   63.97%   +0.01%     
- Complexity     4172     4183      +11     
============================================
  Files           583      584       +1     
  Lines         16320    16338      +18     
  Branches       3150     3153       +3     
============================================
+ Hits          10439    10453      +14     
- Misses         5456     5458       +2     
- Partials        425      427       +2     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5754?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).


Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 06307d4a..a78efffb 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -598,6 +598,7 @@
             * [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)
             * [NextSmallerElement](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java)
+            * [PostfixEvaluator](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/PostfixEvaluator.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)
             * [SortStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/SortStack.java)
@@ -1128,6 +1129,7 @@
             * [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)
+            * [PostfixEvaluatorTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/PostfixEvaluatorTest.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)
             * [SortStackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/SortStackTest.java)
diff --git a/src/main/java/com/thealgorithms/stacks/PostfixEvaluator.java b/src/main/java/com/thealgorithms/stacks/PostfixEvaluator.java
new file mode 100644
index 00000000..02ef5af8
--- /dev/null
+++ b/src/main/java/com/thealgorithms/stacks/PostfixEvaluator.java
@@ -0,0 +1,74 @@
+package com.thealgorithms.stacks;
+
+import java.util.Set;
+import java.util.Stack;
+
+/**
+ * Evaluate a postfix (Reverse Polish) expression using a stack.
+ *
+ * <p>Example: Expression "5 6 + 2 *" results in 22.
+ * <p>Applications: Used in calculators and expression evaluation in compilers.
+ *
+ * @author Hardvan
+ */
+public final class PostfixEvaluator {
+    private PostfixEvaluator() {
+    }
+
+    private static final Set<String> OPERATORS = Set.of("+", "-", "*", "/");
+
+    /**
+     * Evaluates the given postfix expression and returns the result.
+     *
+     * @param expression The postfix expression as a string with operands and operators separated by spaces.
+     * @return The result of evaluating the postfix expression.
+     * @throws IllegalArgumentException if the expression is invalid.
+     */
+    public static int evaluatePostfix(String expression) {
+        Stack<Integer> stack = new Stack<>();
+
+        for (String token : expression.split("\\s+")) {
+            if (isOperator(token)) {
+                int operand2 = stack.pop();
+                int operand1 = 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");
+        };
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/stacks/PostfixEvaluatorTest.java b/src/test/java/com/thealgorithms/stacks/PostfixEvaluatorTest.java
new file mode 100644
index 00000000..882fe644
--- /dev/null
+++ b/src/test/java/com/thealgorithms/stacks/PostfixEvaluatorTest.java
@@ -0,0 +1,27 @@
+package com.thealgorithms.stacks;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.EmptyStackException;
+import org.junit.jupiter.api.Test;
+
+public class PostfixEvaluatorTest {
+
+    @Test
+    public void testValidExpressions() {
+        assertEquals(22, PostfixEvaluator.evaluatePostfix("5 6 + 2 *"));
+        assertEquals(27, PostfixEvaluator.evaluatePostfix("7 2 + 3 *"));
+        assertEquals(3, PostfixEvaluator.evaluatePostfix("10 5 / 1 +"));
+    }
+
+    @Test
+    public void testInvalidExpression() {
+        assertThrows(EmptyStackException.class, () -> PostfixEvaluator.evaluatePostfix("5 +"));
+    }
+
+    @Test
+    public void testMoreThanOneStackSizeAfterEvaluation() {
+        assertThrows(IllegalArgumentException.class, () -> PostfixEvaluator.evaluatePostfix("5 6 + 2 * 3"));
+    }
+}