ADD file via upload

develop
psoyzuart 7 months ago
parent 69f6214223
commit 0c511840c3

@ -0,0 +1,64 @@
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();
}
}
Loading…
Cancel
Save