COP3530 Assignment 6 - Queues

by joseph_kanawall2400

HTML

Warning: I ran out of memory in chrome when trying to display the results for 8500. 8000 works fine though.
<br/>
<input type="textbox" id="item_tb" />
<input type="button" id="q1_button" value="Fill Q1" onClick="fillQ1();" />
<br/>
<div id="log"></div>

JavaScript

// Node
var Node = function (value)
{
    this.back = null;
    this.value = value;
}

//Queue
var Queue = function(name)
{
	this.name = name;
	this.head = null;
	this.tail = null;
	this.size = 0;
	
	this.Enqueue = function(value)
	{
		// This is too cut back on calculations later on
		// If a node is added to queue then treat it like
		// enqueueing another queue
		var newNode = null;
		if(value instanceof Node)
		{
			newNode = value;
		}
		else
		{
			newNode = new Node(value);
		}
		
		if(this.head == null)
		{
			this.head = newNode;
			this.tail = this.head;
		}
		else
		{
			this.tail.back = newNode;
			this.tail = newNode;
		}
		this.size++;
	}
	
	this.Dequeue = function()
	{
		var dequeueNode = this.head;
		this.head = this.head.back;
		this.size--;
		return dequeueNode;
	}
	
	this.Clear = function()
	{
		this.head = null;
		this.tail = null;
		this.size = 0;
	}
	
	this.print = function()
	{
		var string = this.name + "{";
		var node = this.head;
		
		if(node != null)
		{
			while(node != null)
			{
				string += node.value + ",";
				node = node.back;
			}
			string = string.replace(/.$/,""); // Replace last comma with empty
		}
		string += "}";
		return string;
	}
}

// Other Functions
function fillQ1()
{
	var item = document.getElementById('item_tb');
	q1.Clear();
	q2.Clear();
	
	if(isNaN(item.value) || item.value < 3)
	{
		alert("Please enter a valid number above 2 (3-infinity)");
	}
	else
	{
		for(i = 2; i <= item.value; i++)
		{
			q1.Enqueue(i);
		}
	}
	
	item.value = "";
	document.getElementById('log').innerHTML = "";
	FilterPrimes();
}

function FilterPrimes()
{
	var counter = 0;
	AddToLog("~~~ Iteration " + counter + "~~~");
	
	var lastValue = q1.tail.value;
	
	do
	{
		var node = q1.Dequeue();
		
		// If node.value^2 is greater than lastValue then all numbers left in q1 are primes.
		// Pulled from https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
		if(node.value * node.value >...