Search in sources :

Example 6 with Node

use of expression.Node in project OpenNotebook by jaltekruse.

the class ExUtil method generateRandomExpressions.

public static String[] generateRandomExpressions() {
    String[] ops = { ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION };
    String[] vars = { "x", "y", "z", "a", "b", "c", "d", "s", "t", "w", "v", "m", "n", "j", "k", "l" };
    int numTrials = 10;
    String[] expressions = new String[numTrials];
    int numZeros = 0;
    int numNegatives = 0;
    int minNumOps = 2;
    int maxNumOps = 5;
    int maxAbsVal = 20;
    int minGeneratedVal = 1;
    int maxGeneratedVal = 10;
    int numOps;
    for (int j = 0; j < numTrials; j++) {
        numOps = randomInt(minNumOps, maxNumOps, false);
        Node n = randomExpression(ops, vars, numOps, maxAbsVal, minGeneratedVal, maxGeneratedVal, true, false, false, true);
        try {
            expressions[j] = n.toStringRepresentation();
            if (((Number) n.numericSimplify()).getValue() == 0) {
                numZeros++;
            }
            if (((Number) n.numericSimplify()).getValue() < 0) {
                numNegatives++;
            }
        } catch (NodeException e) {
            e.printStackTrace();
        }
    }
    // System.out.println(numNegatives + " out of " + numTrials + " trials evaluated to a negative.");
    return expressions;
}
Also used : Node(expression.Node) NodeException(expression.NodeException)

Example 7 with Node

use of expression.Node in project OpenNotebook by jaltekruse.

the class ExUtil method randomlyAddParenthesis.

/**
 * Randomly adds parenthesis to an expression composed of additions or multiplications.
 * The result of the operation does not change, due to the Associative property of both of
 * the operators, but this method is useful for creating exercises to teach those concepts.
 *
 * @param ex - the expression
 * @param minNumParens - the minimum number of parenthesis to add
 * @param maxNumParens - the maximum number of parenthesis to add
 * @return - the modified expression
 */
public static Node randomlyAddParenthesis(Expression ex, int minNumParens, int maxNumParens) {
    Vector<Node> terms = new Vector<>();
    if (ex.getOperator() instanceof Operator.Addition) {
        terms = ex.splitOnAddition();
        int numParensToAdd = randomInt(minNumParens, maxNumParens, true);
        int unusedTermsLeft = terms.size();
        int tempIndex;
        Expression tempEx;
        while (unusedTermsLeft > 2 && numParensToAdd > 0) {
            // use size - 2 because a term and it's successive term will be used to
            // create a new expression with parenthesis
            tempIndex = randomInt(0, terms.size() - 2, false);
            // remove from the same index twice, because everything is shifted with the
            // first move
            tempEx = new Expression(new Operator.Addition(), terms.remove(tempIndex), terms.remove(tempIndex));
            tempEx.setDisplayParentheses(true);
            terms.add(tempEx);
            unusedTermsLeft--;
            numParensToAdd--;
        }
        return Expression.staggerAddition(terms);
    } else if (ex.getOperator() instanceof Operator.Multiplication) {
        terms = ex.splitOnMultiplication();
        int numParensToAdd = randomInt(minNumParens, maxNumParens, true);
        int unusedTermsLeft = terms.size();
        int tempIndex;
        Expression tempEx;
        while (unusedTermsLeft > 2 && numParensToAdd > 0) {
            tempIndex = randomInt(0, terms.size() - 2, false);
            tempEx = new Expression(new Operator.Multiplication(), terms.remove(tempIndex), terms.remove(tempIndex));
            tempEx.setDisplayParentheses(true);
            terms.add(tempEx);
            unusedTermsLeft--;
            numParensToAdd--;
        }
        return Expression.staggerMultiplication(terms);
    }
    return ex;
}
Also used : Operator(expression.Operator) Expression(expression.Expression) Node(expression.Node) Vector(java.util.Vector)

Example 8 with Node

use of expression.Node in project OpenNotebook by jaltekruse.

the class ExUtil method addRandomOp.

