Skip to content

Commit

Permalink
Updated exercise 1.3.9
Browse files Browse the repository at this point in the history
  • Loading branch information
reneargento committed May 21, 2024
1 parent 62da660 commit 5465741
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions src/chapter1/section3/Exercise9.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
/**
* Created by Rene Argento
*/
// Thanks to ru2saig (https://github.com/ru2saig) for reporting that the sqrt unary operator should be included.
// https://github.com/reneargento/algorithms-sedgewick-wayne/issues/308
public class Exercise9 {

private static String getInfixExpression(String input) {

Stack<String> operands = new Stack<>();
Stack<String> operators = new Stack<>();

Expand All @@ -21,14 +22,20 @@ private static String getInfixExpression(String input) {
} else if (value.equals("+")
|| value.equals("-")
|| value.equals("*")
|| value.equals("/")) {
|| value.equals("/")
|| value.equals("sqrt")) {
operators.push(value);
} else if (value.equals(")")) {
String subExpression;
String operator = operators.pop();
String value2 = operands.pop();
String value1 = operands.pop();

String subExpression = "( " + value1 + " " + operator + " " + value2 + " )";
if (operator.equals("sqrt")) {
subExpression = operator + " ( " + value2 + " )";
} else {
String value1 = operands.pop();
subExpression = "( " + value1 + " " + operator + " " + value2 + " )";
}
operands.push(subExpression);
} else {
operands.push(value);
Expand All @@ -37,8 +44,10 @@ private static String getInfixExpression(String input) {
return operands.pop();
}

// Parameter example: "1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )"
public static void main(String args[]) {
// Parameter examples:
// "1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )"
// "2 + 3 ) * 5 + sqrt 7.0 ) ) )"
public static void main(String[] args) {
String input = args[0];
StdOut.println(getInfixExpression(input));
}
Expand Down

0 comments on commit 5465741

Please sign in to comment.