For my program I need to generate valid infix expressions with customizable complexity. The problem is that I cant figure out a way to prevent division by zero, floating point answers and negative answers.
To prevent negative answers, I'm taking a dirty approach. That is, generate an expression, evaluate it, if it turns out to be negative, generate again.Here are some things you should know:
How can I make sure that a) there are no divisions by zero b) no divisions result in floating point (figured out a dirty way to do this) c) final result is not negative Here is the code
public void generateRandom(int operandLimit, int operatorCount, int complexityLevel) {
Random rand = new Random();
infix.clear();
int i = 0;
infix.add( rand.nextInt(operandLimit) + 1 );
while(i < operatorCount) {
int operator;
if(complexityLevel <= DIVIDE)
operator = rand.nextInt(complexityLevel - 1)*1000 + 1000;
else
operator = rand.nextInt(complexityLevel - 3)*1000 + 1000;
int operand = rand.nextInt(operandLimit) + 1;
if( operator == Operator.DIVIDE ) {
int lastNum = infix.get(infix.size() - 1);
if( lastNum < operand) {
int temp = operand;
operand = lastNum;
lastNum = temp;
}
lastNum -= lastNum % operand;
infix.set(infix.size() - 1, lastNum);
}
infix.add( operator );
infix.add( operand );
++i;
}
if(complexityLevel == ARITMETIC_PARENTHESIS) {
int braceOpen = rand.nextInt( operatorCount ) * 2;
infix.add(braceOpen, Operator.BR_OPEN );
infix.add(braceOpen + 4, Operator.BR_CLOSE);
}
inToPost();
if(evaluate() < 0)
generateRandom(operandLimit, operatorCount, complexityLevel);
}
It looks like you've dealt with your conditions (b) and (c) already. Since your operands are never 0, I would guess that the only possible violation of (a) is if the added parentheses happen to wrap a zero value, and the operator before that is a division. You could check for that case if you modified your inToPost()
to take subexpressions:
if(braceOpen > 0 && infix.get(braceOpen) == Operator.DIVISION &&
evaluate(inToPost(infix.subList(braceOpen, braceOpen + 3))) == 0) {
// Put parentheses elsewhere, or cancel
}