Networks

Assignment 15

by Jake Jernigan

HTML

<p id="nodes"></p>
<br/>
<p id="edges"></p>

JavaScript

var Node = function(_id, _name) {
    this.id = _id;
    this.name = _name;
    this.edges = [];
    return this;
}

var Edge = function(_from, _to, _cost) {
    this.from = null;
    this.to = null;
    this.cost = null;
    return this;
}

var Graph = function() {

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

    this.addNode = function(_id, _name) {
        var node = new Node(_id, _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);

        return edge;
    }

    this.printNodes = function() {
        this.printBonds = function(i) {
            var str = "";
            for (var j = 0; j < this.edges.length; j++) {
    	          if (this.edges[j].from.id == this.nodes[i].id) {
      	            str += this.edges[j].to.name + " ";
                }
                else if (this.edges[j].to.id == this.nodes[i].id) {
      	            str += this.edges[j].from.name + " ";
                }
            }
            return str;
        }
        
        var s = "Graph of Caffeine Molecule: <br/><br/>";
        for (var i = 0; i < this.nodes.length; i++) {
            s = s + this.nodes[i].name + " " + "( " + this.printBonds(i) + ")" + "</br>";
        }
        return s;
    }

    this.printEdges = function() {
        var s = "Bond Costs in Caffeine Molecule: <br/><br/>";
        for (var i = 0; i < this.edges.length; i++) {
            s += "Bond: " + (i + 1) + "   From: " + this.edges[i].from.name + "   To: " + this.edges[i].to.name + "   Cost: " + this.edges[i].cost + "</br>";
        }
        return s;
    }
}

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

    var c1 = graph.addNode("0", "C");
    var c2 = graph.addNode("1", "C");
    var c3 = graph.addNode("2", "C");
    var c4 =...