Graph
Assignment 14
by MimiE
HTML
<h3>Assignment 14: "Graph"</h3>
Select Two Nodes:
<br/>From
<select id = "from"/>
<option value = "A">A</option>
<option value = "B">B</option>
<option value = "C">C</option>
<option value = "D">D</option>
<option value = "E">E</option>
<option value = "F" selected>F</option>
<option value = "G">G</option>
<select> To
<select id = "to">
<option value = "A">A</option>
<option value = "B">B</option>
<option value = "C"selected >C</option>
<option value = "D">D</option>
<option value = "E">E</option>
<option value = "F" >F</option>
<option value = "G">G</option>
</select><br><br>
<input type = "button" onclick = "createGraph();" value = "Create Graph" />
<input type = "button" onclick = "calculateNow();" value = "Calculate" />
<p id = "nodes">
<p id = "edges"></p>
<span id = "result" />
JavaScript
this.addNode = function(_name) {
var node = new Node(_name);
this.nodes.push(node);
return node;
};
this.addEdge = function(from, to, cost) {
var edge = new Edge(cost);
edge.from = from;
edge.to = to;
edge.cost = cost;
this.edges.push(edge);
return edge;
};
var Graph = function() {
this.edges = {};
}
graph.prototype.addNode = function (label) {
// an adjacent list is used to store the edges between nodes
this.edges[label] = {};
};
graph.prototype.addEdge = function (from, to, cost) {
// undirected graph
this.edges[from][to] = cost;
this.edges[to][from] = cost;
};
graph.prototype.calculatePaths = function (from, to, cost, paths) {
paths.push(from);
// permutate and display all the paths (and costs) between
// the two given nodes
if (from == to) {
// reach the destination, display it in the result span
displayPath(paths, cost);
} else {
// enumerate the adjacent nodes
for (var connected in this.edges[from]) {
if (paths.indexOf(connected) < 0) { // not visited yet
var thiscost = this.edges[from][connected];
this.calculatePaths(connected, to, cost + thiscost, paths);
}
}
}
paths.pop();
};
function displayPath(paths, cost) {
// convert the paths into a string
var value = paths[0];
for (var i = 1; i < paths.length; i++) {
value = value + ", " + paths[i];
}
value += ": " + cost;
// add to the page
var result = document.getElementById('result');
result.innerHTML += value + "<br />";
}
window.calculateNow = function () {
// this function calculates and displays the costs
// of all paths between two nodes.
var result = document.getElementById('result');
result.innerHTML = "";
// get the source and destination nodes from user input
var from = document.getElementById('from').value;
var to =...