/* * Function: MoreQueueTest * Usage: MoreQueueTest(); * ----------------------- * Tests a few more enqueue, dequeueMax, some boundary cases explored. * Reports results of test to cout. */ void MorePQueueTest() { PQueue pq; cout << boolalpha; cout << endl << "----------- More pqueue testing functions -----------" << endl; cout << endl << "Enqueuing integers from 15 downto 1 (decreasing order)" << endl; for (int i = 15; i > 0; i--) pq.enqueue(i); cout << "Enqueuing duplicates for even numbers 2 to 14" << endl; for (int j = 2; j <= 14; j += 2) pq.enqueue(j); cout << "Dequeuing the top 10 elements: "; for (int k = 0; k < 10; k++) cout << pq.dequeueMax() << " "; cout << endl << "Dequeuing all the rest: "; while (!pq.isEmpty()) cout << pq.dequeueMax() << " "; cout << endl << "Pqueue should be empty. Is it empty? " << pq.isEmpty() << endl; // The line below calling DequeueMax should cause your program to halt with an error. // Once you've verified that your PQueue correctly raises this error // you should comment out the call, so that you can continue on with the other tests. cout << endl << "This next test raises an error if your pqueue is working correctly." << endl; cout << "Once you verify the test, comment it out to move on to the other tests." << endl; cout << "(Comment out line " << __LINE__ + 1 << " in the file " << __FILE__ << ")." << endl; cout << "Dequeue from empty pqueue returns " << pq.dequeueMax() << endl; cout << endl << "Hit return to continue: "; GetLine(); }
/* * Function: MoreQueueTest * Usage: MoreQueueTest(); * ----------------------- * Tests a few more enqueue, dequeueMax, some boundary cases explored. * Reports results of test to cout. */ void MorePQueueTest() { PQueue pq; cout << boolalpha; cout << endl << "----------- More pqueue testing functions -----------" << endl; cout << endl << "Enqueuing integers from 15 downto 1 (decreasing order)" << endl; for (int i = 15; i > 0; i--) pq.enqueue(i); cout << "Enqueuing duplicates for even numbers 2 to 14" << endl; for (int j = 2; j <= 14; j += 2) pq.enqueue(j); cout << "Dequeuing the top 10 elements: "; for (int k = 0; k < 10; k++) cout << pq.dequeueMax() << " "; cout << endl << "Dequeuing all the rest: "; while (!pq.isEmpty()) cout << pq.dequeueMax() << " "; cout << endl << "Pqueue should be empty. Is it empty? " << pq.isEmpty() << endl; }
/* * Function: BasicPQueueTest * Usage: BasicQueueTest(); * ------------------------ * Runs a test of the PQueue focusing on simple enqueue, dequeueMax. * Reports results of test to cout. */ void BasicPQueueTest() { PQueue pq; cout << boolalpha; // configure stream to print booleans as true/false instead of 1/0 cout << endl << "----------- Testing Basic PQueue functions -----------" << endl; cout << "The pqueue was just created. Is it empty? " << pq.isEmpty() << endl; cout << endl << "Now enqueuing integers from 1 to 10 (increasing order)" << endl; for (int i = 1; i <= 10; i++) pq.enqueue(i); cout << "Pqueue should not be empty. Is it empty? " << pq.isEmpty() << endl; cout << "Pqueue should have size = 10. What is size? " << pq.size() << endl; cout << "Dequeuing the top 5 elements: "; for (int j = 0; j < 5; j++) cout << pq.dequeueMax() << " "; cout << endl << "Pqueue should have size = 5. What is size? " << pq.size() << endl; cout << endl << "Dequeuing all the rest: "; while (!pq.isEmpty()) cout << pq.dequeueMax() << " "; cout << endl << "Pqueue should be empty. Is it empty? " << pq.isEmpty() << endl; }
void PQSort(int array[], int nElems) { PQueue pq; for (int i = 0; i < nElems; i++) pq.enqueue(array[i]); for (int i = nElems-1; i >= 0; i--) array[i] = pq.dequeueMax(); }
/* * Function: RunEnqueueDequeueTrial * -------------------------------- * Runs the enqueue & dequeue time trials for the specified * pqueue size. Reports results to cout. * Note that we just randomly choose numbers to insert. * The amount of time it takes to do one enqueue/dequeue is * too small to be accurately measured, so we do many iterations in * a loop and time that. */ void RunEnqueueDequeueTrial(int size) { PQueue pq; for (int i = 0; i < size; i++) pq.enqueue(RandomInteger(1,size)); cout << "Time to enqueue into " << size << "-element pqueue: " << flush; double start = GetCurrentTime(); for (int j = 0; j < NumRepetitions; j++) pq.enqueue(RandomInteger(1, 2*size)); cout << 1000*(GetCurrentTime() - start)/NumRepetitions << " usecs" << endl; cout << "Time to dequeue from " << size << "-element pqueue: " << flush; start = GetCurrentTime(); for (int k = 0; k < NumRepetitions; k++) pq.dequeueMax(); cout << 1000*(GetCurrentTime() - start)/NumRepetitions << " usecs" << endl; }
/* * Function: RunMemoryTrial * ------------------------ * Fills a pqueue to specified size and reports memory usage. Then does * a bunch of enqueue-dequeue operations to jumble things up and reports * on the memory usage again. Reports results to cout. */ void RunMemoryTrial(int size) { PQueue pq; cout << endl << "Running memory trial on " << size << "-element pqueue" << endl; for (int i = 0; i < size; i++) pq.enqueue(RandomInteger(1, size)); cout << "After consecutive enqueues, " << size << "-element pqueue is using " << pq.bytesUsed()/1000 << " KB of memory" << endl; int num = size; for (int j = 0; j < NumRepetitions; j++) { /* do a bunch of enqueue/dequeue ops */ if (RandomChance(.5)) { pq.enqueue(RandomInteger(0, size)); num++; } else { pq.dequeueMax(); num--; } } cout << "After more enqueue/dequeue, " << num << "-element pqueue is using " << pq.bytesUsed()/1000 << " KB of memory" << endl; }
void loadIntoPriorityQueue(PQueue &inputPQueue) // Create and add arrival events to event list { unsigned int tempTime; //temporary holders for cin input unsigned int tempLength; while(cin >> tempTime >> tempLength) //load data into both variables until hits EOF { //cout << "Input #" << currentInputCount << ": Time = " << tempTime << ", Length = " << tempLength << endl; //debug Event tempEvent(tempTime, tempLength); //cout << "created event successfully" << endl; //debug inputPQueue.enqueue(tempEvent); //insert our new event into the queue } //inputPQueue.print(); //debug }
void basicStructuralTests() { beginTest("Basic Structural Tests"); /* This try ... catch system is designed to catch any errors that the * program explicitly generates. It does not guard against runtime * crashes from errors like following a bad pointer, so if your * program crashes and pulls up the debugger, you should be looking * for memory errors. */ try { /* The use of curly braces here introduces a new block scope. We * use this so that we can construct multiple different priority * queues. */ /* Basic test: Add 5 elements to the queue and ensure that * the size is correct at each step. */ { logInfo("These tests will check size() isEmpty() without calling dequeueMin()."); PQueue queue; checkCondition(queue.isEmpty(), "New priority queue should be empty."); checkCondition(queue.size() == 0, "New priority queue should have size 0."); for (int i = 0; i < 5; i++) { queue.enqueue("Test String"); checkCondition(queue.size() == i + 1, "Queue should have proper size after inserting a value."); checkCondition(!queue.isEmpty(), "Queue containing elements should not be empty."); cout<<i<<endl; } } /* Slightly more complex test: Enqueue and dequeue elements, ensuring the * size matches at each step. */ { logInfo("We're about to start calling dequeueMin()."); PQueue queue; for (int i = 0; i < 5; i++) { queue.enqueue("Test String"); } for (int i = 5; i > 0; i--) { checkCondition(queue.size() == i, "Queue should have proper size after dequeues."); checkCondition(!queue.isEmpty(), "Queue should not be empty before all elements are removed."); queue.dequeueMin(); } checkCondition(queue.size() == 0, "After removing all elements, the queue should have size 0."); checkCondition(queue.isEmpty(), "After removing all elements, the queue should be empty."); } /* Getting harder: The value dequeued should always match the value of peek(). */ { logInfo("This next test will check whether peek() matches dequeueMin()."); PQueue queue; for (int i = 0; i < 5; i++) { queue.enqueue(randomString()); } while (!queue.isEmpty()) { string expected = queue.peek(); checkCondition(queue.dequeueMin() == expected, "Value returned by peek() matches value returned by dequeueMin()"); } } /* A different one - let's make sure that peeking at an empty queue causes an * error. */ { PQueue queue; bool didThrow = false; try { logInfo("About to peek into an empty queue. This may cause a crash"); logInfo("if your implementation is incorrect."); queue.peek(); } catch (ErrorException&) { didThrow = true; } checkCondition(didThrow, "Priority queue uses 'error' when peek() called on empty queue."); } /* In the same vein - what happens if we dequeue from an empty queue? */ { PQueue queue; bool didThrow = false; try { logInfo("About to dequeue from an empty queue. This may cause a crash"); logInfo("if your implementation is incorrect."); queue.dequeueMin(); } catch (ErrorException&) { didThrow = true; } checkCondition(didThrow, "Priority queue uses 'error' when dequeueMin() called on empty queue."); } } catch (ErrorException& e) { cout << "TEST FAILURE: Unexpected exception: " << e.getMessage() << endl; } catch (exception& e) { cout << "TEST FAILURE: Unexpected exception: " << e.what() << endl; } catch (...) { cout << "TEST FAILURE: Unknown exception." << endl; } endTest("Basic Structural Tests"); }
void sortCraftedTests() { beginTest("Sort Crafted Tests"); /* This try ... catch system is designed to catch any errors that the * program explicitly generates. It does not guard against runtime * crashes from errors like following a bad pointer, so if your * program crashes and pulls up the debugger, you should be looking * for memory errors. */ try { /* The use of curly braces here introduces a new block scope. We * use this so that we can construct multiple different priority * queues. */ /* First test: Two concatenated sequences of ascending values that * interleave with one another. */ { logInfo("Sorting two sequences that need to be interleaved."); Vector<string> sequence; sequence += string(1, 'A'); sequence += string(1, 'C'); sequence += string(1, 'E'); sequence += string(1, 'G'); sequence += string(1, 'B'); sequence += string(1, 'D'); sequence += string(1, 'F'); sequence += string(1, 'H'); /* Feed this sequence into the priority queue. */ PQueue queue; foreach (string letter in sequence) { queue.enqueue(letter); } /* Dequeue the elements and confirm that they come back sorted. */ for (char ch = 'A'; ch <= 'H'; ch++) { string expected(1, ch); checkCondition(queue.dequeueMin() == expected, "Queue should yield " + expected + "."); } } /* Second test: Two interleaving sequences, alternate version.. */ { logInfo("Sorting two sequences that need to be interleaved, version two."); Vector<string> sequence; sequence += string(1, 'B'); sequence += string(1, 'D'); sequence += string(1, 'F'); sequence += string(1, 'H'); sequence += string(1, 'A'); sequence += string(1, 'C'); sequence += string(1, 'E'); sequence += string(1, 'G'); /* Feed this sequence into the priority queue. */ PQueue queue; foreach (string letter in sequence) { queue.enqueue(letter); } /* Dequeue the elements and confirm that they come back sorted. */ for (char ch = 'A'; ch <= 'H'; ch++) { string expected(1, ch); checkCondition(queue.dequeueMin() == expected, "Queue should yield " + expected + "."); } }
void sortRandomTests() { beginTest("Sort Random Tests"); /* This try ... catch system is designed to catch any errors that the * program explicitly generates. It does not guard against runtime * crashes from errors like following a bad pointer, so if your * program crashes and pulls up the debugger, you should be looking * for memory errors. */ try { /* The use of curly braces here introduces a new block scope. We * use this so that we can construct multiple different priority * queues. */ /* Basic test: Feed the strings H through A into the priority queue in some order, * then confirm that they come back in sorted order */ { logInfo("Enqueuing a random permutation of A - H and checking whether it leaves sorted."); Vector<string> letters; for (char ch = 'A'; ch <= 'H'; ch++) { /* The code * * string(1, ch) * * converts the character ch into a one-character string. */ letters += string(1, ch); } /* Scramble the letters with the STL random_shuffle algorithm. */ random_shuffle(letters.begin(), letters.end()); /* Load the letters into the priority queue. */ PQueue queue; foreach (string letter in letters) queue.enqueue(letter); /* Confirm they come back sorted. */ for (char ch = 'A'; ch <= 'H'; ch++) { string expected(1, ch); checkCondition(queue.dequeueMin() == expected, "Queue should yield " + expected + "."); } } /* Harder test: Sort 10 random strings and confirm that the priority queue hands * them back in the same order. */ { logInfo("Enqueuing 10 random strings and checking whether it leaves sorted."); /* Create 10 random strings. */ Vector<string> randomValues; for (int i = 0; i < 10; i++) { randomValues += randomString(); } /* Feed these values into the priority queue and pull them back out. */ PQueue queue; foreach (string value in randomValues) queue.enqueue(value); /* Confirm each comes back correctly. */ sort(randomValues.begin(), randomValues.end()); for (int i = 0; i < randomValues.size(); i++) { checkCondition(queue.dequeueMin() == randomValues[i], "Expecting to get value " + randomValues[i] + " from queue."); } } /* Much harder test: Sort 10000 random strings and confirm that the priority queue hands * them back in the same order. */ { logInfo("Generating 10000 random strings."); Vector<string> randomValues; for (int i = 0; i < 10000; i++) { randomValues += randomString(); } /* Feed these values into the priority queue and pull them back out. */ logInfo("Enqueuing 10000 random strings."); PQueue queue; foreach (string value in randomValues) queue.enqueue(value); /* Use C++'s provided sorting routine to sort these values. */ logInfo("Sorting 10000 random strings."); sort(randomValues.begin(), randomValues.end(), greater<string>()); /* Confirm each comes back correctly. */ logInfo("Dequeuing 10000 random strings."); bool isCorrect = true; reverse(randomValues.begin(), randomValues.end()); for (int i = 0; i < randomValues.size(); i++) { if (queue.dequeueMin() != randomValues[i]) { isCorrect = false; break; } } checkCondition(isCorrect, "Queue correctly sorted 10000 random strings."); } } catch (ErrorException& e) { cout << "TEST FAILURE: Unexpected exception: " << e.getMessage() << endl; } catch (exception& e) { cout << "TEST FAILURE: Unexpected exception: " << e.what() << endl; } catch (...) { cout << "TEST FAILURE: Unknown exception." << endl; } endTest("Sort Random Tests"); }
int main(void) { Queue bankQueue; //represents the line of customers in the bank/bank line PQueue eventListPQueue; //priority queue eventListPQueue for the event list bool tellerAvailable = true; loadIntoPriorityQueue(eventListPQueue); //load data into Priority Queue from file/Create and add arrival events to event list //waitTime = SUM(time of departure) - SUM(processing time) - SUM(time of arrival)/COUNT(EVENTS) unsigned int sumDepartureTime = 0; unsigned int sumProcessingTime = 0; unsigned int sumArrivalTime = 0; unsigned int eventCount = 0; //track how many customers came in float waitTime; //Calculated at the end cout << "Simulation Begins" << endl; while(!eventListPQueue.isEmpty()) //run while eventListPQueue is not empty { Event newEvent = eventListPQueue.peek(); // Get current time unsigned int currentTime = newEvent.getTime(); // get time of newEvent if (newEvent.getType() == 'A') //check if newEvent is an arrival event { // Processes an arrival event. //processArrival(newEvent, eventListPQueue, bankQueue, tellerAvailable, currentTime); eventListPQueue.dequeue(); //Remove this event from the event list Event customer = newEvent; //customer referenced in arrivalEvent if (bankQueue.isEmpty() && tellerAvailable) { unsigned int departureTime = currentTime + customer.getLength();//currentTime + transaction time in arrivalEvent Event newDepartureEvent('D', departureTime, 0); //a new departure event with departureTime eventListPQueue.enqueue(newDepartureEvent); tellerAvailable = false; } else { bankQueue.enqueue(customer); } cout << "Processing an arrival event at time:\t" << customer.getTime() << endl; eventCount++; //count how many customers arrived sumArrivalTime += customer.getTime(); sumProcessingTime += customer.getLength(); } else { // Processes a departure event. // processDeparture(newEvent, eventListPQueue, bankQueue, tellerAvailable, currentTime); eventListPQueue.dequeue(); // Remove this event from the event list if(!bankQueue.isEmpty()) { // Customer at front of line begins transaction Event customer = bankQueue.peek(); bankQueue.dequeue(); unsigned int departureTime = currentTime + customer.getLength(); //currentTime + transaction time in customer Event newDepartureEvent('D', departureTime, 0); //a new departure event with departureTime eventListPQueue.enqueue(newDepartureEvent); } else { tellerAvailable = true; } cout << "Processing a departure event at time:\t" << currentTime << endl; //temp sumDepartureTime += currentTime; } } waitTime = (float)(sumDepartureTime - sumProcessingTime - sumArrivalTime)/eventCount; //do the average wait time calculation cout << "Simulation Ends\n\n"; cout << "Final Statistics:" << endl; cout << "\tTotal number of people processed: " << eventCount << endl; cout << "\tAverage amount of time spent waiting: " << waitTime << endl; // cout << "Bank Queue Contents:" << endl; // bankQueue.print(); // cout << "Priority Queue Contents:" << endl; // eventListPQueue.print(); // resultPrinterQueue(bankQueue); //print out the results return 0; }