14
by zazagalaxy
HTML
<h3>
<center>Assignment 14</center>
</h3>
<h4><center>
Graph Calculations</center>
</h4>
</select>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'>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'>C</option>
<option value='D'>D</option>
<option value='E'>E</option>
<option value='F'>F</option>
<option value='G'>G</option>
</select>
<input type="button" id="click" onclick="create();" value="Create Graph" />
<input type="button" id="click" onclick="getcalc();" value="Calculate" />
<br>
<br>
<div id="output">
</div>
<img src="http://cop3530.pbworks.com/f/1436983373/Graph1.jpg" />
JavaScript
//in collaboration with Eugene
var Node = function(name) {
this.name = name;
}
var Graph = function() {
this.edges = {};
this.paths = [];
this.cost = 0;
}
Graph.prototype.addnode = function(name) {
this.edges[name] = new Node(name);
}
Graph.prototype.addedge = function(v,w, cost) {
this.edges[v][w] = cost;
this.edges[w][v] = cost;
}
Graph.prototype.calculate = function(v, w, cost, path) {
this.paths.push(v);
if (v === w) {
this.print(path, cost);
} else {
for (var i in this.edges[v]) {
if (!this.paths.includes(i)) {
var c1 = this.edges[v][i];
var c2 = c1 + cost;
this.calculate(i, w, c2, path);
}
}
}
this.paths.pop();
}
Graph.prototype.print = function(path, cost) {
var out = "Path: ";
var c = 0;
for (var i = 0; i < this.paths.length; i++) {
out = out + this.paths[i] + ",";
}
out += " Cost= " + cost + "<br>";
document.getElementById("output").innerHTML += out;
}
var graph = new Graph();
var create = function() {
var nodes = ["A", "B", "C", "D", "E", "F", "G"];
for (var i in nodes) {
graph.addnode(nodes[i]);
}
var edges = [["A","B",2],["A", "C", 1],["B", "D", 1],["B", "G", 1],["C", "D", 1],["C", "E", 1],["D", "E", 2],["D", "F", 1],["D", "G", 2]];
for (var t in edges) {
graph.addedge(edges[t][0],edges[t][1],edges[t][2]);
}
var out = "";
var out1 = "";
for (var n in nodes) {
out1 += "Node: " + n + " Value: " + nodes[n] + "<br>";
}
for (var g in edges) {
out += "Edge: " + edges[g][0] + ", " + edges[g][1] + " Cost: " + edges[g][2] + "<br>";
}
out1 += out;
document.getElementById('output').innerHTML = out1;
}
function getcalc() {
document.getElementById('output').innerHTML = "";
var v1 = document.getElementById('from').value;
var v2 = document.getElementById('to').value;
graph.calculate(v1,v2,graph.cost,graph.paths);
}