diff --git a/src/chapter1/section3/Exercise9.java b/src/chapter1/section3/Exercise9.java index 7a4f312..8efcda4 100644 --- a/src/chapter1/section3/Exercise9.java +++ b/src/chapter1/section3/Exercise9.java @@ -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 operands = new Stack<>(); Stack operators = new Stack<>(); @@ -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); @@ -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)); }