-
Notifications
You must be signed in to change notification settings - Fork 0
/
kargersRandomizedContraction.js
51 lines (37 loc) · 1.45 KB
/
kargersRandomizedContraction.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const Vertex = require("../../data-structures/graphs/vertex/Vertex");
function kargersRandomizedContraction(graph) {
if (graph.verticesCount < 3) {
// get one of the two remaining vertices
const vertex = graph.allVertices[0];
return graph.getEdges(vertex.key).length / 2;
}
const vertices = graph.allVertices;
const vertexKey = vertices[
getRandomNumberInRange(0, vertices.length - 1)
].key;
const adjVertices = graph.getEdges(vertexKey);
const vertex1 = vertexKey.toString();
const vertex2 = adjVertices[
getRandomNumberInRange(0, adjVertices.length - 1)
];
// remove self-loops
graph.removeAllEdgesInBetween(vertex1, vertex2);
mergeTwoVertices(graph, vertex1, vertex2);
return kargersRandomizedContraction(graph);
}
function mergeTwoVertices(graph, vertexKey1, vertexKey2) {
const mergedVertex = new Vertex(`${vertexKey1} + ${vertexKey2}`);
graph.addVertex(mergedVertex);
const vertex1Edges = graph.getEdges(vertexKey1);
const vertex2Edges = graph.getEdges(vertexKey2);
const mergedVertexAdj = [...vertex1Edges, ...vertex2Edges];
graph.removeVertex(vertexKey1);
graph.removeVertex(vertexKey2);
mergedVertexAdj.forEach(edge => {
graph.addEdge(mergedVertex.key, edge);
});
}
function getRandomNumberInRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
module.exports = kargersRandomizedContraction;