AI生成代码(待修改)

main
Teptao 7 months ago
parent e2085370ba
commit 50f01a65eb

@ -0,0 +1,51 @@
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
/**
*
*
*/
public abstract class AbstractProblemGenerator implements IProblemGenerator {
protected static final Random random = new Random();
protected static final int MIN_OPERAND = 1;
protected static final int MAX_OPERAND = 100;
@Override
public List<Equation> generate(int count, Set<String> existingProblems) {
List<Equation> newProblems = new ArrayList<>();
Set<String> currentBatchCanonicalForms = new HashSet<>();
// 为了避免无限循环,设置一个最大尝试次数
int maxAttempts = count * 100;
int attempts = 0;
while (newProblems.size() < count && attempts < maxAttempts) {
Equation candidate = createSingleProblem();
String canonicalForm = candidate.toCanonicalString();
// 检查是否与历史题目或本次生成的题目重复
if (!existingProblems.contains(canonicalForm) &&!currentBatchCanonicalForms.contains(canonicalForm)) {
newProblems.add(candidate);
currentBatchCanonicalForms.add(canonicalForm);
}
attempts++;
}
if (newProblems.size() < count) {
System.err.println("警告: 未能生成足够数量的唯一题目。可能题库已饱和。");
}
return newProblems;
}
/**
*
*
* @return Equation
*/
protected abstract Equation createSingleProblem();
}

@ -0,0 +1,125 @@
import java.util.List;
import java.util.Scanner;
import java.util.Set;
/**
*
*
*/
public class Application {
private static final int MIN_PROBLEMS = 10;
private static final int MAX_PROBLEMS = 30;
// 依赖注入:在主类中创建和组装服务
private final Scanner scanner = new Scanner(System.in);
private final AuthService authService = new AuthService(new InMemoryUserRepository());
private final SessionManager sessionManager = SessionManager.getInstance();
private final IFileService fileService = new TextFilePersistence();
public static void main(String args) {
Application app = new Application();
app.run();
}
/**
*
*/
public void run() {
System.out.println("欢迎使用模块化数学题目生成系统!");
while (true) {
if (!sessionManager.isUserLoggedIn()) {
handleLoggedOutState();
} else {
handleLoggedInState();
}
}
}
/**
*
*/
private void handleLoggedOutState() {
System.out.print("请输入用户名和密码(用空格隔开): ");
String credentials = scanner.nextLine().split("\\s+");
if (credentials.length!= 2) {
System.out.println("输入格式错误,请重新输入。");
return;
}
authService.login(credentials, credentials)
.ifPresentOrElse(
sessionManager::startSession,
() -> System.out.println("请输入正确的用户名、密码")
);
}
/**
*
*/
private void handleLoggedInState() {
String levelName = sessionManager.getCurrentLevel().getDisplayName();
System.out.printf("当前选择为%s出题准备生成%s数学题目请输入生成题目数量输入-1将退出当前用户重新登录%n", levelName, levelName);
String input = scanner.nextLine().trim();
if (input.equals("-1")) {
sessionManager.endSession();
System.out.println("已退出当前用户。");
return;
}
if (input.startsWith("切换为")) {
handleSwitchLevel(input);
return;
}
try {
int count = Integer.parseInt(input);
if (count >= MIN_PROBLEMS && count <= MAX_PROBLEMS) {
generateAndSaveProblems(count);
} else {
System.out.printf("题目数量的有效输入范围是“%d-%d”。%n", MIN_PROBLEMS, MAX_PROBLEMS);
}
} catch (NumberFormatException e) {
System.out.println("无效输入,请输入数字或有效指令。");
}
}
/**
*
*
* @param input "切换为初中"
*/
private void handleSwitchLevel(String input) {
String targetLevelName = input.substring("切换为".length());
EducationLevel targetLevel = EducationLevel.fromDisplayName(targetLevelName);
if (targetLevel!= null) {
sessionManager.setCurrentLevel(targetLevel);
System.out.printf("切换成功,当前选择为%s出题。%n", targetLevelName);
} else {
System.out.println("请输入小学、初中和高中三个选项中的一个");
}
}
/**
*
*
* @param count
*/
private void generateAndSaveProblems(int count) {
User currentUser = sessionManager.getCurrentUser();
System.out.println("正在加载历史题目以确保唯一性...");
Set<String> history = fileService.loadAllProblemHistory(currentUser);
System.out.println("正在生成题目...");
List<Equation> newProblems = sessionManager.getCurrentGenerator().generate(count, history);
if (!newProblems.isEmpty()) {
fileService.saveProblems(currentUser, newProblems);
} else {
System.out.println("未能生成任何新题目。");
}
}
}

