Skip to content

Commit 05993c1

Browse files
committed
added calc-equation & critical-connections
1 parent 5cb2872 commit 05993c1

File tree

6 files changed

+173
-33
lines changed

6 files changed

+173
-33
lines changed

src/graph/calc-equation.ts

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
function calcEquation(
2+
equations: string[][],
3+
values: number[],
4+
queries: string[][]
5+
): number[] {
6+
const graph = new Map<string, Map<string, number>>();
7+
const result: number[] = [];
8+
9+
for (let i = 0; i < equations.length; i++) {
10+
const [a, b] = equations[i];
11+
const value = values[i];
12+
13+
if (!graph.has(a)) graph.set(a, new Map());
14+
if (!graph.has(b)) graph.set(b, new Map());
15+
16+
graph.get(a).set(b, value);
17+
graph.get(b).set(a, 1/value);
18+
}
19+
20+
const dfs = (start: string, end: string, visited: Set<string>): number => {
21+
if (!graph.has(start) || !graph.has(end)) {
22+
return -1.0;
23+
}
24+
if (start === end) {
25+
return 1.0;
26+
}
27+
visited.add(start);
28+
29+
for (const [neighbor, neighborVal] of graph.get(start)) {
30+
if (!visited.has(neighbor)) {
31+
const result = dfs(neighbor, end, visited);
32+
if (result !== -1.0) {
33+
return result * neighborVal
34+
}
35+
}
36+
}
37+
return -1.0;
38+
}
39+
40+
for (const [d, c] of queries) {
41+
const visited = new Set<string>();
42+
result.push(dfs(d, c, visited));
43+
}
44+
45+
return result;
46+
};
47+
48+
export function calcEquationDBG() {
49+
const tests = [
50+
{
51+
input: {
52+
equations: [["a", "b"], ["b", "c"]],
53+
values: [2.0, 3.0],
54+
queries: [["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"]]
55+
},
56+
expected: [6.0, 0.5, -1.0, 1.0, -1.0]
57+
},
58+
{
59+
input: {
60+
equations: [["a", "b"], ["b", "c"], ["bc", "cd"]],
61+
values: [1.5, 2.5, 5.0],
62+
queries: [["a", "c"], ["c", "b"], ["bc", "cd"], ["cd", "bc"]]
63+
},
64+
expected: [3.75, 0.4, 5.0, 0.2]
65+
},
66+
{
67+
input: {
68+
equations: [["a", "b"]],
69+
values: [0.5],
70+
queries: [["a", "b"], ["b", "a"], ["a", "c"], ["x", "y"]]
71+
},
72+
expected: [0.5, 2.0, -1.0, -1.0]
73+
}
74+
];
75+
76+
tests.forEach((test, index) => {
77+
const result = calcEquation(test.input.equations, test.input.values, test.input.queries);
78+
const success = JSON.stringify(result) === JSON.stringify(test.expected);
79+
if (success) {
80+
console.log(`Test ${index} success`);
81+
} else {
82+
console.log(`Test ${index} fail`);
83+
console.log(`expected: ${JSON.stringify(test.expected)}`);
84+
console.log(`got: ${JSON.stringify(result)}`);
85+
}
86+
});
87+
88+
}

src/graph/critical-connections.ts

+50-27
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,73 @@
1+
function criticalConnectionsEZ(n: number, connections: number[][]): number[][] {
2+
const graph: number[][] = Array.from({ length: n }, () => []);
3+
const result: number[][] = [];
14

2-
const connections = [
3-
[0,1],
4-
[1,2],
5-
[2,0],
6-
[1,3]
7-
]
5+
for (const [u, v] of connections) {
6+
graph[u].push(v);
7+
graph[v].push(u);
8+
}
9+
10+
const isConnected = (removedEdge: [number, number]) => {
11+
const visited: boolean[] = new Array(n).fill(false);
12+
let count = 0;
13+
const dfs = (u: number) => {
14+
visited[u] = true;
15+
count++;
16+
for (const v of graph[u]) {
17+
if (!visited[v]
18+
&& !(u === removedEdge[0] && v === removedEdge[1])
19+
&& !(u === removedEdge[1] && v === removedEdge[0])
20+
) {
21+
dfs(v);
22+
}
23+
}
24+
};
25+
dfs(0);
26+
return count === n;
27+
};
28+
29+
for (const [u, v] of connections) {
30+
if (!isConnected([u, v])) {
31+
result.push([u, v]);
32+
}
33+
}
34+
35+
return result;
36+
}
837

