// This is a basic implementation of a Graph
// It has nodes and edges
// I am using a stack (array in Javascript) to hold info
var Node = function(_name) {
this.name = _name;
this.edges = [];
return this;
}
var Edge = function(_cost) {
this.from = null;
this.to = null;
this.cost = null;
return this;
}
function calculateNow() {
// Create Graph and calculate cost of all paths
var g = new Graph();
calculate();
function Graph() {
this.edges = {};
this.addNode = function(label) {
this.edges[label] = {};
};
this.addEdge = function(from, to, cost) {
this.edges[from][to] = cost;
this.edges[to][from] = cost;
};
//calculating minimum path for two vertices
this.calculatePaths = function(from, to, cost, paths) {
if (g.edges[from][to]) {
cost = g.edges[from][to];
paths = paths.concat("," + to);
g.displayPath(paths, cost);
} else {
next = getNextEdge(from);
cost = cost + g.edges[from][next];
paths = paths.concat("," + next);
g.displayPath(paths, cost);
if (next !== to) {
g.calculatePaths(next, to, cost, paths);
}
}
that.calculatePaths(next, to, cost + that.edges[from][next], path.concat([next]));
// implement - this is designed for a recursive call
// also if path is defined well - it will contain cost.
};
//displaying path
this.displayPath = function(path, cost) {
document.getElementById(path + " Cost: " + cost);
var res = document.getElementById('result');
res.innerHTML = path + " Cost: " + cost;
};
}
function calculate() {
var from = document.getElementById('from').value;
var to = document.getElementById('to').value;
g.addNode('A');
g.addNode('B');
g.addNode('C');
g.addNode('D');
g.addNode('E');
g.addNode('F');
g.addNode('G');
g.addEdge('A', 'B', 2);
g.addEdge('A', 'C', 1);
g.addEdge('B', 'D',...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.