@ -0,0 +1,31 @@
import java.util.Optional;
/**
*
*
*/
public class AuthService {
private final UserRepository userRepository;
/**
*
*
* @param userRepository
*/
public AuthService(UserRepository userRepository) {
this.userRepository = userRepository;
}
/**
*
*
* @param username
* @param password
* @return Optional Optional
*/
public Optional<User> login(String username, String password) {
return userRepository.findByUsername(username)
.filter(user -> user.password().equals(password));
}
}

@ -0,0 +1,38 @@
/**
*
*/
public enum EducationLevel {
PRIMARY("小学"),
MIDDLE("初中"),
HIGH("高中");
private final String displayName;
EducationLevel(String displayName) {
this.displayName = displayName;
}
/**
*
*
* @return
*/
public String getDisplayName() {
return displayName;
}
/**
*
*
* @param displayName
* @return EducationLevel null
*/
public static EducationLevel fromDisplayName(String displayName) {
for (EducationLevel level : EducationLevel.values()) {
if (level.getDisplayName().equals(displayName)) {
return level;
}
}
return null;
}
}

@ -0,0 +1,29 @@
import java.util.List;
/**
*
* 1-100
*/
public class ElementaryProblemGenerator extends AbstractProblemGenerator {
@Override
protected Equation createSingleProblem() {
int operand1 = random.nextInt(MAX_OPERAND) + MIN_OPERAND;
int operand2 = random.nextInt(MAX_OPERAND) + MIN_OPERAND;
// 随机选择加法或减法
if (random.nextBoolean()) {
// 加法
return new Equation(List.of(operand1, operand2), List.of(Operator.ADD));
} else {
// 减法,确保结果非负
if (operand1 < operand2) {
// 如果第一个数小,则交换它们
int temp = operand1;
operand1 = operand2;
operand2 = temp;
}
return new Equation(List.of(operand1, operand2), List.of(Operator.SUBTRACT));
}
}
}

@ -0,0 +1,98 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
*
*
*/
public class Equation {
private final List<Integer> operands;
private final List<Operator> operators;
private final int result;
/**
*
*
* @param operands
* @param operators
*/
public Equation(List<Integer> operands, List<Operator> operators) {
this.operands = List.copyOf(operands);
this.operators = List.copyOf(operators);
this.result = calculate();
}
/**
*
*
*
* @return
*/
private int calculate() {
if (operands.isEmpty()) {
return 0;
}
int currentResult = operands.get(0);
for (int i = 0; i < operators.size(); i++) {
currentResult = operators.get(i).apply(currentResult, operands.get(i + 1));
}
return currentResult;
}
/**
*
* : "35 + 12 = 47"
*
* @return
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(operands.get(0));
for (int i = 0; i < operators.size(); i++) {
sb.append(" ").append(operators.get(i).getSymbol()).append(" ").append(operands.get(i + 1));
}
sb.append(" = ").append(result);
return sb.toString();
}
/**
*
* (+, *) "3 + 5" "5 + 3"
*
*
* @return
*/
public String toCanonicalString() {
if (operators.size()!= 1) {
// 对于多操作符的复杂情况,暂不进行排序,直接返回标准形式
return getSimpleExpression();
}
Operator op = operators.get(0);
if (op == Operator.ADD || op == Operator.MULTIPLY) {
List<Integer> sortedOperands = new ArrayList<>(operands);
Collections.sort(sortedOperands);
return sortedOperands.get(0) + " " + op.getSymbol() + " " + sortedOperands.get(1);
}
return getSimpleExpression();
}
/**
*
*
* @return
*/
private String getSimpleExpression() {
StringBuilder sb = new StringBuilder();
sb.append(operands.get(0));
for (int i = 0; i < operators.size(); i++) {
sb.append(" ").append(operators.get(i).getSymbol()).append(" ").append(operands.get(i + 1));
}
return sb.toString();
}
}