938
function criticalConnections(n: number, connections: number[][]): number[][] {
1039
const graph: number[][] = Array.from({ length: n }, () => []);
1140
const result: number[][] = [];
12-
const disc: number[] = new Array(n).fill(-1); // Время открытия вершины
13-
const low: number[] = new Array(n).fill(-1); // Минимальное время посещения
41+
const disc: number[] = new Array(n).fill(-1);
42+
const low: number[] = new Array(n).fill(-1);
1443
let time = 0;
1544

16-
// Построение графа
1745
for (const [u, v] of connections) {
1846
graph[u].push(v);
1947
graph[v].push(u);
2048
}
21-
22-
// Основная функция DFS
2349
const dfs = (u: number, parent: number) => {
24-
disc[u] = low[u] = time++; // Инициализация времени открытия и low
50+
disc[u] = low[u] = time++;
2551
for (const v of graph[u]) {
26-
if (v === parent) continue; // Игнорируем родительскую вершину
27-
28-
if (disc[v] === -1) { // Если вершина v еще не посещена
29-
dfs(v, u); // Рекурсивный DFS
30-
31-
// Обновляем low[u] на основе дочерней вершины v
52+
if (v === parent){
53+
continue;
54+
};
55+
if (disc[v] === -1) {
56+
dfs(v, u);
3257
low[u] = Math.min(low[u], low[v]);
33-
34-
// Если low[v] > disc[u], то (u, v) — критическое соединение
3558
if (low[v] > disc[u]) {
3659
result.push([u, v]);
3760
}
3861
} else {
39-
// Обратное ребро, обновляем low[u]
4062
low[u] = Math.min(low[u], disc[v]);
4163
}
4264
}
4365
};
44-
45-
// Запуск DFS для всех вершин
4666
for (let i = 0; i < n; i++) {
4767
if (disc[i] === -1) {
48-
dfs(i, -1); // -1 означает, что у начальной вершины нет родителя
68+
dfs(i, -1);
4969
}
5070
}
51-
5271
return result;
5372
}
5473

@@ -58,12 +77,16 @@ export function criticalConnectionsDBG(){
5877
const tests = [
5978
{
6079
input: { n: 4, connections: [[0, 1], [1, 2], [2, 0], [1, 3]] },
61-
result: [[1, 3]] // Соединение [1, 3] является критическим
80+
result: [[1, 3]]
6281
},
6382
{
6483
input: { n: 2, connections: [[0, 1]] },
65-
result: [[0, 1]] // Единственное соединение [0, 1] является критическим
84+
result: [[0, 1]]
6685
},
86+
{
87+
input: { n: 6, connections: [[0, 1], [1, 2], [1, 3], [3, 4], [4, 5], [2, 5]] },
88+
result: [[0, 1]]
89+
}
6790
];
6891

6992
tests.forEach((test, index) => {

src/main.ts

+2-6
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1+
import { calcEquationDBG } from "./graph/calc-equation";
12
import { criticalConnectionsDBG } from "./graph/critical-connections";
23

3-
criticalConnectionsDBG()
4-
5-
6-
7-
8-
94

5+
calcEquationDBG()

src/worker/test.ts

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import workerpool from 'workerpool';
2+
3+
function longComputationTask(input: number): number {
4+
let result = 0;
5+
for (let i = 0; i < 1e9; i++) {
6+
result += Math.sin(input + i);
7+
}
8+
return result;
9+
}
10+
11+
workerpool.worker({
12+
longComputationTask: longComputationTask
13+
});

src/worker/worker.ts

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import workerpool from 'workerpool';
2+
3+
// Задача с задержкой, которая симулирует долгую операцию
4+
function longComputationTask(input: number): Promise<string> {
5+
console.log(`Task ${input} started`);
6+
7+
return new Promise((resolve) => {
8+
setTimeout(() => {
9+
const result = `Task ${input} completed`;
10+
console.log(result);
11+
resolve(result);
12+
}, 5000); // Задержка 5 секунд для демонстрации параллельной работы
13+
});
14+
}
15+
16+
// Экспортируем задачу через workerpool
17+
workerpool.worker({
18+
longComputationTask: longComputationTask
19+
});

tsconfig.json

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"strictBindCallApply": false,
1818
"forceConsistentCasingInFileNames": false,
1919
"noFallthroughCasesInSwitch": false,
20+
"esModuleInterop": true,
2021
},
2122
"include": ["src", "test"]
2223
}

0 commit comments

Comments
 (0)