Assignment 14

by pat spag

HTML

<input type="button" onclick="createGraph();" value="Create Graph" />
<br/>
<br/> 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>
<input type="button" onclick="calculate();" value="Calculate" />
<br/>
<p id="nodes"></p>
<br/>
<p id="edges"></p>
<br/>
<br/><span id="result" />

JavaScript

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

var Graph = function() {

  // This is a specific implementation of a graph
  // that uses nodes edges and paths. There are many
  // more ways to implement a graph and you should 
  // research them

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


  // Must implement
  this.calculatePaths = function(from, to, cost, paths) {
  	paths = this.paths;
    paths.push(from);
    
    if(from == to){
    	this.printPaths(paths.join(" "), cost)
    }
    for (var j = 0; j < this.edges.length; j+=1 ){
    	if(paths.indexOf(this.edges[j]) < 0){
      	var temp = cost+this.edges[from][this.edges[j]];
       ...