@ -0,0 +1,30 @@
import java.util.ArrayList;
import java.util.List;
/**
*
* 3-5使
*/
public class HighSchoolProblemGenerator extends AbstractProblemGenerator {
private static final Operator OPERATORS = {
Operator.ADD, Operator.SUBTRACT, Operator.MULTIPLY
}; // 暂时排除除法以简化生成逻辑
@Override
protected Equation createSingleProblem() {
int numOperands = random.nextInt(3) + 3; // 3到5个操作数
List<Integer> operands = new ArrayList<>();
List<Operator> operators = new ArrayList<>();
for (int i = 0; i < numOperands; i++) {
operands.add(random.nextInt(MAX_OPERAND) + MIN_OPERAND);
}
for (int i = 0; i < numOperands - 1; i++) {
operators.add(OPERATORS);
}
return new Equation(operands, operators);
}
}

@ -0,0 +1,24 @@
import java.util.List;
import java.util.Set;
/**
*
*/
public interface IFileService {
/**
*
*
* @param user
* @param problems
*/
void saveProblems(User user, List<Equation> problems);
/**
*
*
* @param user
* @return
*/
Set<String> loadAllProblemHistory(User user);
}

@ -0,0 +1,18 @@
import java.util.List;
import java.util.Set;
/**
* ()
*
*/
public interface IProblemGenerator {
/**
*
*
* @param count
* @param existingProblems
* @return Equation
*/
List<Equation> generate(int count, Set<String> existingProblems);
}

@ -0,0 +1,33 @@
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
*
*
*/
public class InMemoryUserRepository implements UserRepository {
private static final Map<String, User> userDatabase = new ConcurrentHashMap<>();
// 静态初始化块,用于加载预设用户数据
static {
// 小学老师
userDatabase.put("primary_teacher1", new User("primary_teacher1", "p123", EducationLevel.PRIMARY));
userDatabase.put("primary_teacher2", new User("primary_teacher2", "p123", EducationLevel.PRIMARY));
userDatabase.put("primary_teacher3", new User("primary_teacher3", "p123", EducationLevel.PRIMARY));
// 初中老师
userDatabase.put("middle_teacher1", new User("middle_teacher1", "m123", EducationLevel.MIDDLE));
userDatabase.put("middle_teacher2", new User("middle_teacher2", "m123", EducationLevel.MIDDLE));
userDatabase.put("middle_teacher3", new User("middle_teacher3", "m123", EducationLevel.MIDDLE));
// 高中老师
userDatabase.put("high_teacher1", new User("high_teacher1", "h123", EducationLevel.HIGH));
userDatabase.put("high_teacher2", new User("high_teacher2", "h123", EducationLevel.HIGH));
userDatabase.put("high_teacher3", new User("high_teacher3", "h123", EducationLevel.HIGH));
}
@Override
public Optional<User> findByUsername(String username) {
return Optional.ofNullable(userDatabase.get(username));
}
}

@ -0,0 +1,30 @@
import java.util.List;
/**
*
* 2-3
*/
public class MiddleSchoolProblemGenerator extends AbstractProblemGenerator {
private static final Operator OPERATORS = {
Operator.ADD, Operator.SUBTRACT, Operator.MULTIPLY, Operator.DIVIDE
};
@Override
protected Equation createSingleProblem() {
// 简单实现:目前仅生成两个操作数的题目
Operator operator = OPERATORS;
if (operator == Operator.DIVIDE) {
// 为除法生成能整除的数
int divisor = random.nextInt(MAX_OPERAND - 1) + 2; // 除数不为0或1
int quotient = random.nextInt(MAX_OPERAND / divisor) + 1;
int dividend = divisor * quotient;
return new Equation(List.of(dividend, divisor), List.of(Operator.DIVIDE));
} else {
int operand1 = random.nextInt(MAX_OPERAND) + MIN_OPERAND;
int operand2 = random.nextInt(MAX_OPERAND) + MIN_OPERAND;
return new Equation(List.of(operand1, operand2), List.of(operator));
}
}
}

@ -0,0 +1,40 @@
import java.util.function.IntBinaryOperator;
/**
*
*
*/
public enum Operator {
ADD('+', (a, b) -> a + b),
SUBTRACT('-', (a, b) -> a - b),
MULTIPLY('*', (a, b) -> a * b),
DIVIDE('/', (a, b) -> a / b);
private final char symbol;
private final IntBinaryOperator operation;
Operator(char symbol, IntBinaryOperator operation) {
this.symbol = symbol;
this.operation = operation;
}
/**
*
*
* @return
*/
public char getSymbol() {
return symbol;
}
/**
*
*
* @param a
* @param b
* @return
*/
public int apply(int a, int b) {
return operation.applyAsInt(a, b);
}
}

