parent
49ac5d1afc
commit
3d016d0eec
@ -1,20 +1,44 @@
|
|||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
|
|
||||||
public class PrimaryProblem implements ProblemsGenerator {
|
public class PrimaryProblem implements ProblemsGenerator {
|
||||||
private static final Random RANDOM = new Random();
|
private static final Random RANDOM = new Random();
|
||||||
private static final char[] OPS = {'+', '-', '*', '/'};
|
private static final String[] OPERATORS = {"+", "-", "*", "/"};
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String generate() {
|
public String generate() {
|
||||||
int count = RANDOM.nextInt(5) + 1; // 1~5个数
|
int count = RANDOM.nextInt(4) + 2;
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
for (int i = 0; i < count; i++) {
|
|
||||||
int num = RANDOM.nextInt(100) + 1;
|
boolean addParentheses = count >= 3 && RANDOM.nextDouble() < 0.5;
|
||||||
sb.append(num);
|
if (addParentheses) {
|
||||||
if (i < count - 1) {
|
int parenCount = RANDOM.nextInt(count - 2) + 2;
|
||||||
sb.append(" ").append(OPS[RANDOM.nextInt(OPS.length)]).append(" ");
|
int startPos = RANDOM.nextInt(count - parenCount + 1);
|
||||||
}
|
|
||||||
}
|
for (int i = 0; i < count; i++) {
|
||||||
return sb.toString();
|
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(OPERATORS[RANDOM.nextInt(OPERATORS.length)]).append(" ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
}
|
}
|
Loading…
Reference in new issue