public static Node addRandomOp(Node n, String[] ops, String[] vars, int min, int max, double maxAbsVal, boolean excludeZero, boolean subtractNegatives, boolean addNegatives) {
    int opIndex = rand.nextInt(ops.length);
    String opCode = ops[opIndex];
    Node newChild = new Number(randomInt(min, max, excludeZero));
    Operator op = null;
    Number newNum;
    Expression newEx;
    double expressionVal = 0;
    boolean numberTooBig = false;
    try {
        // System.out.println(n.toStringRepresentation());
        expressionVal = ((Number) n.numericSimplify()).getValue();
    } catch (NodeException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    if (Math.abs(expressionVal) > maxAbsVal) {
        numberTooBig = true;
    }
    if (opCode.equals(DIVISION)) {
        op = new Operator.Division();
        newEx = new Expression(op);
        if (!(newChild instanceof Number)) {
            // to keep the answer clean
            return addNodeOnRandomSide(n, newChild, op);
        } else if (expressionVal == 0) {
            newNum = (Number) newChild;
            do {
                newChild = new Number(randomInt(min, max, excludeZero));
            } while (newNum.getValue() == 0);
            return new Expression(op, n, newChild);
        } else if (isPrime(expressionVal) || (rand.nextBoolean() && !numberTooBig)) {
            // or the expression was randomly selected to be the divisor when it wasn't prime
            return addRandomOp(n, ops, vars, min, max, maxAbsVal, excludeZero, subtractNegatives, addNegatives);
        // had problem with these next two lines, gave up for now and just adding another operation
        // newChild = new Number( expressionVal * randomInt(min, max, excludeZero));
        // return new Expression(op, newChild, n);
        } else {
            // need to find a divisor
            if (numberTooBig) {
                return addRandomOp(n, ops, vars, min, max, maxAbsVal, excludeZero, subtractNegatives, addNegatives);
            }
            double[] factors = getFactors(expressionVal);
            int factorIndex = rand.nextInt(factors.length);
            newChild = new Number(factors[factorIndex]);
            return new Expression(op, n, newChild);
        }
    } else if (opCode.equals(ADDITION)) {
        op = new Operator.Addition();
        if (!(newChild instanceof Number)) {
            // to keep the answer clean
            return addNodeOnRandomSide(n, newChild, op);
        }
        if (!addNegatives) {
            if (max < 0) {
            // the settings contradict one another, the user wanted only negative numbers generated
            // do nothing
            } else {
                // the minimum is below zero, so exclude those values between 0 and the minimum while finding a new number
                int tempMin = 0;
                newNum = (Number) newChild;
                if (min > 0)
                    tempMin = min;
                while (newNum.getValue() < 0) {
                    newNum = new Number(randomInt(tempMin, max, excludeZero));
                }
            }
        }
    } else if (opCode.equals(SUBTRACTION)) {
        op = new Operator.Subtraction();
        if (!(newChild instanceof Number)) {
            // to keep the answer clean
            if (n instanceof Expression && ((Expression) n).getOperator() instanceof Operator.Negation) {
                // MIGHT CAUSE INFINITE RECURSION, BE CAREFUL
                return addRandomOp(n, ops, vars, min, max, maxAbsVal, excludeZero, subtractNegatives, addNegatives);
            }
            return addNodeOnRandomSide(n, newChild, op);
        }
        if (!subtractNegatives) {
            // negative numbers are not supposed to be subtracted, generate new positive number
            if (max < 0) {
            // the settings contradict one another, the user wanted only negative numbers generated
            // do nothing, ignore the value of subtractNegatives
            } else {
                // the minimum is below zero, so exclude those values between 0 and the minimum while finding a new number
                int tempMin = 0;
                newNum = (Number) newChild;
                if (min > 0)
                    tempMin = min;
                while (newNum.getValue() < 0) {
                    newNum = new Number(randomInt(tempMin, max, excludeZero));
                }
            }
        }
    } else if (opCode.equals(MULTIPLICATION)) {
        op = new Operator.Multiplication();
        newEx = new Expression(op);
        if (!(newChild instanceof Number)) {
            // to keep the answer clean
            return addNodeOnRandomSide(n, newChild, op);
        }
    } else if (opCode.equals(NEGATION)) {
        if (n instanceof Expression && ((Expression) n).getOperator() instanceof Operator.Negation || (n instanceof Number && ((Number) n).getValue() < 0)) {
            // THIS WILL CAUSE INFINITE RECURSION IF THE ONLY OPERATOR IS NEGATION!!
            return addRandomOp(n, ops, vars, min, max, maxAbsVal, excludeZero, subtractNegatives, addNegatives);
        }
        return new Expression(new Operator.Negation(), true, n);
    } else {
        throw new RuntimeException("unknown op");
    }
    return addNodeOnRandomSide(n, newChild, op);
}
Also used : Operator(expression.Operator) Node(expression.Node) NodeException(expression.NodeException) Number(expression.Number) Expression(expression.Expression)

Example 9 with Node

use of expression.Node in project OpenNotebook by jaltekruse.

the class PropertyOfOppositiesWithVariables method generateExpression.

@Override
protected Node[] generateExpression(int difficulty) throws NodeException {
    Node[] n = new Node[2];
    if (difficulty == ProblemGenerator.EASY) {
        double num = ExUtil.randomInt(2, 9, true);
        n[0] = ExUtil.randomlyStaggerOperation(new Operator.Addition(), new Number(num), ExUtil.randomTerm(1, ExUtil.randomVarName(), 3, 12), new Number(-1 * num), new Number(ExUtil.randomInt(2, 9, true)));
    } else if (difficulty == ProblemGenerator.MEDIUM) {
        double[] numPair = ExUtil.pairOfCleanAddingNumbers(100);
        Node var = ExUtil.randomTerm(1, ExUtil.randomVarName(), 3, 12);
        n[0] = ExUtil.randomlyStaggerOperation(new Operator.Addition(), new Number(ExUtil.randomInt(2, 9, true)), var, new Number(ExUtil.randomInt(2, 9, true)), new Expression(new Operator.Negation(), var));
    } else if (difficulty == ProblemGenerator.HARD) {
        double[] numPair2 = ExUtil.pairOfCleanAddingNumbers(200);
        Vector<String> varNames = ExUtil.randomUniqueVarNames(2);
        Node var = ExUtil.randomTerm(1, ExUtil.randomVarName(), 3, 12);
        n[0] = ExUtil.randomlyStaggerOperation(new Operator.Addition(), new Number(ExUtil.randomInt(2, 9, true)), ExUtil.randomTerm(1, varNames.get(1), 3, 12), new Number(numPair2[0]), var, new Number(numPair2[0]), new Expression(new Operator.Negation(), var));
    }
    n[0] = ExUtil.randomlyAddParenthesis((Expression) n[0], 0, 3);
    n[1] = n[0].collectLikeTerms().smartNumericSimplify().standardFormat();
    return n;
}
Also used : Operator(expression.Operator) Node(expression.Node) Number(expression.Number) Expression(expression.Expression)

Example 10 with Node

use of expression.Node in project OpenNotebook by jaltekruse.

the class VariableValueInsertionProblem method generateProblem.

public GeneratedProblem generateProblem(int difficulty) {
    Grouping newProblem = new Grouping(getParentContainer(), getxPos(), getyPos() + getHeight() + bufferSpace, getWidth(), getHeight());
    String s;
    Node n = null;
    Vector<String> varNames = new Vector<>();
    Vector<Number> varVals = new Vector<>();
    for (StringAttribute strAtt : (Vector<StringAttribute>) getScripts().getValues()) {
        s = strAtt.getValue();
        if (s == null || s.equals("")) {
            continue;
        }
        try {
            n = Node.parseNode(s);
            // sub in variables already assigned in previous scripts
            for (int i = 0; i < varNames.size(); i++) {
                n = n.replace(varNames.get(i), varVals.get(i));
            }
            n = n.numericSimplify();
            if (n instanceof Expression) {
                Expression ex = (Expression) n;
                if (ex.getOperator() instanceof Operator.Equals) {
                    if (ex.getChild(0) instanceof Identifier) {
                        Identifier var = (Identifier) ex.getChild(0);
                        if (ex.getChild(1) instanceof Number) {
                            varNames.add(var.getIdentifier());
                            // this causes a lot of unneeded parenthesis
                            // but without it, you cannot sub in a value
                            // where there is an implied parenthesis
                            // ex.getChild(1).setDisplayParentheses(true);
                            varVals.add((Number) ex.getChild(1));
                        }
                    }
                }
            }
        } catch (NodeException e) {
            JOptionPane.showMessageDialog(null, "Error generating a problem, check scripts.", ERROR, JOptionPane.ERROR_MESSAGE);
        }
    }
    MathObject newObj = null;
    for (MathObject mObj : getObjects()) {
        newObj = mObj.clone();
        for (int i = 0; i < varNames.size(); i++) {
            newObj = subInVal(varNames.get(i), varVals.get(i), newObj);
        }
        // shift object down so it doesn't overlap the current problem
        newObj.setyPos(newObj.getyPos() + getHeight() + bufferSpace);
        // this line sets the bounds to the actual space it takes to render them
        if (getParentContainer() != null) {
            // if this problem formula is in the background storage for a document
            getParentDoc().getDocViewerPanel().drawObjectInBackground(newObj);
        } else {
            // if this problem formula is actually on a document
            getProblemHoldingDocument().getDocViewerPanel().drawObjectInBackground(newObj);
        }
        newObj.setParentContainer(newProblem.getParentContainer());
        newProblem.addObjectFromPage(newObj);
    }
    return new GeneratedProblem(newProblem.getParentContainer(), this.getProblemID(), newProblem);
}
Also used : Node(expression.Node) StringAttribute(doc.attributes.StringAttribute) NodeException(expression.NodeException) Identifier(expression.Identifier) Number(expression.Number) Expression(expression.Expression) Vector(java.util.Vector)

Aggregations

Node (expression.Node)29 Expression (expression.Expression)10 NodeException (expression.NodeException)10 Number (expression.Number)9 Operator (expression.Operator)7 Vector (java.util.Vector)6 StringAttribute (doc.attributes.StringAttribute)4 AttributeException (doc.attributes.AttributeException)3 Identifier (expression.Identifier)2 BasicStroke (java.awt.BasicStroke)2 Graphics2D (java.awt.Graphics2D)2 Point (java.awt.Point)2 RootNodeGraphic (math_rendering.RootNodeGraphic)2 ListAttribute (doc.attributes.ListAttribute)1 ExpressionObject (doc.mathobjects.ExpressionObject)1 GeneratedProblem (doc.mathobjects.GeneratedProblem)1 Multiplication (expression.Operator.Multiplication)1 Color (java.awt.Color)1 Cursor (math_rendering.Cursor)1