JSFiddle - React, Tailwind, and code Playground
by methodin
JavaScript
function round(n) {
return Math.round(n*100) / 100;
}
// Represents an edge from source to sink with capacity
var Edge = function(source, sink, capacity) {
this.source = source;
this.sink = sink;
this.capacity = capacity;
};
// Main class to manage the network
var Graph = function() {
this.edges = {};
this.nodes = [];
this.nodeMap = {};
// Add a node to the graph
this.addNode = function(node) {
this.nodes.push(node);
this.nodeMap[node] = this.nodes.length-1;
this.edges[node] = [];
};
// Add an edge from source to sink with capacity
this.addEdge = function(source, sink, capacity) {
// Create the two edges = one being the reverse of the other
var edge = new Edge(source, sink, capacity);
this.edges[source].push(edge);
};
// Does edge from source to sink exist?
this.edgeExists = function(source, sink) {
if(this.edges[source] !== undefined)
for(var i=0;i<this.edges[source].length;i++)
if(this.edges[source][i].sink == sink)
return this.edges[source][i];
return null;
};
// Turn the set of nodes and edges to a matrix with the value being
// the capacity between the nodes
this.getAssociatedMatrix = function() {
var matrix = [];
for(var i=0;i<this.nodes.length;i++) {
var row = [];
for(var j=0;j<this.nodes.length;j++) {
var edge = this.edgeExists(this.nodes[j], this.nodes[i]);
if(i == j) edge = {capacity:1};
row.push(edge != null ? edge.capacity : 0);
}
matrix.push(row);
}
return matrix;
};
// Normalizes a given matrix
this.normalize = function(matrix) {
// Find the sum of each column
var sums = [];
for(var col=0;col<matrix.length;col++) {
var sum = 0;
for(var...