Graph = class Graph {
constructor(edges = []) {
this.edges = edges;
}
checkType() {
assert(Array.isArray(this.edges));
for (let edge of this.edges) {
assert(Array.isArray(edge));
asserteq(edge.length, 3);
for (let elem of edge) {
asserteq(typeof elem, "number");
assert(elem >= 0);
}
}
}
get size() {
return this.edges.length;
}
add(edges) {
this.edges.push(...edges);
}
remove(edge) {
for (let i = this.edges.length; i >= 0; --i) {
if (edge[0] === this.edges[i][0] &&
edge[1] === this.edges[i][1] &&
edge[2] === this.edges[i][2]) {
this.edges.splice(i, 1);
}
}
throw Error(`Element ${edge} don't exist in the Graph`);
}
getVertices() {
let vertices = new Set();
for (let edge of this.edges) {
vertices.add(edge[0]);
vertices.add(edge[1]);
}
return vertices.size;
}
getDiameter() {
let adjacencyList = this.buildAdjacencyList();
let diameter = 0;
for (let vertex in adjacencyList) {
let distances = this.bfs(adjacencyList, vertex);
let maxDistance = Math.max(...Object.values(distances));
diameter = Math.max(diameter, maxDistance);
}
return diameter;
}
buildAdjacencyList() {
let adjacencyList = {};
for (let edge of this.edges) {
let [source, destination] = edge.slice(0, 2);
if (adjacencyList[source]) {
adjacencyList[source].add(destination);
} else {
adjacencyList[source] = new Set([destination]);
}
if (adjacencyList[destination]) {
adjacencyList[destination].add(source);
} else {
adjacencyList[destination] = new Set([source]);
}
}
return adjacencyList;
}
getEdgeWeight(v1, v2) {
for (let edge of this.edges)
if (v1 == edge[0] && v2 == edge[1] || v1 == edge[1] && v2 == edge[0])
return edge[2];
return null;
}
bfs(adjacencyList, start) {
let queue = [start];
let distances = {};
distances[start] = 0;
while (queue.length > 0) {
let current = queue.shift();
let neighbors = adjacencyList[current];
for (let neighbor of neighbors) {
if (!distances.hasOwnProperty(neighbor)) {
distances[neighbor] =
distances[current] + 1;
queue.push(neighbor);
}
}
}
return distances;
}
}