Skip to content

Commit 72a4ff6

Browse files
committed
fix: 随机生成使用用户输入的课程数量
1 parent 2691a90 commit 72a4ff6

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

src/components/InputPanel.tsx

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,27 +51,32 @@ export default function InputPanel({
5151
};
5252

5353
const generateRandom = () => {
54-
// 随机课程数量 3-8
55-
const num = Math.floor(Math.random() * 6) + 3;
54+
// 使用用户输入的课程数量
55+
const num = parseInt(numCourses, 10);
56+
if (isNaN(num) || num < 2 || num > 20) {
57+
setError('请先输入有效的课程数量 (2-20)');
58+
return;
59+
}
5660

5761
// 生成随机 DAG(有向无环图)
62+
// 边数量:节点数的 1-2 倍,确保图有一定复杂度
5863
const prereqs: number[][] = [];
59-
const edgeCount = Math.floor(Math.random() * (num * 2)) + 1;
64+
const maxEdges = Math.min(num * 2, (num * (num - 1)) / 2);
65+
const edgeCount = Math.floor(Math.random() * maxEdges) + Math.max(1, Math.floor(num / 2));
6066
const existingEdges = new Set<string>();
6167

62-
for (let i = 0; i < edgeCount; i++) {
63-
// 确保 from > to 来避免环
68+
for (let i = 0; i < edgeCount && prereqs.length < maxEdges; i++) {
69+
// 确保 from > to 来避免环(拓扑序:小编号是先修课)
6470
const to = Math.floor(Math.random() * (num - 1));
6571
const from = Math.floor(Math.random() * (num - to - 1)) + to + 1;
6672
const key = `${from}-${to}`;
6773

68-
if (!existingEdges.has(key)) {
74+
if (!existingEdges.has(key) && from !== to) {
6975
existingEdges.add(key);
7076
prereqs.push([from, to]);
7177
}
7278
}
7379

74-
setNumCourses(num.toString());
7580
setPrerequisites(JSON.stringify(prereqs));
7681
setError(null);
7782
onSubmit(num, prereqs);

0 commit comments

Comments
 (0)