LindaLiu1202 / spring_portfolio

0 stars 0 forks source link

FRQ3 - Array/ArrayList #4

Open LindaLiu1202 opened 1 year ago

LindaLiu1202 commented 1 year ago

Hacks

Finish rpnToResult for Calculator

// Takes RPN and produces a final result
    private void rpnToResult()
    {
        // stack is used to hold operands and each calculation
        Stack<Double> calcStack = new Stack<Double>();

        // RPN is processed, ultimately calcStack has final result
        for (String token : this.reverse_polish)
        {
            // If the token is an operator, calculate
            if (isOperator(token))
            {
                // Pop the two top entries
                double e1 = calcStack.pop();
                double e2 = calcStack.pop();
                // Calculate intermediate results
                switch (token) {
                    case "+":
                        result = e2 + e1;
                        break;
                    case "-":
                        result = e2 - e1;
                        break;
                    case "*":
                        result = e2 * e1;
                        break; 
                    case "/":
                        result = e2 / e1;
                        break;
                    case "%":
                        result = e2 % e1;
                        break;
                    default:
                        break;
                }

                // Push intermediate result back onto the stack
                calcStack.push( result );
            }
            // else the token is a number push it onto the stack
            else
            {
                calcStack.push(Double.valueOf(token));
            }
        }
        // Pop final result and set as final result for expression
        this.result = calcStack.pop();
    }

.pop() - returns the element present at the top of the stack and then removes it .peek() - returns the element at the top of the Stack else returns NULL if the Stack is empty During calculation algorithm will work through RPN, Left to Right. 1. go to first operator, 2. obtain to the amount of operands required for operator, 3. solve, 4. push result

Add unbalanced parenthesis check and in original FRQ, or other error checks. FYI, usually when structuring code with error checking it can greatly impact code structure.

image

FRQ isBalanced method (from an ArrayList)

public boolean isBalanced(ArrayList<String> delimiters){
        int countOpen=0;
        int countClose=0; 
        for (int i=0; i<delimiters.size(); i++){ 
            if (delimiters.get(i).equals(openDel)){  //.get(i) - ArrayList
               countOpen++;
            }
            else {
               countClose++;
            }           
            if(countClose > countOpen)
                return false;
        }
        return countOpen == countClose;
    }
}

difference between looping through every character in String and every item in ArrayList

String  str
for(int i=0; i<str.length(); i++)
    str.substring(i,i+1)       // get every character in String 
 01234
"Linda".substring(0,1)    
.substring(start , end)  from start to end-1  

ArrayList  list 
for(int i=0; i<list.size(); i++) 
     list.get(i)          // get every item in the ArrayList         

for array

Array    arr
for(int i=0; i<arr.length; i++)
     arr[i]             //  get every element in the array

Build in Power of operator ^:2 ^ 1 = 2, 2 ^ 2 = 4, 2 ^ 3 = 83. Build an API to receive an expression and respond with a result. This is a good opportunity to respond with an error if you built in parenthesis or other error checking.

    // Helper definition for supported operators
    private final Map<String, Integer> OPERATORS = new HashMap<>();
    {
        // Map<"token", precedence>
        OPERATORS.put("^", 2);
        OPERATORS.put("*", 3);
        OPERATORS.put("/", 3);
        OPERATORS.put("%", 3);
        OPERATORS.put("+", 4);
        OPERATORS.put("-", 4);
    }

the order of precedence rules, aka PEMDAS (parenthesis, exponents, multiplication, division, addition, subtraction) need to be factored into order of computation

testing if power is precedent

 Calculator powerMath = new Calculator("1 + 10^2");
        System.out.println("Power Math\n" + powerMath);
image

tokensToReversePolishNotation ()

image

rpnToResult()

image

pow() - return the value of first argument raised to the power of the second argument return type of pow() method is double

Build an API to receive an expression and respond with a result.

@RestController
@RequestMapping("/api/calculator")
public class CalculatorApiController {

    @GetMapping("{expression}")
    public ResponseEntity<String> getExpression(@PathVariable String expression) throws JsonMappingException, JsonProcessingException {
      // test Object
      Calculator test = new Calculator(expression);

      return ResponseEntity.ok(test.toString());  // JSON response, see ExceptionHandlerAdvice for throws
    }

}

Tester

    // Tester method
    public static void main(String[] args) {
        // Random set of test cases
        Calculator simpleMath = new Calculator("100 + 200  * 3");
        System.out.println("Simple Math\n" + simpleMath);

        System.out.println();

        Calculator parenthesisMath = new Calculator("(100 + 200)  * 3");
        System.out.println("Parenthesis Math\n" + parenthesisMath);

        System.out.println();

        Calculator decimalMath = new Calculator("100.2 - 99.3");
        System.out.println("Decimal Math\n" + decimalMath);

        System.out.println();

        Calculator moduloMath = new Calculator("300 % 200");
        System.out.println("Modulo Math\n" + moduloMath);

        System.out.println();

        Calculator divisionMath = new Calculator("300/200");
        System.out.println("Division Math\n" + divisionMath);

        System.out.println();

        Calculator powerMath = new Calculator("10^2");
        System.out.println("Power Math\n" + powerMath);

    }
}

Output

image

Testing using Postman Simple Math

image

Demonstrating Order of Precedence

multiplication have precedence over addition

image

Basic Skill building, do FRQ3. FYI, isBalanced could help in error corrections for Calculator.

import java.util.ArrayList;

public class Delimiters {
     //  part1   private instances variables          global variables 
    private String openDel;
    private String closeDel;

     //   part2    constructors     
    public Delimiters(String open, String close)
    {
        openDel=open;    
        closeDel=close;
    }

     //   part3    non-constructor methods     normal methods 
    public ArrayList<String> getDelimitersList(String[] tokens){
        //     ArrayList<DataType> ListName = new ArrayList<DataType>();
                 ArrayList<String> delimiters = new ArrayList<String>();                 
                   for(int i=0; i<tokens.length; i++){
                         if(tokens[i].equals(openDel) || tokens[i].equals(closeDel)){
                              delimiters.add(tokens[i]);
                         }
                   }
            return delimiters;       
    }

    public boolean isBalanced(ArrayList<String> delimiters){
        int countOpen=0;
        int countClose=0; 
        for (int i=0; i<delimiters.size(); i++){ 
            if (delimiters.get(i).equals(openDel)){
               countOpen++;
            }
            else {
               countClose++;
            }           
            if(countClose > countOpen)
                return false;
        }
        return countOpen == countClose;
    }
}
ellenjxu commented 1 year ago

Score: 2.8/3.0

Extra work done for completing FRQ 3, demonstrated knowledge with .substring, .get, and applying it into the Hacks. Also had additional notes and understanding. Points off for divide/power not working in API/Postman, but working in tester (which was a common problem with parsing/POST).