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.
individual/src/PrimaryQuestionGenerator.java

65 lines
2.3 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.

public class PrimaryQuestionGenerator extends AbstractQuestionGenerator {
private static final String[] OPERATORS = {"+", "-", "×", "÷"};
@Override
public String generateQuestion() {
int attempts = 0;
while (attempts < 100) {
attempts++;
int operandCount = random.nextInt(4) + 2; // 2~5个操作数
StringBuilder question = new StringBuilder();
// 生成操作数和运算符
for (int i = 0; i < operandCount; i++) {
question.append(generateNumber());
if (i < operandCount - 1) {
question.append(" ").append(generateOperator(OPERATORS)).append(" ");
}
}
// 随机添加括号
String result = addReasonableParentheses(question.toString(), operandCount);
result = ensureBalancedParentheses(result); // 确保括号平衡
if (isQuestionUnique(result) && isValidParentheses(result) && hasOperator(result)) {
addToGeneratedQuestions(result);
String regex = "(?<!\\s)\\)(?=[^)]*$)";
result = result.replaceAll(regex, " )");
return result;
}
}
return "3 + 5"; // 备用题目
}
private String addReasonableParentheses(String expression, int operandCount) {
if (operandCount <= 2 || random.nextDouble() < 0.3) {
return expression;
}
String[] parts = expression.split(" ");
if (parts.length < 5) return expression;
StringBuilder newExpr = new StringBuilder();
int start = random.nextInt(parts.length / 2);
int end = start + random.nextInt(parts.length / 2 - start + 1) + 1;
end = Math.min(end, parts.length / 2 - 1);
for (int i = 0; i < parts.length; i++) {
if (i == start * 2) {
newExpr.append("( ");
}
newExpr.append(parts[i]);
if (i == end * 2 && i >= start * 2 + 2) {
newExpr.append(" )");
}
if (i < parts.length - 1) {
newExpr.append(" ");
}
}
return newExpr.toString().trim();
}
}