Repository: TheAlgorithms/Java
Pull request #5755 (2024-10-13 06:53:32)

feat: Add `PrefixEvaluator` 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/5755?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 `90.00000%` with `2 lines` in your changes missing coverage. Please review.
> Project coverage is 63.98%. 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 [(`2f07871`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/2f07871d545befc23db989f064f1a4a6d2cb3381?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/5755?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...java/com/thealgorithms/stacks/PrefixEvaluator.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5755?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fstacks%2FPrefixEvaluator.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9zdGFja3MvUHJlZml4RXZhbHVhdG9yLmphdmE=) | 90.00% | [1 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5755?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    #5755      +/-   ##
============================================
+ Coverage     63.96%   63.98%   +0.01%     
- Complexity     4172     4184      +12     
============================================
  Files           583      584       +1     
  Lines         16320    16340      +20     
  Branches       3150     3153       +3     
============================================
+ Hits          10439    10455      +16     
- 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/5755?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 a78efffb..d9beaadc 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -600,6 +600,7 @@
             * [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)
+            * [PrefixEvaluator](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/PrefixEvaluator.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)
             * [StackPostfixNotation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/StackPostfixNotation.java)
@@ -1131,6 +1132,7 @@
             * [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)
+            * [PrefixEvaluatorTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/PrefixEvaluatorTest.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)
             * [StackPostfixNotationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java)
diff --git a/src/main/java/com/thealgorithms/stacks/PrefixEvaluator.java b/src/main/java/com/thealgorithms/stacks/PrefixEvaluator.java
new file mode 100644
index 00000000..eb2ce95e
--- /dev/null
+++ b/src/main/java/com/thealgorithms/stacks/PrefixEvaluator.java
@@ -0,0 +1,76 @@
+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");
+        };
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/stacks/PrefixEvaluatorTest.java b/src/test/java/com/thealgorithms/stacks/PrefixEvaluatorTest.java
new file mode 100644
index 00000000..e2faa619
--- /dev/null
+++ b/src/test/java/com/thealgorithms/stacks/PrefixEvaluatorTest.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 PrefixEvaluatorTest {
+
+    @Test
+    public void testValidExpressions() {
+        assertEquals(10, PrefixEvaluator.evaluatePrefix("+ * 2 3 4"));
+        assertEquals(5, PrefixEvaluator.evaluatePrefix("- + 7 3 5"));
+        assertEquals(6, PrefixEvaluator.evaluatePrefix("/ * 3 2 1"));
+    }
+
+    @Test
+    public void testInvalidExpression() {
+        assertThrows(EmptyStackException.class, () -> PrefixEvaluator.evaluatePrefix("+ 3"));
+    }
+
+    @Test
+    public void testMoreThanOneStackSizeAfterEvaluation() {
+        assertThrows(IllegalArgumentException.class, () -> PrefixEvaluator.evaluatePrefix("+ 3 4 5"));
+    }
+}