ADD file via upload

pull/3/head
hnu202326010305 2 weeks ago
parent 44062e673a
commit 5ff952dbed

@ -0,0 +1,70 @@
import java.util.List;
import java.util.Random;
/**
*
*/
public class TrigManager {
private static final Random RANDOM = new Random();
private static final String[] TRIG_FUNCTIONS = {"sin", "cos", "tan"};
//添加三角函数
public String addTrigOperations(String expression, List<Integer> numPositions) {
if (numPositions.isEmpty()) {
return expression;
}
String[] tokens = expression.split(" ");
int targetIndex = chooseTargetIndex(numPositions, tokens);
if (targetIndex == -1) {
return expression;
}
tokens[targetIndex] = applyTrig(tokens[targetIndex]);
return String.join(" ", tokens);
}
//随机函数种类
private int chooseTargetIndex(List<Integer> numPositions, String[] tokens) {
for (int tries = 0; tries < 50; tries++) {
int idx = numPositions.get(RANDOM.nextInt(numPositions.size()));
if (canApplyTrig(tokens, idx)) {
return idx;
}
}
return -1;
}
//检测三角函数是否合法
private boolean canApplyTrig(String[] tokens, int index) {
if (!isNumber(tokens[index])) {
return false;
}
int value = Integer.parseInt(tokens[index]);
// 防止 tan(90)
if (value == 90 && RANDOM.nextInt(3) == 2) {
return false;
}
// cos(90) 不加在除法右边
if (index > 0 && tokens[index - 1].equals("/") && value == 90) {
return false;
}
return true;
}
//添加操作
private String applyTrig(String token) {
String func = TRIG_FUNCTIONS[RANDOM.nextInt(TRIG_FUNCTIONS.length)];
return func + "(" + token + ")";
}
private boolean isNumber(String token) {
try {
Integer.parseInt(token);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
Loading…
Cancel
Save