|
|
|
@ -7,32 +7,53 @@ import java.util.Random;
|
|
|
|
|
public class PrimaryQuestionGenerator implements QuestionGenerator {
|
|
|
|
|
@Override
|
|
|
|
|
public String generateQuestion(StringBuilder question, Random random) {
|
|
|
|
|
int num1 = random.nextInt(100) + 1; // 1-100的随机数
|
|
|
|
|
int num2 = random.nextInt(100) + 1;
|
|
|
|
|
// 随机生成1-5个操作数
|
|
|
|
|
int operandCount = random.nextInt(5) + 1;
|
|
|
|
|
String[] operators = {"+", "-", "*", "/"};
|
|
|
|
|
String op = operators[random.nextInt(operators.length)];
|
|
|
|
|
int[] operands = new int[operandCount];
|
|
|
|
|
String[] chosenOperators = new String[operandCount - 1];
|
|
|
|
|
|
|
|
|
|
// 确保减法和除法结果为正整数
|
|
|
|
|
if ("-".equals(op) && num1 < num2) {
|
|
|
|
|
int temp = num1;
|
|
|
|
|
num1 = num2;
|
|
|
|
|
num2 = temp;
|
|
|
|
|
} else if ("/".equals(op)) {
|
|
|
|
|
// 生成第一个操作数
|
|
|
|
|
operands[0] = random.nextInt(100) + 1; // 1-100的随机数
|
|
|
|
|
question.append(operands[0]);
|
|
|
|
|
|
|
|
|
|
// 生成剩余的操作数和运算符
|
|
|
|
|
for (int i = 1; i < operandCount; i++) {
|
|
|
|
|
chosenOperators[i-1] = operators[random.nextInt(operators.length)];
|
|
|
|
|
operands[i] = random.nextInt(100) + 1;
|
|
|
|
|
|
|
|
|
|
// 确保减法结果非负
|
|
|
|
|
if ("-".equals(chosenOperators[i-1]) && operands[i-1] < operands[i]) {
|
|
|
|
|
// 如果当前操作数小于下一个操作数,交换它们
|
|
|
|
|
int temp = operands[i-1];
|
|
|
|
|
operands[i-1] = operands[i];
|
|
|
|
|
operands[i] = temp;
|
|
|
|
|
// 更新已添加到问题中的数值
|
|
|
|
|
question.setLength(0);
|
|
|
|
|
question.append(operands[0]);
|
|
|
|
|
for (int j = 1; j < i; j++) {
|
|
|
|
|
question.append(" " + chosenOperators[j-1] + " " + operands[j]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// 确保除法结果为整数
|
|
|
|
|
num1 = num2 * (random.nextInt(10) + 1);
|
|
|
|
|
else if ("/".equals(chosenOperators[i-1])) {
|
|
|
|
|
// 调整被除数为除数的倍数
|
|
|
|
|
operands[i-1] = operands[i] * (random.nextInt(10) + 1);
|
|
|
|
|
// 更新已添加到问题中的数值
|
|
|
|
|
question.setLength(0);
|
|
|
|
|
question.append(operands[0]);
|
|
|
|
|
for (int j = 1; j < i; j++) {
|
|
|
|
|
question.append(" " + chosenOperators[j-1] + " " + operands[j]);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 添加运算符和操作数
|
|
|
|
|
question.append(" " + chosenOperators[i-1] + " " + operands[i]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 10%的概率添加括号
|
|
|
|
|
if (random.nextDouble() < 0.1) {
|
|
|
|
|
question.append("(");
|
|
|
|
|
question.append(num1);
|
|
|
|
|
question.append(" ").append(op).append(" ");
|
|
|
|
|
question.append(num2);
|
|
|
|
|
question.append(")");
|
|
|
|
|
} else {
|
|
|
|
|
question.append(num1);
|
|
|
|
|
question.append(" ").append(op).append(" ");
|
|
|
|
|
question.append(num2);
|
|
|
|
|
// 10%的概率添加外层括号(如果有多个操作数)
|
|
|
|
|
if (operandCount > 1 && random.nextDouble() < 0.1) {
|
|
|
|
|
question.insert(0, "(").append(")");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
question.append(" = ?");
|
|
|
|
|