Graph

Assignment 14

by Alan Harris

HTML

<button onclick="createGraph();">
Create a Graph 
</button>
<br/>
<br/> Select two nodes:
<br />From
<select id="from"></select>
To
<select id="to"></select>
<button onclick="calculate();">
Calculate 
</button>
<br/>
<p id="nodes"></p>
<br/>
<p id="edges"></p>
<br/>
<br/><span id="result" />

CSS

button:focus {
  border: 1px solid black;
  padding: 4px 4px;
}

button {
  background-color: grey;
  border: 1px solid black;
  color: white;
  padding: 4px 8px;
  text-decoration: none;
  margin: 4px 2px;
}

button:hover {
  background-color: black;
}

JavaScript

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;
}

var Graph = function() {


  this.nodes = [];
  this.edges = [];
  this.paths = [];

  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);

    // In this implementation of a graph the nodes also 
    // keep a collection of edges. For many traversal algorithms
    // you will need this and should it the edge collection
    // to your nodes here.

    return edge;
  };

  this.printNodes = function() {
    var s = "All Nodes in Graph <br/>";
    for (var i = 0; i < this.nodes.length; i++) {
      s = s + "Node: " + i + "   Name: " + this.nodes[i].name + "</br>";
    }
    return s;
  }

  this.printEdges = function() {
    var s = "All Edges in Graph <br/>";
    for (var i = 0; i < this.edges.length; i++) {
      s += "Edge: " + i + "   From: " + this.edges[i].from.name + "   To: " + this.edges[i].to.name + "   Cost: " + this.edges[i].cost + "</br>";
    }
    return s;
  }


 
  this.calculatePaths = function() {   //implement from algorithm
    return this.paths;
  }

  
  this.printPaths = function() {  //implement from algorithm
    return this.paths;
  }
}

var nodeList = document.getElementById("nodes");
var graph = new Graph(); 
function createGraph() {

  var a = graph.addNode('A');
  addNodeToCombo(a);
  var b = graph.addNode('B');
  addNodeToCombo(b);
  var c = graph.addNode('C');
  addNodeToCombo(c);
  var d = graph.addNode('D');
  addNodeToCombo(d);
  var e = graph.addNode('E');
  addNodeToCombo(e);
  var f = graph.addNode('F');
  addNodeToCombo(f);
  var g = graph.addNode('G');
  addNodeToCombo(g);

  graph.addEdge(a, b, 2);
  graph.addEdge(a,...