You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
projectone/src/MiddleSchoolProblemGenerato...

69 lines
3.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import java.text.DecimalFormat;
import java.util.Random;
public class MiddleSchoolProblemGenerator extends AbstractProblemGenerator {
public MiddleSchoolProblemGenerator(Random random, DecimalFormat df) {
super(random, df);
}
@Override
public MathProblem generate() {
int operandCount = random.nextInt(3) + 3; // 3-5 个操作数
int[] operands = new int[operandCount];
String[] selectedOperators = new String[operandCount - 1];
String[] displayOperands = new String[operandCount];
String[] operatorPool = {"+", "-", "*", "/"};
for (int i = 0; i < operandCount; i++) {
operands[i] = random.nextInt(100) + 1;
displayOperands[i] = String.valueOf(operands[i]);
}
for (int i = 0; i < operandCount - 1; i++) {
selectedOperators[i] = operatorPool[random.nextInt(operatorPool.length)];
}
// 平方或根号
int specialOperandIndex = random.nextInt(operandCount);
boolean useSquareRoot = random.nextBoolean();
if (useSquareRoot) {
int base = random.nextInt(24) + 2; //2-25
int perfectSquare = base * base;
operands[specialOperandIndex] = base; // √(base^2) = base
displayOperands[specialOperandIndex] = "√" + perfectSquare;
} else {
int base = random.nextInt(9) + 2; // 2-10
int square = base * base;
operands[specialOperandIndex] = square;
displayOperands[specialOperandIndex] = base + "²";
}
// 括号选择
boolean addedBracket = false;
int bracketStartIndex = findBracketStart(toDoubleArray(operands), selectedOperators, 0.3);
String expression;
double result;
if (bracketStartIndex != -1) {
// 构建带括号(显示用 displayOperands
StringBuilder expressionBuilder = new StringBuilder();
for (int i = 0; i < operandCount; i++) {
if (i == bracketStartIndex) expressionBuilder.append("(");
expressionBuilder.append(displayOperands[i]);
if (i == bracketStartIndex + 1) expressionBuilder.append(")");
if (i < operandCount - 1) expressionBuilder.append(" ").append(selectedOperators[i]).append(" ");
}
expression = expressionBuilder.toString();
result = evaluateExpressionWithBrackets(operands, selectedOperators, bracketStartIndex);
} else {
StringBuilder expressionBuilder = new StringBuilder();
expressionBuilder.append(displayOperands[0]);
result = operands[0];
for (int i = 0; i < operandCount - 1; i++) {
expressionBuilder.append(" ").append(selectedOperators[i]).append(" ").append(displayOperands[i + 1]);
result = applyOperator(result, operands[i + 1], selectedOperators[i]);
}
expression = expressionBuilder.toString();
}
return new MathProblem(expression, df.format(result), "初中");
}
}