COP3530 Assignment 15 - Networks

by joseph_kanawall2400

HTML

<div id="output"/>

JavaScript

function Node(id, value)
{
	this.id = id;
	this.content = value;
	this.edges = [];
	
	this.addEdge = function(otherNode, cost)
	{
		this.edges.push({"node": otherNode, "cost": cost});
	}
	
	this.toString = function()
	{
		return this.content + " (" + this.edges.map(function(item) {return item.node.content}).sort().join(", ") + ")";
	}
	
	this.printEdges = function()
	{
		var str = this + "\n";
		for(i = 0; i < this.edges.length; i++)
		{
			str += " |-- to: " + this.edges[i].node + ", cost: " + this.edges[i].cost + "\n";
		}
		return str;
	}
}

function Graph()
{
	this.idCount = 0;
	this.nodes = {};
	
	this.add = function(value)
	{
		var newNode = new Node(this.idCount, value);
		this.nodes[newNode.id] = newNode;
		this.idCount++;
		return newNode;
	}
	
	this.connect = function(node1, node2, cost)
	{
		node1.addEdge(node2, cost);
		node2.addEdge(node1, cost);
	}
	
	this.toString = function()
	{
		var strAry = [];
		for(var key in this.nodes)
		{
			strAry.push(this.nodes[key].toString());
		}
		return strAry.sort(customSort).sort(sortAtom).join("\n");
	}
}

function sortAtom(x, y)
{
	var atomOrder = ["O", "H", "N", "C"];
	var xn = atomOrder.indexOf(x[0]);
	var yn = atomOrder.indexOf(y[0]);
	return (xn < yn) ? -1 : (xn > yn) ? 1: 0;
}

// Sort function came from http://mozgovipc.blogspot.com/2010/11/jquery-javascript-how-to-sort-string.html
// this makes everything nice and tidey
function customSort(x,y)
{
	if(x.length != y.length)
	{
		return x.length - y.length;
	}
	return (x < y) ? -1 : (x > y) ? 1 : 0;
}

var graph = new Graph();
var h1 = graph.add("H");
var h2 = graph.add("H");
var h3 = graph.add("H");
var h4 = graph.add("H");
var h5 = graph.add("H");
var h6 = graph.add("H");
var h7 = graph.add("H");
var h8 = graph.add("H");
var h9 = graph.add("H");
var h10 = graph.add("H");

var c1 = graph.add("C");
var c2 = graph.add("C");
var c3 = graph.add("C");
var c4 = graph.add("C");
var c5 = graph.add("C");
var c6 = graph.add("C");
var c7 = graph.add("C");
var c8 =...