Skip to content

Commit 31b549d

Browse files
committed
Add tests for Kosaraju's
1 parent e73b1dd commit 31b549d

12 files changed

+953097
-2
lines changed

src/data-structures/graph/graph.test.ts

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { getTestAnswer } from "../../helperTests";
1+
import { getTestAnswer, getTestAnswerArr } from "../../helperTests";
22
import Graph from "./graph";
33

44
describe("Graph class test", () => {
@@ -61,4 +61,40 @@ describe("Graph class test", () => {
6161
expect(labeledOrder.get("w")).toBeGreaterThan(1);
6262
expect(labeledOrder.get("w")).toBeLessThan(4);
6363
});
64+
65+
test("Kosaraju's Algorithm, using test cases from stanford-algs repo", () => {
66+
const TEST48 = `mostlyCycles_48_12800.txt`;
67+
const TEST52 = `mostlyCycles_52_20000.txt`;
68+
const TEST56 = `mostlyCycles_56_40000.txt`;
69+
const TEST60 = `mostlyCycles_60_80000.txt`;
70+
const TEST64 = `mostlyCycles_64_160000.txt`;
71+
72+
const largest5 = (m: Map<string, number> | boolean) => {
73+
if (typeof m === "boolean") return false;
74+
let arr = Array.from(m.values());
75+
arr = arr.sort((a, b) => b - a);
76+
return arr.slice(0, 5);
77+
};
78+
const test = (file: string) => {
79+
const g = Graph.createDirected(
80+
`${__dirname}/test-datasets/kosaraju/input_${file}`
81+
);
82+
const ans = getTestAnswerArr(
83+
`${__dirname}/test-datasets/kosaraju/output_${file}`
84+
);
85+
const m = g.kosaraju();
86+
expect(m).not.toBeFalsy();
87+
// if m is false, this test already failed
88+
const arr = largest5(m) as number[];
89+
arr.forEach((n, i) => {
90+
expect(n).toBe(ans[i]);
91+
});
92+
};
93+
94+
test(TEST48);
95+
test(TEST52);
96+
test(TEST56);
97+
test(TEST60);
98+
test(TEST64);
99+
});
64100
});

src/data-structures/graph/graph.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -724,7 +724,7 @@ class Graph<T> {
724724
// the vertex who calls dfs (maps leader's vertex key to the size of the Strong Component)
725725
const leader: Map<T, number> = new Map();
726726
let u, r;
727-
for (let i = finish.length - 1; i > 0; i--) {
727+
for (let i = 0; i < finish.length; i++) {
728728
u = finish[i];
729729
if (!visited.get(u)) {
730730
r = this.dfs(u);

0 commit comments

Comments
 (0)