Graph

Assignment 14

by MimiE

HTML

<h3>Assignment 14: "Graph"</h3>
   
  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><br><br>
<input type = "button" onclick = "calculateNow();" value = "Calculate" />
<p id = "nodes"></p>
 <p id = "edges"></p>
 <span id = "result" />

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

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

      // implement - this is designed for a recursive call
      // also if path is defined well - it will contain cost.
    };

    function getNextEdge(from) { //getting next minimum node
      var res, cost = 999;
      if (g.edges[from]['A']) {
        cost = g.edges[from]['A'];
        res = 'A';
      }
      if (g.edges[from]['B'] && g.edges[from]['B'] <= cost) {
        cost = g.edges[from]['B'];
        res = 'B';
      }
      if (g.edges[from]['C'] && g.edges[from]['C'] <= cost) {
        cost = g.edges[from]['C'];
        res = 'C';
      }
      if (g.edges[from]['D'] && g.edges[from]['D'] <= cost) {
        cost = g.edges[from]['D'];
        res = 'D';
      }
      if (g.edges[from]['E'] && g.edges[from]['E'] <= cost) {
        cost = g.edges[from]['E'];
        res = 'E';
      }
      if (g.edges[from]['F'] && g.edges[from]['F'] <= cost) {
        cost = g.edges[from]['F'];
        res = 'F';
     ...