Assignment 14

by Taylor Zimmerman

HTML

<input type="button" onclick="createGraph();" value="Create Graph" />
<br/>
<br/> Select two nodes:
<br />From
<select id="from"></select>
To
<select id="to"></select>
<input type="button" onclick="calculateNow();" 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;
}
function calculateNow() {
  // Create Graph and calculate cost of all paths
  var g = new Graph();
  calculate();

  function Graph() {
    this.edges = {};

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

    this.addEdge = function(from, to, cost) {
      this.edges[from][to] = cost;
      this.edges[to][from] = cost;
    };

    //calculating minimum path for two vertices

    this.calculatePaths = function(from, to, cost, paths) {
      if (g.edges[from][to]) {
        cost = g.edges[from][to];
        paths = paths.concat("," + to);
        g.displayPath(paths, cost);
      } else {
        next = getNextEdge(from);
        cost = cost + g.edges[from][next];
        paths = paths.concat("," + next);
        g.displayPath(paths, cost);

        if (next !== to) {
          g.calculatePaths(next, to, cost, paths);
        }
      }
			that.calculatePaths(next, to, cost + that.edges[from][next], path.concat([next]));
      // implement - this is designed for a recursive call
      // also if path is defined well - it will contain cost.
    };


    //displaying path
    this.displayPath = function(path, cost) {
      document.getElementById(path + " Cost: " + cost);
      var res = document.getElementById('result');
      res.innerHTML = path + " Cost: " + cost;
    };

  }

  function calculate() {
    var from = document.getElementById('from').value;
    var to = document.getElementById('to').value;

    g.addNode('A');
    g.addNode('B');
    g.addNode('C');
    g.addNode('D');
    g.addNode('E');
    g.addNode('F');
    g.addNode('G');

    g.addEdge('A', 'B', 2);
    g.addEdge('A', 'C', 1);
    g.addEdge('B', 'D',...