Package lipstone.joshua.parser.util

Examples of lipstone.joshua.parser.util.ConsCell


    if (containsVariables(input))
      return ns.simplifyTerms(input);
    if (input.length() < 3) {
      if (input.getCarType() == ConsType.OPERATOR && input.getNextConsCell().getCarType() == ConsType.NUMBER) {
        if ((Character) input.getCar() == '-')
          input.getNextConsCell().replaceCar(new ConsCell(((BigDec) input.getNextConsCell().getCar()).multiply(BigDec.MINUSONE), ConsType.NUMBER));
        if ((Character) input.getCar() == '/')
          input.getNextConsCell().replaceCar(new ConsCell(BigDec.ONE.divide((BigDec) input.getNextConsCell().getCar()), ConsType.NUMBER));
        input = input.remove();
      }
      return input;
    }
    if (input.getCarType() == ConsType.OPERATOR)
      input = new ConsCell(BigDec.ZERO, ConsType.NUMBER, input, ConsType.CONS_CELL);
   
    ConsCell current = input;
    char steps[] = {'%', '%', '^', '^', '*', '/', '+', '-'};
    for (int i = 0; i < steps.length - 1; i += 2) {
      boolean forward = true;
      do {
        forward = true;
        if (current.getNextConsCell(2).isNull() || current.getNextConsCell().isNull())
          break;
        ConsCell second = current.getNextConsCell(2);
        if (current.getNextConsCell().getCarType() == ConsType.OPERATOR && (((Character) current.getNextConsCell().getCar()) == steps[i] || ((Character) current.getNextConsCell().getCar()) == steps[i + 1])) {
          char operator = (Character) current.getNextConsCell().getCar();
          boolean makeNegative = false;
          if (second.getCarType() == ConsType.OPERATOR) {
            if (((Character) second.getCar()) == '-')
              makeNegative = true;
            second.remove();
            second = current.getNextConsCell(2);
          }
          if (current.getCarType() == ConsType.NUMBER && second.getCarType() == ConsType.NUMBER) {
            BigDec num1 = (BigDec) current.getCar(), num2 = ((BigDec) second.getCar()).multiply(makeNegative ? BigDec.MINUSONE : BigDec.ONE), output = BigDec.ZERO;
            second.remove(); //num2
            current.getNextConsCell().remove(); //operator
           
            if (operator == '%')
              output = num1.mod(num2);
            else if (operator == '^') {
              while (current.getNextConsCell().getCarType() == ConsType.OPERATOR && (Character) current.getNextConsCell().getCar() == '^') {
                boolean negate = false;
                while (current.getNextConsCell(2).getCarType() == ConsType.OPERATOR) {
                  if ((Character) current.getNextConsCell(2).getCar() == '-')
                    negate = !negate;
                  current.getNextConsCell(2).remove();
                }
                if (current.getNextConsCell(2).getCarType() != ConsType.NUMBER)
                  throw new UndefinedResultException("For stacked exponents, each subsequent exponent must evaluate to a number", null);
                num2 = num2.pow(negate ? ((BigDec) current.getNextConsCell(2).getCar()).multiply(BigDec.MINUSONE) : (BigDec) current.getNextConsCell(2).getCar());
                current.getNextConsCell().remove();
                current.getNextConsCell().remove();
              }
              output = num1.pow(num2);
            }
            else if (operator == '*')
              output = num1.multiply(num2);
            else if (operator == '/')
              output = num1.divide(num2);
            else if (operator == '+')
              output = num1.add(num2);
            else if (operator == '-')
              output = num1.subtract(num2);
            else
              throw new UndefinedResultException(lastPlugin);
            current.replaceCar(new ConsCell(output, ConsType.NUMBER));
            forward = false;
          }
          else if ((current.getCarType() == ConsType.STRING || second.getCarType() == ConsType.STRING) &&
              !(current.getCarType() == ConsType.NUMBER || second.getCarType() == ConsType.NUMBER)) {
            if (operator != '+')
              throw new UndefinedResultException(lastPlugin);
            current.replaceCar(new ConsCell(current.carToString() + second.carToString(), ConsType.STRING));
            second.remove();
            current.getNextConsCell().remove();
            forward = false;
          }
          else if (current.getCarType() == ConsType.NUMBER && second.getCarType() == ConsType.STRING) {
            if (operator == '+')
              current.replaceCar(new ConsCell(current.carToString() + second.carToString(), ConsType.STRING));
            else if (operator == '*')
              current.replaceCar(new ConsCell(stringMultiplier(second.carToString(), ((BigDec) current.getCar()).intValue()), ConsType.STRING));
            else
              throw new UndefinedResultException(lastPlugin);
            second.remove();
            current.getNextConsCell().remove();
            forward = false;
          }
          else if (current.getCarType() == ConsType.STRING && second.getCarType() == ConsType.NUMBER) {
            if (operator == '+')
              current.replaceCar(new ConsCell(current.carToString() + second.carToString(), ConsType.STRING));
            else if (operator == '*')
              current.replaceCar(new ConsCell(stringMultiplier(current.carToString(), ((BigDec) second.getCar()).intValue()), ConsType.STRING));
            else
              throw new UndefinedResultException(lastPlugin);
            second.remove();
            current.getNextConsCell().remove();
            forward = false;
          }
          else if (current.getCarType() == ConsType.OBJECT && second.getCarType() == ConsType.OBJECT) {
            Matrix m1 = currentEqn.matrices.get(Integer.parseInt(((String) current.getCar()).substring(2, ((String) current.getCar()).length() - 1)));
            Matrix m2 = currentEqn.matrices.get(Integer.parseInt(((String) second.getCar()).substring(2, ((String) second.getCar()).length() - 1)));
            Matrix result = m1.matrixOp(m2, new Character(operator).toString());
            currentEqn.matrices.add(result);
            second.remove();
            current.getNextConsCell().remove();
            current.replaceCar(new ConsCell("{M" + (currentEqn.matrices.size() - 1) + "}", ConsType.OBJECT));
            forward = false;
          }
          else if (current.getCarType() == ConsType.NUMBER && second.getCarType() == ConsType.OBJECT) {
            if (operator == '/')
              throw new UndefinedOperationException(operator + " is not defined for a matrix and a scalar.", lastPlugin);
            Matrix m = currentEqn.matrices.get(Integer.parseInt(((String) current.getCar()).substring(2, ((String) current.getCar()).length() - 1)));
            Matrix result = m.scalarOp((BigDec) current.getCar(), new Character(operator).toString());
            currentEqn.matrices.add(result);
            second.remove();
            current.getNextConsCell().remove();
            current.replaceCar(new ConsCell("{M" + (currentEqn.matrices.size() - 1) + "}", ConsType.OBJECT));
            forward = false;
          }
          else if (current.getCarType() == ConsType.OBJECT && second.getCarType() == ConsType.NUMBER) {
            Matrix m = currentEqn.matrices.get(Integer.parseInt(((String) second.getCar()).substring(2, ((String) second.getCar()).length() - 1)));
            Matrix result = m.scalarOp((BigDec) second.getCar(), new Character(operator).toString());
            currentEqn.matrices.add(result);
            second.remove();
            current.getNextConsCell().remove();
            current.replaceCar(new ConsCell("{M" + (currentEqn.matrices.size() - 1) + "}", ConsType.OBJECT));
            forward = false;
          }
        }
      } while (!forward || (forward && !((current = current.getNextConsCell()).isNull()))); //This steps current forward while checking for nulls
      current = input;
View Full Code Here


   *             thrown when an error happens.
   */
  private String innerParse(String input) throws ParserException {
    try {
      isProcessing = true;
      commandQueue.push(new ConsCell("END_OF_STACK", ConsType.IDENTIFIER));
      String output = "";
      input = input.trim();
      initial = new String(input);
      ConsCell query = removeDoubles(Tokenizer.tokenizeString(input));
      vars = getVariables(query);
      if (output.equals(""))
        output = runCommands(query).toString();
      if (!output.equals(""))
        return output;
View Full Code Here

    }
  }
 
  public ConsCell runCommands(ConsCell input) throws ParserException {
    ArrayList<ConsCell> outputs = new ArrayList<ConsCell>();
    ConsCell current = input;
    do {
      if (current.getCarType() == ConsType.IDENTIFIER && commands.containsKey(current.getCar())) {
        ConsCell arguments = new ConsCell();
        String command = (String) current.getCar();
        while (!((current = current.remove()).isNull()) && !(current.getCarType() == ConsType.IDENTIFIER && commands.containsKey(current.getCar())))
          arguments = arguments.append(current.singular());
        if (commands.containsKey(current.getCar()))
          current = current.getPreviousConsCell();
        outputs.add(((CommandPlugin) commands.get(command).getPlugin()).runCommand(command, arguments.getFirstConsCell().splitOnSeparator()));
      }
    } while (!((current = current.getNextConsCell()).isNull())); //This steps current forward while checking for nulls
    ConsCell output = new ConsCell();
    ConsCell head = output;
    for (ConsCell out : outputs)
      head = head.append(out).getLastConsCell().append(new ConsCell("\n", ConsType.SEPARATOR));
    head.remove();
    return output;
  }
View Full Code Here

   *            the input that is to be processed as a String
   * @return the result of the parsed equation as a String
   */
  public ConsCell run(String equation) throws ParserException {
    equation = equation.trim();
    ConsCell input = Tokenizer.tokenizeString(equation);
    if (!isValid(input)) {
      if (equation.equals("+"))
        return new ConsCell(BigDec.ONE, ConsType.NUMBER);
      if (equation.equals("-"))
        return new ConsCell(BigDec.MINUSONE, ConsType.NUMBER);
      throw new ParserException("Invalid Input", null);
    }
    // split based on '=' here
    ArrayList<String> initVars = new ArrayList<String>(vars);
    if (!equation.contains("="))
View Full Code Here

  }
 
  public ConsCell run(ConsCell input) throws ParserException {
    if (!isValid(input)) {
      if (input.toString().equals("+"))
        return new ConsCell(BigDec.ONE, ConsType.NUMBER);
      if (input.toString().equals("-"))
        return new ConsCell(BigDec.MINUSONE, ConsType.NUMBER);
      //throw new ParserException("Invalid Input", null);
    }
    input = input.clone();
    ArrayList<String> initVars = new ArrayList<String>(vars);
    if (!input.containsIdentifier("="))
View Full Code Here

   * @return the output with all finalOperation substitutions reversed.
   */
  public ConsCell reverseFinalOperationSubstitutions(ConsCell output) {
    if (finalSubstitutions.size() == 0)
      return output;
    ConsCell current = output;
    do {
      if (current.getCarType() == ConsType.OBJECT && ((String) current.getCar()).startsWith("{FIN")) {
        int finalSub = Integer.parseInt(((String) current.getCar()).substring(4, ((String) current.getCar()).length() - 1));
        current.replaceCar(finalSubstitutions.get(finalSub));
      }
    } while (!((current = current.getNextConsCell()).isNull())); //This steps output forward while checking for nulls
    return output;
  }
View Full Code Here

    String result = output.toString();
    if (result.contains("NaN"))
      throw new UndefinedResultException("The result is not a number.", null);
    // Handles the matrix replacement for display purposes
    output = reverseFinalOperationSubstitutions(output);
    ConsCell current = output;
    do {
      if (current.getCarType() == ConsType.OBJECT && ((String) current.getCar()).startsWith("{M")) {
        int matrixNum = Integer.parseInt(((String) current.getCar()).substring(2, ((String) current.getCar()).length() - 1));
        current.replaceCar(new ConsCell(currentEqn.matrices.get(matrixNum).toString(), ConsType.OBJECT));
      }
    } while (!((current = current.getNextConsCell()).isNull())); //This steps output forward while checking for nulls
    finalSubstitutions.clear();
    output = ns.removeExcessParentheses(output);
    for (OutputFilterPlugin plugin : postProcessFilters)
      output = plugin.postProcess(output);
    result = output.toString();
View Full Code Here

    if (parts.size() > 2)
      throw new UndefinedResultException("Incorrectly formatted equation.  Please use only 2-sided equalities.", null);
    if (parts.size() > 1) {
      if (parser.getVars().size() == 0 || !parser.containsVariables(input, parser.getVars())) {
        if (new BigDec(parser.run(parts.get(0)).carToString()).eq(new BigDec(parser.run(parts.get(1)).carToString())))
          return new ConsCell("true", ConsType.IDENTIFIER);
        else
          return new ConsCell("false", ConsType.IDENTIFIER);
      }
      input = parts.get(0).getLastConsCell().append(invertSign(parts.get(1))).getFirstConsCell();
    }
    try {
      initialInput.push(input.clone());
      ArrayList<BigDec> solutionsList = solve(input, true, true);
     
      ConsCell solutions = new ConsCell();
      for (BigDec d : solutionsList)
        solutions = solutions.append(new ConsCell(",", ConsType.SEPARATOR, new ConsCell(d, ConsType.NUMBER)));
      if (!solutions.isNull())
        solutions = solutions.getFirstConsCell().remove();
      else
        solutions = new ConsCell("no solution in", ConsType.IDENTIFIER, Tokenizer.tokenizeString("(" + domainMin + ", " + domainMax + ")"));
      return solutions;
    }
    finally {
      initialInput.pop();
    }
View Full Code Here

   
    BigDec modifier = null;
    BigDec[] form = new BigDec[]{BigDec.ONE, BigDec.ZERO};
    if ((modifier = matchesForm(orders, highestOrder, form)) != null) { //Linear
      if (linearEquation == null) { //Initialize the linear equation structure.  This makes subsequent calls faster.
        linearEquationHooks[0] = new ConsCell("a", ConsType.IDENTIFIER);
        linearEquationHooks[1] = new ConsCell("b", ConsType.IDENTIFIER, new ConsCell('/', ConsType.OPERATOR, linearEquationHooks[0]));
        linearEquation = new ConsCell('-', ConsType.OPERATOR, linearEquationHooks[1]);
      }
     
      BigDec a = BigDec.ZERO, b = BigDec.ZERO;
     
      form[0] = form[0].subtract(modifier);
      form[1] = form[1].subtract(modifier);
      for (ConsCell term : orders) {
        BigDec order = orders.get(term);
        if (order.eq(form[1]))
          b = b.add(getCoefficient(term));
        else
          a = a.add(getCoefficient(term));
      }
     
      linearEquationHooks[0].replaceCar(new ConsCell(a, ConsType.NUMBER));
      linearEquationHooks[1].replaceCar(new ConsCell(b, ConsType.NUMBER));
      solutions.add(new BigDec(parser.run(linearEquation.clone()).toString()));
    }
   
    if (solutions.size() == 0 && (modifier = matchesForm(orders, highestOrder, (form = new BigDec[]{new BigDec(2), BigDec.ONE, BigDec.ZERO}))) != null) { //Quadratic
      if (quadraticEquation == null) { //Initialize the quadratic equation structure.  This makes subsequent calls faster.
        quadraticEquation = Tokenizer.tokenizeString("(-b\"+-\"(b^2-4*a*c)^0.5)/(2*a)");
        quadraticEquationHooks[0] = quadraticEquation.allInstancesOf(new ConsCell("a", ConsType.IDENTIFIER));
        quadraticEquationHooks[1] = quadraticEquation.allInstancesOf(new ConsCell("b", ConsType.IDENTIFIER));
        quadraticEquationHooks[2] = quadraticEquation.allInstancesOf(new ConsCell("c", ConsType.IDENTIFIER));
        quadraticEquationHooks[3] = quadraticEquation.allInstancesOf(new ConsCell("+-", ConsType.STRING));
      }
     
      BigDec a = BigDec.ZERO, b = BigDec.ZERO, c = BigDec.ZERO;
     
      form[0] = form[0].subtract(modifier);
      form[1] = form[1].subtract(modifier);
      form[2] = form[2].subtract(modifier);
      for (ConsCell term : orders) {
        BigDec order = orders.get(term);
        if (order.eq(form[2]))
          c = c.add(getCoefficient(term));
        else if (order.eq(form[1]))
          b = b.add(getCoefficient(term));
        else
          a = a.add(getCoefficient(term));
      }
     
      for (ConsCell cell : quadraticEquationHooks[0])
        cell.replaceCar(new ConsCell(a, ConsType.NUMBER)); //a
      for (ConsCell cell : quadraticEquationHooks[1])
        cell.replaceCar(new ConsCell(b, ConsType.NUMBER)); //b
      quadraticEquationHooks[2].get(0).replaceCar(new ConsCell(c, ConsType.NUMBER)); //c
     
      quadraticEquationHooks[3].get(0).replaceCar(new ConsCell('+', ConsType.OPERATOR)); //+
      solutions.add(new BigDec(parser.run(quadraticEquation.clone()).toString()));
      quadraticEquationHooks[3].get(0).replaceCar(new ConsCell('-', ConsType.OPERATOR)); //-
      solutions.add(new BigDec(parser.run(quadraticEquation.clone()).toString()));
    }
    return checkSolutions(solutions, equation, accuracy);
  }
View Full Code Here

   *            the equation to factor
   * @return the factored form of the equation if possible, otherwise it returns the original.
   * @throws ParserException
   */
  public ConsCell factoring(ConsCell equation) throws ParserException {
    ConsCell output = removeExcessParentheses(rationalRootsFactoring(equation));
    if (!output.equals(equation))
      return output;
    return equation;
  }
View Full Code Here

TOP

Related Classes of lipstone.joshua.parser.util.ConsCell

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.