|
|
|
@ -2,17 +2,41 @@ import java.util.Random;
|
|
|
|
|
|
|
|
|
|
public class PrimaryProblem implements ProblemsGenerator {
|
|
|
|
|
private static final Random RANDOM = new Random();
|
|
|
|
|
private static final char[] OPS = {'+', '-', '*', '/'};
|
|
|
|
|
private static final String[] OPERATORS = {"+", "-", "*", "/"};
|
|
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
public String generate() {
|
|
|
|
|
int count = RANDOM.nextInt(5) + 1; // 1~5个数
|
|
|
|
|
int count = RANDOM.nextInt(4) + 2;
|
|
|
|
|
StringBuilder sb = new StringBuilder();
|
|
|
|
|
|
|
|
|
|
boolean addParentheses = count >= 3 && RANDOM.nextDouble() < 0.5;
|
|
|
|
|
if (addParentheses) {
|
|
|
|
|
int parenCount = RANDOM.nextInt(count - 2) + 2;
|
|
|
|
|
int startPos = RANDOM.nextInt(count - parenCount + 1);
|
|
|
|
|
|
|
|
|
|
for (int i = 0; i < count; i++) {
|
|
|
|
|
if (i == startPos) {
|
|
|
|
|
sb.append("( ");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int num = RANDOM.nextInt(100) + 1;
|
|
|
|
|
sb.append(num);
|
|
|
|
|
|
|
|
|
|
if (i == startPos + parenCount - 1) {
|
|
|
|
|
sb.append(" )");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (i < count - 1) {
|
|
|
|
|
sb.append(" ").append(OPERATORS[RANDOM.nextInt(OPERATORS.length)]).append(" ");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
for (int i = 0; i < count; i++) {
|
|
|
|
|
int num = RANDOM.nextInt(100) + 1;
|
|
|
|
|
sb.append(num);
|
|
|
|
|
if (i < count - 1) {
|
|
|
|
|
sb.append(" ").append(OPS[RANDOM.nextInt(OPS.length)]).append(" ");
|
|
|
|
|
sb.append(" ").append(OPERATORS[RANDOM.nextInt(OPERATORS.length)]).append(" ");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return sb.toString();
|
|
|
|
|