Repository: TheAlgorithms/Java
Pull request #5401 (2024-08-26 13:10:16)

refactor: `InfixToPostfix`
Refactor InfixToPostfix
Added tests.

BalancedBrackets.isBalanced works only with "(){}[]<>", to use it need to remove other characters and check.

<!--
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/5401?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 48.18%. Comparing base [(`b70f077`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/b70f077343a4629cf163400f1d64993c6ab2bbf7?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`892a4b8`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/892a4b8ce28c494d99f107e52cac9af7cb9264cc?dropdown=coverage&el=desc&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    #5401      +/-   ##
============================================
+ Coverage     48.02%   48.18%   +0.16%     
- Complexity     2962     2977      +15     
============================================
  Files           524      524              
  Lines         15275    15273       -2     
  Branches       2903     2901       -2     
============================================
+ Hits           7336     7360      +24     
+ Misses         7637     7609      -28     
- Partials        302      304       +2     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5401?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/src/main/java/com/thealgorithms/stacks/InfixToPostfix.java b/src/main/java/com/thealgorithms/stacks/InfixToPostfix.java
index e3519978..33611bd7 100644
--- a/src/main/java/com/thealgorithms/stacks/InfixToPostfix.java
+++ b/src/main/java/com/thealgorithms/stacks/InfixToPostfix.java
@@ -1,19 +1,15 @@
 package com.thealgorithms.stacks;
 
 import java.util.Stack;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 public final class InfixToPostfix {
     private InfixToPostfix() {
     }
 
-    public static void main(String[] args) throws Exception {
-        assert "32+".equals(infix2PostFix("3+2"));
-        assert "123++".equals(infix2PostFix("1+(2+3)"));
-        assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6"));
-    }
-
     public static String infix2PostFix(String infixExpression) throws Exception {
-        if (!BalancedBrackets.isBalanced(infixExpression)) {
+        if (!BalancedBrackets.isBalanced(filterBrackets(infixExpression))) {
             throw new Exception("invalid expression");
         }
         StringBuilder output = new StringBuilder();
@@ -55,4 +51,10 @@ public final class InfixToPostfix {
             return -1;
         }
     }
+
+    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/InfixToPostfixTest.java b/src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java
new file mode 100644
index 00000000..02a08e39
--- /dev/null
+++ b/src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java
@@ -0,0 +1,33 @@
+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.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+class InfixToPostfixTest {
+
+    @ParameterizedTest
+    @MethodSource("provideValidExpressions")
+    void testValidExpressions(String infix, String expectedPostfix) throws Exception {
+        assertEquals(expectedPostfix, InfixToPostfix.infix2PostFix(infix));
+    }
+
+    private static Stream<Arguments> provideValidExpressions() {
+        return Stream.of(Arguments.of("3+2", "32+"), Arguments.of("1+(2+3)", "123++"), Arguments.of("(3+4)*5-6", "34+5*6-"));
+    }
+
+    @ParameterizedTest
+    @MethodSource("provideInvalidExpressions")
+    void testInvalidExpressions(String infix, String expectedMessage) {
+        Exception exception = assertThrows(Exception.class, () -> InfixToPostfix.infix2PostFix(infix));
+        assertEquals(expectedMessage, exception.getMessage());
+    }
+
+    private static Stream<Arguments> provideInvalidExpressions() {
+        return Stream.of(Arguments.of("((a+b)*c-d", "invalid expression"));
+    }
+}