@ -0,0 +1,79 @@
/**
* 使
*
*/
public class SessionManager {
private static final SessionManager INSTANCE = new SessionManager();
private User currentUser;
private IProblemGenerator currentGenerator;
private EducationLevel currentLevel;
private SessionManager() {
// 私有构造函数防止外部实例化
}
/**
* SessionManager
*
* @return SessionManager
*/
public static SessionManager getInstance() {
return INSTANCE;
}
/**
*
*
* @param user
*/
public void startSession(User user) {
this.currentUser = user;
setCurrentLevel(user.defaultLevel());
}
/**
* (退)
*/
public void endSession() {
this.currentUser = null;
this.currentGenerator = null;
this.currentLevel = null;
}
/**
*
*
* @return true false
*/
public boolean isUserLoggedIn() {
return currentUser!= null;
}
public User getCurrentUser() {
return currentUser;
}
public IProblemGenerator getCurrentGenerator() {
return currentGenerator;
}
public EducationLevel getCurrentLevel() {
return currentLevel;
}
/**
*
*
* @param level
*/
public void setCurrentLevel(EducationLevel level) {
this.currentLevel = level;
this.currentGenerator = switch (level) {
case PRIMARY -> new ElementaryProblemGenerator();
case MIDDLE -> new MiddleSchoolProblemGenerator();
case HIGH -> new HighSchoolProblemGenerator();
};
}
}

@ -0,0 +1,82 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*
*/
public class TextFilePersistence implements IFileService {
private static final DateTimeFormatter FILE_NAME_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
// 正则表达式用于从文件中提取表达式部分,例如 "1. 3 + 5 = 8" -> "3 + 5"
private static final Pattern EXPRESSION_PATTERN = Pattern.compile("^\\d+\\.\\s*(.*?)\\s*=.*$");
@Override
public void saveProblems(User user, List<Equation> problems) {
String userDirectoryPath = user.getStoragePath();
try {
Files.createDirectories(Paths.get(userDirectoryPath));
String fileName = LocalDateTime.now().format(FILE_NAME_FORMATTER) + ".txt";
Path filePath = Paths.get(userDirectoryPath, fileName);
try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(filePath))) {
for (int i = 0; i < problems.size(); i++) {
writer.println((i + 1) + ". " + problems.get(i).toString());
if (i < problems.size() - 1) {
writer.println(); // 每题之间空一行
}
}
System.out.println("题目已成功保存至: " + filePath.toAbsolutePath());
}
} catch (IOException e) {
System.err.println("错误:无法保存文件。 " + e.getMessage());
}
}
@Override
public Set<String> loadAllProblemHistory(User user) {
Set<String> history = new HashSet<>();
File userDirectory = new File(user.getStoragePath());
if (!userDirectory.exists() ||!userDirectory.isDirectory()) {
return history; // 目录不存在,没有历史记录
}
File files = userDirectory.listFiles((dir, name) -> name.endsWith(".txt"));
if (files == null) {
return history;
}
for (File file : files) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine())!= null) {
Matcher matcher = EXPRESSION_PATTERN.matcher(line);
if (matcher.matches()) {
// 此处不进行规范化,因为生成器在检查时会进行规范化
// 直接添加文件中的表达式字符串
history.add(matcher.group(1).trim());
}
}
} catch (IOException e) {
System.err.println("警告:读取历史文件失败 " + file.getName() + "。 " + e.getMessage());
}
}
return history;
}
}

@ -0,0 +1,19 @@
/**
*
* (Value Object)
*
* @param username
* @param password ()
* @param defaultLevel
*/
public record User(String username, String password, EducationLevel defaultLevel) {
/**
*
*
* @return
*/
public String getStoragePath() {
return "./" + username + "/";
}
}

@ -0,0 +1,16 @@
import java.util.Optional;
/**
* 访
*
*/
public interface UserRepository {
/**
*
*
* @param username
* @return Optional
*/
Optional<User> findByUsername(String username);
}
Loading…
Cancel
Save