Assignment 14 Graphs

by austinmillett

HTML

<!-- Heading 1 -->
<h2> Austin Millett </h2>

<!-- Heading 2 -->
<h3> Assignment 14 - Graphs </h3>

<!-- Title -->
<br> Select two nodes: <br> 

<!-- Selection 1 -->
From <select id = "from"> </select>

<!-- Selection 2 -->
To <select id = "to"> </select>

<!-- Button for calculate -->
<input type = "button"  id = "button1" onclick = "calculate();" value = "Calculate" /> <br>

<!-- Outputs for Paths, Nodes and Edges -->
<p id = "paths"> </p> <br>
<p id = "nodes"> </p> <br>
<p id = "edges"> </p>

CSS

/* Design for the "Calculate" button */
#button1 {
background-color: black; 
border: 2px solid; 
color: white;
padding: 4px 8px; 
text-align: center; 
font-size: 15px; 
}

JavaScript

var Graph = function() {

this.edges = {};
this.paths = [];

this.addNode = function(_name) {
this.edges[_name] = {};
}

this.addEdge = function(_from, _to, _cost) {
this.edges[_from][_to] = _cost;
this.edges[_to][_from] = _cost;
}
    
this.printNodes = function() {
var s = "All Nodes in Graph: <br/><br/>";
var i = 1;
for (var node in this.edges) {
s = s + "Node: " + i + " Name: " + node + "</br>";
i++;
}
return s;
}

this.calculatePaths = function(_from, _to, _cost, _paths) {
this.paths.push(_from);
if (_from == _to) { 
this.printPaths(_paths, _cost);
}
else {
for (var neighbor in this.edges[_from]) {
if (this.paths.includes(neighbor) == false) {
var runningCost = this.edges[_from][neighbor];
var totalCost = _cost + runningCost;
this.calculatePaths(neighbor, _to, totalCost, _paths);
}
}
}
this.paths.pop();
}

this.printPaths = function(_paths, _cost) {
var str = this.paths[0];
for (var i = 1; i < this.paths.length; i++) {
str = str + ", " + this.paths[i];
}
str += ": " + _cost + "<br />";
document.getElementById("paths").innerHTML += str;
}
}

var graph = new Graph(); // Global

function createGraph() {
graph.addNode("A");
addNodeToCombo("A");
graph.addNode("B");
addNodeToCombo("B");
graph.addNode("C");
addNodeToCombo("C");
graph.addNode("D");
addNodeToCombo("D");
graph.addNode("E");
addNodeToCombo("E");
graph.addNode("F");
addNodeToCombo("F");
graph.addNode("G");
addNodeToCombo("G");

graph.addEdge("A", "B", 2);
graph.addEdge("A", "C", 1);
graph.addEdge("B", "D", 1);
graph.addEdge("B", "G", 1);
graph.addEdge("C", "D", 1);
graph.addEdge("C", "E", 1);
graph.addEdge("D", "E", 2);
graph.addEdge("D", "F", 1);
graph.addEdge("D", "G", 2);
    
printEdges = function() {
var s = "All Edges in Graph: <br/><br/>";
s += "Edge: 1 From: A To: B Cost: 2 </br>";
s += "Edge: 2 From: A To: C Cost: 1 </br>";
s += "Edge: 3 From: B To: D Cost: 1 </br>";
s += "Edge: 4 From: B To: G Cost: 1 </br>";
s += "Edge: 5 From: C To: D Cost: 1 </br>";
s += "Edge: 6 From: C To: E Cost: 1...