// CMSC 341 - Fall 2024 - Project 3
#include "mqueue.h"
//Constructor
MQueue::MQueue(prifn_t priFn, HEAPTYPE heapType, STRUCTURE structure)
{
//skew-heap or leftist-heap based on input
m_heapType = heapType;
//min-heap or max-heap based on input
m_structure = structure;
//priority
m_priorFunc = priFn;
//no heap or heap elements exist yet
m_heap = nullptr;
m_size = 0;
}
//Destructor
MQueue::~MQueue()
{
clear();
}
void MQueue::clear() {
clearHelper(m_heap);
m_heap = nullptr;
m_size = 0;
}
//Copy Constructor
MQueue::MQueue(const MQueue& rhs)
{
//skew or leftist heap
m_heapType = rhs.m_heapType;
//min or max heap
m_structure = rhs.m_structure;
//priority
m_priorFunc = rhs.m_priorFunc;
//copy size
m_size = rhs.m_size;
//check if rhs is empty first
if(rhs.m_heap == nullptr) {
m_heap = nullptr;
} else {
//deep copy of rhs
m_heap = copy(rhs.m_heap);
}
}
//Creates an exact copy of rhs
MQueue& MQueue::operator=(const MQueue& rhs) {
//Self assignment check & clearing currrent heap data
if(this != &rhs) {
clear();
m_size = rhs.m_size;
m_priorFunc = rhs.m_priorFunc;
m_heapType = rhs.m_heapType;
m_structure = rhs.m_structure;
//deep copy the heap nodes
m_heap = copy(rhs.m_heap);
}
return *this;
}
void MQueue::mergeWithQueue(MQueue& rhs) {
//checking if they are same queue
//no self merging
if(this == &rhs) {
throw domain_error("No self merging!");
}
//compataiblity check
if(m_priorFunc != rhs.m_priorFunc) {
throw domain_error("Incompataible priority!");
}
if(m_structure != rhs.m_structure) {
throw domain_error("Incompataible structures!");
}
//Merge depending on leftist or skew
if(m_structure == LEFTIST){
mergeLeft(m_heap, rhs.m_heap);
} else {
mergeSkew(m_heap,rhs.m_heap);
}
//resetting rhs to empty state
rhs.m_heap = nullptr;
//updating size after merging
m_size += rhs.m_size;
rhs.m_size = 0;
}
bool MQueue::insertOrder(const Order& order) {
//get priority using priority function given
int prio = m_priorFunc(order);
//check if it's a valid order zero it's not valid
//we dont insert.
if(prio == 0) {
return false;
}
//new node for the order
Node* newNode = new Node(order);
//Insert node depending on the heap/structure
if(m_structure == LEFTIST) {
//Initial NPL Value
newNode->setNPL(0);
m_heap = mergeLeft(m_heap, newNode);
} else if (m_structure == SKEW){
m_heap = mergeSkew(m_heap, newNode);
}
//Inc size of queue when inserting.
m_size++;
return true;
}
int MQueue::numOrders() const
{
return m_size;
}
prifn_t MQueue::getPriorityFn() const {
return m_priorFunc;
}
Order MQueue::getNextOrder() {
//heap is empty
if (m_heap == nullptr){
throw out_of_range("Queue is empty!");
}
//Holding highest prio order to return
Order highestPrioOrder = m_heap->m_order;
//merge left& right sub-heaps to form a new root
Node* oldRoot = m_heap;
if(m_heapType == MINHEAP){
mergeLeft(m_heap->m_left, m_heap->m_right);
}else {
mergeSkew(m_heap->m_left,m_heap->m_right);
}
//Free memory of the old root.
//Also updating the size since we're remmoving
delete oldRoot;
m_size--;
return highestPrioOrder;
}
void MQueue::setPriorityFn(prifn_t priFn, HEAPTYPE heapType) {
//base case we dont make changes nothing to change
if(m_priorFunc == priFn && m_heapType == heapType) {
return;
}
int size = m_size;
int i = 0;
//extract nodes inmto array
Node** nodes = new Node*[size];
extract(m_heap,nodes,i);
clear();
//set the new prio func and heap
m_priorFunc = priFn;
m_heapType = heapType;
//new heap root
Node* nHeap = nullptr;
//rebuild heap based on typ
for(int i =0; i < size; i++) {
if(heapType == MINHEAP) {
nHeap = mergeLeft(nHeap , nodes[i]);
} else {
nHeap = mergeSkew(nHeap, nodes[i]);
}
}
// assign new heap root to be our new root
m_heap = nHeap;
m_size = size;
delete[] nodes;
}
HEAPTYPE MQueue::getHeapType() const
{
return m_heapType;
}
void MQueue::setStructure(STRUCTURE structure)
{
//check current structure
if(m_structure == structure) {
//dont need to do anything since already same
return;
}
//need size since it will be cleared later
int size = m_size;
int i = 0;
//allocate array of node pointers
Node** nodes = new Node*[size];
//extract the nodes into our array
extract(m_heap,nodes,i);
//after extracting we clear our heap to ensure to remnants/frags
clear();
//best to start with an empty heap
Node* nHeap = nullptr;
//rebuild our structure
for(int i =0; i < size; i++) {
if(structure == LEFTIST) {
nHeap = mergeLeft(nHeap,nodes[i]);
} else {
nHeap = mergeSkew(nHeap, nodes[i]);
}
}
//update and free memory
m_heap = nHeap;
delete[] nodes;
m_structure = structure;
}
STRUCTURE MQueue::getStructure() const {
return m_structure;
}
void MQueue::printOrderQueue() const {
cout <<"Contents of the queue: " << endl;
preOrder(m_heap);
}
void MQueue::dump() const {
if (m_size == 0) {
cout << "Empty heap.\n" ;
} else {
dump(m_heap);
}
cout << endl;
}
void MQueue::dump(Node *pos) const {
if ( pos != nullptr ) {
cout << "(";
dump(pos->m_left);
if (m_structure == SKEW)
cout << m_priorFunc(pos->m_order) << ":" << pos->m_order.m_customer;
else
cout << m_priorFunc(pos->m_order) << ":" << pos->m_order.m_customer << ":" << pos->m_npl;
dump(pos->m_right);
cout << ")";
}
}
ostream& operator<<(ostream& sout, const Order& order) {
sout << "Customer: " << order.getCustomer()
<< ", importance: " << order.getImportance()
<< ", quantity: " << order.getQuantity()
<< ", order placement time: " << order.getFIFO();
return sout;
}
ostream& operator<<(ostream& sout, const Node& node) {
sout << node.m_order;
return sout;
}
Node *MQueue::copy(Node node)
{
//Base case
if (node == nullptr){
return nullptr;
}
//New node with same data as our current node
Node newNode = new Node(node->m_order);
//copy left and right children
newNode->m_left = copy(node->m_left);
newNode->m_right = copy(node-> m_right);
//only do this if it's a leftist heap
if(m_structure == LEFTIST){
newNode->m_npl = node->m_npl;
}
//return root of the copied tree
return newNode;
}
Node *MQueue::mergeLeft(Node *p1, Node *p2)
{
//Base case
// either heap is null return other heap
if(p1 == nullptr){
return p2;
}
if(p2 == nullptr){
return p1;
}
//Making sure p1 has higher priority
if(comparePrio(p1->getOrder(), p2->getOrder()) < 0) {
swap(p1,p2);
}
//Merge p2 with the right child of p1
p1->m_right = mergeLeft(p1->m_right, p2);
//Check for leftist property first
//Meaning left npl >= right npl
if(p1->m_left == nullptr) {
//Left child is null here so we swap left and right child
//To keep leftist property
p1->m_left = p1->m_right;
p1->m_right = nullptr;
} else if (p1->m_right != nullptr) {
//Both children exist
if(p1->m_left->getNPL() < p1->m_right->getNPL()) {
swap(p1->m_left,p1->m_right);
}
}
int leftNpl = p1->m_left ? p1->m_left->getNPL() : -1; // -1 if left is null
int rightNpl = p1->m_right ? p1->m_right->getNPL() : -1; // -1 if right is null
p1->m_npl = 1 + min(leftNpl, rightNpl); // Update NPL based on children
return p1;
}
Node *MQueue::mergeSkew(Node *p1, Node *p2)
{
//Base case either heap is null return other
if(p1 == nullptr) {
return p2;
}
if(p2 == nullptr) {
return p1;
}
//Making sure p1 has higher priority
if(comparePrio(p1->getOrder(), p2->getOrder()) < 0) {
swap(p1, p2);
}
//Merge p2 with right chiild of p1
p1->m_right = mergeSkew(p1->m_right,p2);
//swap left and right child to maintain skew properites
swap(p1->m_left,p1->m_right);
return p1;
}
int MQueue::comparePrio(const Order &order1, const Order &order2) const
{
int prio1 = m_priorFunc(order1);
int prio2 = m_priorFunc(order2);
//Max heap
if(m_heapType == MAXHEAP) {
if(prio1 > prio2){
return 1;
}
if(prio1 < prio2) {
return -1;
}
//Theyre equal
return 0;
} else {
//Min heap
if(prio1 < prio2) {
return 1;
}
if( prio1 > prio2){
return -1;
}
return 0;
}
}
void MQueue::clearHelper(Node *Node)
{
//Base case
if(Node == nullptr) {
return;
}
//we delete nodes left and right recursively
clearHelper(Node->m_left);
clearHelper(Node->m_right);
delete Node;
}
void MQueue::extract(Node *node, Node **array, int &i)
{
//no nodes left to store
if(node == nullptr) {
return;
}
//store current node in the array
array[i++] = node;
//recursively go left & right children
extract(node->m_left, array,i);
extract(node->m_right,array,i);
}
void MQueue::preOrder(Node *node) const
{
//base case
//no more nodes to traverse
if(node == nullptr) {
return;
cout << "[" << m_priorFunc(node->getOrder()) << "]"
<< "Customer: " << node->getOrder().getCustomer()
<< ", importance: " << node->getOrder().getImportance()
<< ", quantity: " << node->getOrder().getQuantity()
<<", order placement time: " << node->getOrder().getProcessTime()
<< endl;
}
}
/* void MQueue::swap(Node *&a, Node &b)
{
Node temp = a;
a = b;
b = temp;
}
*/
this is my mqueue.cpp
// CMSC 341 - Fall 2024 - Project 3
#include "mqueue.h"
#include <math.h>
#include
#include
#include
using namespace std;
enum RANDOM {UNIFORMINT, UNIFORMREAL, NORMAL, SHUFFLE};
class Random {
public:
Random(){}
Random(int min, int max, RANDOM type=UNIFORMINT, int mean=50, int stdev=20) : m_min(min), m_max(max), m_type(type)
{
if (type == NORMAL){
//the case of NORMAL to generate integer numbers with normal distribution
m_generator = std::mt19937(m_device());
//the data set will have the mean of 50 (default) and standard deviation of 20 (default)
//the mean and standard deviation can change by passing new values to constructor
m_normdist = std::normal_distribution<>(mean,stdev);
}
else if (type == UNIFORMINT) {
//the case of UNIFORMINT to generate integer numbers
// Using a fixed seed value generates always the same sequence
// of pseudorandom numbers, e.g. reproducing scientific experiments
// here it helps us with testing since the same sequence repeats
m_generator = std::mt19937(10);// 10 is the fixed seed value
m_unidist = std::uniform_int_distribution<>(min,max);
}
else if (type == UNIFORMREAL) { //the case of UNIFORMREAL to generate real numbers
m_generator = std::mt19937(10);// 10 is the fixed seed value
m_uniReal = std::uniform_real_distribution((double)min,(double)max);
}
else { //the case of SHUFFLE to generate every number only once
m_generator = std::mt19937(m_device());
}
}
void setSeed(int seedNum){
// we have set a default value for seed in constructor
// we can change the seed by calling this function after constructor call
// this gives us more randomness
m_generator = std::mt19937(seedNum);
}
void init(int min, int max){
m_min = min;
m_max = max;
m_type = UNIFORMINT;
m_generator = std::mt19937(10);// 10 is the fixed seed value
m_unidist = std::uniform_int_distribution<>(min,max);
}
void getShuffle(vector & array){
// this function provides a list of all values between min and max
// in a random order, this function guarantees the uniqueness
// of every value in the list
// the user program creates the vector param and passes here
// here we populate the vector using m_min and m_max
for (int i = m_min; i<=m_max; i++){
array.push_back(i);
}
shuffle(array.begin(),array.end(),m_generator);
}
void getShuffle(int array[]){
// this function provides a list of all values between min and max
// in a random order, this function guarantees the uniqueness
// of every value in the list
// the param array must be of the size (m_max-m_min+1)
// the user program creates the array and pass it here
vector<int> temp;
for (int i = m_min; i<=m_max; i++){
temp.push_back(i);
}
std::shuffle(temp.begin(), temp.end(), m_generator);
vector<int>::iterator it;
int i = 0;
for (it=temp.begin(); it != temp.end(); it++){
array[i] = *it;
i++;
}
}
int getRandNum(){
// this function returns integer numbers
// the object must have been initialized to generate integers
int result = 0;
if(m_type == NORMAL){
//returns a random number in a set with normal distribution
//we limit random numbers by the min and max values
result = m_min - 1;
while(result < m_min || result > m_max)
result = m_normdist(m_generator);
}
else if (m_type == UNIFORMINT){
//this will generate a random number between min and max values
result = m_unidist(m_generator);
}
return result;
}
double getRealRandNum(){
// this function returns real numbers
// the object must have been initialized to generate real numbers
double result = m_uniReal(m_generator);
// a trick to return numbers only with two deciaml points
// for example if result is 15.0378, function returns 15.03
// to round up we can use ceil function instead of floor
result = std::floor(result*100.0)/100.0;
return result;
}
string getRandString(int size){
// the parameter size specifies the length of string we ask for
// to use ASCII char the number range in constructor must be set to 97 - 122
// and the Random type must be UNIFORMINT (it is default in constructor)
string output = "";
for (int i=0;i<size;i++){
output = output + (char)getRandNum();
}
return output;
}
int getMin(){return m_min;}
int getMax(){return m_max;}
private:
int m_min;
int m_max;
RANDOM m_type;
std::random_device m_device;
std::mt19937 m_generator;
std::normal_distribution<> m_normdist;//normal distribution
std::uniform_int_distribution<> m_unidist;//integer uniform distribution
std::uniform_real_distribution<double> m_uniReal;//real uniform distribution
};
int priorityFn1(const Order &order);
int priorityFn2(const Order &order);
class Tester{};
int main() {
Random nameGen(97,122);
Random FIFO(MINONE,MAX50); Random processTime(MINONE,MAX12);
Random dueTime(MINONE,MAX12); Random slackTime(MINONE,MAX12);
Random material(MINZERO,MAX100); Random importance(MINONE,MAX100);
Random workers(MAX100,MAX200); Random quantity(MIN1000,MAX10000);
MQueue queue1(priorityFn2, MINHEAP, LEFTIST);
for (int i=0;i<8;i++){
Order order(nameGen.getRandString(5),
FIFO.getRandNum(), processTime.getRandNum(),
dueTime.getRandNum(), slackTime.getRandNum(),
material.getRandNum(), importance.getRandNum(),
workers.getRandNum(), quantity.getRandNum());
queue1.insertOrder(order);
}
cout << "\nDump of the leftist heap queue with priorityFn2 (MINHEAP):\n";
queue1.dump();
queue1.setStructure(SKEW);
cout << "\nDump of the skew heap queue with priorityFn2 (MINHEAP):\n";
queue1.dump();
cout << "\nPreorder traversal of the nodes in the queue with priorityFn2 (MINHEAP):\n";
queue1.printOrderQueue();
queue1.setPriorityFn(priorityFn1, MAXHEAP);
cout << "\nDump of the skew queue with priorityFn1 (MAXHEAP):\n";
queue1.dump();
return 0;
}
/* Priority functions */
int priorityFn1(const Order & order) {
//this function works with a MAXHEAP
//priority value is determined based on some criteria
//priority value falls in the range [1101-10400]
int minValue = MIN1000 + MAX100 + MINONE + MINZERO;
int maxValue = MAX100 + MAX100 + MAX200 + MAX10000;
//the larger value means the higher priority
int priority = order.getMaterial() + order.getImportance() +
order.getWorkForce() + order.getQuantity();
if (priority >= minValue && priority <= maxValue)
return priority;
else
return 0; // this is an invalid order object
}
int priorityFn2(const Order & order) {
//this function works with a MINHEAP
//priority value is determined based on some criteria
//priority value falls in the range [4-86]
int minValue = MINONE + MINONE + MINONE + MINONE;
int maxValue = MAX12 + MAX12 + MAX12 + MAX50;
//the smaller value means the higher priority
int priority = order.getFIFO() + order.getProcessTime() +
order.getDueTime() + order.getSlackTime();
if (priority >= minValue && priority <= maxValue)
return priority;
else
return 0; // this is an invalid order object
}
is the driver.cPP
// CMSC 341 - Fall 2024 - Project 3
#ifndef MQUEUE_H
#define MQUEUE_H
#include
#include
#include
using namespace std;
using std::out_of_range;
class Grader; // forward declaration (for grading purposes)
class Tester; //forward declaration
class MQueue; //forward declaration
class Order; //forward declaration
// Constant parameters, min and max values
const int MINZERO = 0;
const int MINONE = 1;
const int MIN1000 = 1000;
const int MAX12 = 12;
const int MAX50 = 50;
const int MAX100 = 100;
const int MAX200 = 200;
const int MAX10000 = 10000;
#define DEFAULTCUSTOMER "NONAME"
enum HEAPTYPE {MINHEAP, MAXHEAP};
enum STRUCTURE {SKEW, LEFTIST};
// Priority function pointer type
typedef int (*prifn_t)(const Order&);
//
// order class
//
class Order {
public:
friend class Grader; // for grading purposes
friend class Tester; // for testing purposes
friend class MQueue;
Order(){
m_customer=DEFAULTCUSTOMER; m_FIFO=0; m_processTime=0;
m_dueTime=0; m_slackTime=0; m_material=0;
m_importance=0; m_workForce=0; m_quantity=0;
}
Order(string customer, int FIFO, int process, int due, int slack,int material, int importance, int workers, int quantity) {
m_customer=customer; m_FIFO=FIFO; m_processTime=process;
m_dueTime=due; m_slackTime=slack; m_material=material;
m_importance=importance; m_workForce=workers; m_quantity=quantity;
}
string getCustomer() const {return m_customer;}
int getFIFO() const {return m_FIFO;}
int getProcessTime() const {return m_processTime;}
int getDueTime() const {return m_dueTime;}
int getSlackTime() const {return m_slackTime;}
int getMaterial() const {return m_material;}
int getImportance() const {return m_importance;}
int getWorkForce() const {return m_workForce;}
int getQuantity() const{return m_quantity;}
// Overloaded insertion operator
friend ostream& operator<<(ostream& sout, const Order& order);
private:
string m_customer;//customer name
// m_FIFO is an integer indicating in what order customers placed their orders
// it takes a value between 1 and 50, at any time the plant only accepts 50 orders at max
// therefore this value cannot go beyond 50
// a value of 1 means this was the first customer who placed the order
// a value of 50 means this was the 50th customer who placed the order
int m_FIFO;// (ordinal position) = 1(higher) - 50(lower)
int m_processTime;// (month) = 1(higher) - 12(lower)
int m_dueTime;// (month) = 1(higher) - 12(lower)
int m_slackTime;// (month) = 1(higher) - 12(lower)
int m_material;//material availability, (percentage) = 100(higher) - 0(lower)
int m_importance;// customer importance (percentage) = 100(higher) - 1(lower)
int m_workForce;// work force availability, (person count) = 200(higher) - 100(lower)
int m_quantity;//quantity of the order, (unit count) = 10000(higher) - 1000(lower)
};
class Node {
public:
friend class Grader; // for grading purposes
friend class Tester; // for testing purposes
friend class MQueue;
Node(Order order) {
m_order = order;
m_right = nullptr;
m_left = nullptr;
m_npl = 0;
}
void setNPL(int npl) {m_npl = npl;}
int getNPL() const {return m_npl;}
Order getOrder() const {return m_order;}
// Overloaded insertion operator
friend ostream& operator<<(ostream& sout, const Node& node);
private:
Order m_order; // order information
Node * m_right; // right child
Node * m_left; // left child
int m_npl; // null path length for leftist heap
};
class MQueue {
public:
// stores the skew/leftist heap, minheap/maxheap
friend class Grader; // for grading purposes
friend class Tester; // for testing purposes
MQueue(){}
MQueue(prifn_t priFn, HEAPTYPE heapType, STRUCTURE structure);
~MQueue();
void clear();
MQueue(const MQueue& rhs);
MQueue& operator=(const MQueue& rhs);
bool insertOrder(const Order& input);
Order getNextOrder();
void mergeWithQueue(MQueue& rhs);
int numOrders() const;
// The following function prints the queue using preorder traversal.
// Although the first order printed should have the highest priority,
// the remaining orders will not necessarily be in priority order.
void printOrderQueue() const;
prifn_t getPriorityFn() const;
// Set a new priority function. Must rebuild the heap!!!
void setPriorityFn(prifn_t priFn, HEAPTYPE heapType);
HEAPTYPE getHeapType() const;
STRUCTURE getStructure() const;
// Set a new data structure (skew/leftist). Must rebuild the heap!!!
void setStructure(STRUCTURE structure);
void dump() const; // For debugging purposes
private:
Node * m_heap; // Pointer to root of skew heap
int m_size; // Current size of the heap
prifn_t m_priorFunc; // Function to compute priority
HEAPTYPE m_heapType; // MINHEAP or MAXHEAP
STRUCTURE m_structure; // skew heap or leftist heap
void dump(Node *pos) const; // helper function for dump
/******************************************
* Private function declarations go here! *
******************************************/
//Help recursively copy each node.
Node* copy(Node* node);
//Merge leftist-heap
Node* mergeLeft(Node* p1, Node* p2);
//Merge a skew-heap
Node*mergeSkew(Node* p1, Node* p2);
//Compare priority of two nodes
int comparePrio(const Order& order1, const Order& order2)const;
//Helper function for deleting nodes in heap.
void clearHelper(Node* Node);
//helper function to help extract nodes
void extract(Node* node, Node** array, int& i);
//helper to traverse in pre-order for printing
void preOrder(Node* node) const;
// void swap(Node*& a, Node*& b);
};
#endif
is the mqueue.h
#include "mqueue.h"
#include
#include
class Tester
{
private:
static int getImportance(const Order& order) {return order.getImportance();}
Order genRandomOrder();
bool heapProperties(Node** nodes, int numNodes,HEAPTYPE heapType, STRUCTURE structureType);
public:
bool testInsertionMinHeap();
bool testConstructor();
bool testCopyConstructor();
bool testCopyConstructorEmpty();
bool testCopyConstructorNotEmpty();
bool testAssignmentOperator();
bool testAssignmentOperatorEdgeCase();
bool testDestructor();
};
//Main function to run tests in
int main() {
Tester tester;
bool constructorResult = tester.testConstructor();
cout << (constructorResult ? "Constructor test passed\n" : "Constructor test failed\n") << endl;
bool copyConstructorResult = tester.testCopyConstructor();
cout << (copyConstructorResult ? "Copy constructor test passed\n" : "Copy constructor test failed\n") << endl;
bool copyConstructorEmptyResult = tester.testCopyConstructorEmpty();
cout << (copyConstructorEmptyResult ? "Copy constructor empty test passed\n" : "Copy constructor empty test failed\n") << endl;
bool copyConstructorNotEmptyResult = tester.testCopyConstructorNotEmpty();
cout << (copyConstructorNotEmptyResult ? "Copy constructor not empty test passed\n" : "Copy constructor not empty test failed\n") << endl;
bool assignmentOperatorResult = tester.testAssignmentOperator();
cout << (assignmentOperatorResult ? "Assignment operator test passed\n" : "Assignment operator test failed\n") << endl;
// still need to fix?
bool destructorResult = tester.testDestructor();
cout << (destructorResult ? "Destructor test passed\n" : "Destructor test failed\n") << endl;
bool insertionMinHeapResult = tester.testInsertionMinHeap();
cout << (insertionMinHeapResult ? "Insertion min heap test passed\n" : "Insertion min heap test failed\n") << endl;
}
//Leftist insertion of a min heap
bool Tester::testInsertionMinHeap()
{
// Create an MQueue instance with specific heap type and structure
MQueue testQueue(getImportance, MAXHEAP, LEFTIST);
// Insert 300 orders into the queue
for (int i = 0; i < 20; i++) {
Order randomOrder = genRandomOrder();
testQueue.insertOrder(randomOrder);
cout << "Inserted order: " << randomOrder << endl;
cout << "Priority: " << testQueue.getPriorityFn() << endl;
}
//Check there's actually 300 orders in the queue
bool numOrders = (testQueue.numOrders() == 300);
//Check the heap properties of the queue
Node* nodes[20];
int numNodes = 0;
testQueue.extract(testQueue.m_heap, nodes, numNodes);
bool validMinHeap = heapProperties(nodes, numNodes, testQueue.getHeapType(), testQueue.getStructure());
testQueue.dump();
// Return true if all conditions pass false otherwise
return numOrders && validMinHeap;
}
bool Tester::testConstructor()
{
// Create an MQueue instance with specific heap type and structure
MQueue testQueue(getImportance, MINHEAP, LEFTIST);
// Check initial conditions for MQueue
bool CorrectPrioFn = (testQueue.getPriorityFn() == getImportance);
bool CorrectHeapType = (testQueue.getHeapType() == MINHEAP);
bool CorrectStructure = (testQueue.getStructure() == LEFTIST);
bool isEmpty = (testQueue.numOrders() == 0);
// Return true if all conditions pass false otherwise
return CorrectPrioFn && CorrectHeapType && CorrectStructure && isEmpty;
}
bool Tester::testCopyConstructor()
{
// Create an MQueue instance with specific heap type and structure
MQueue testQueue(getImportance, MAXHEAP, LEFTIST);
// Insert some orders into the original queue
for (int i = 0; i < 50; i++) {
Order randomOrder = genRandomOrder();
testQueue.insertOrder(randomOrder);
}
// Create a copy of the original queue using the copy constructor
MQueue copiedQueue(testQueue);
// Verify that the copied queue has the same state as the original queue
bool SamePrioFn = (copiedQueue.getPriorityFn() == testQueue.getPriorityFn());
bool SameHeapType = (copiedQueue.getHeapType() == testQueue.getHeapType());
bool SameStructure = (copiedQueue.getStructure() == testQueue.getStructure());
bool SameNumOrders = (copiedQueue.numOrders() == testQueue.numOrders());
//Create the string streams to compare the dumps
stringstream testQueueDump, copiedQueueDump;
// Redirect cout to the string streams
streambuf* oldCoutBuffer = cout.rdbuf();
cout.rdbuf(testQueueDump.rdbuf());
testQueue.dump();
// Restore cout tphe original state
cout.rdbuf(oldCoutBuffer);
streambuf* oldCoutBuffer2 = cout.rdbuf();
cout.rdbuf(copiedQueueDump.rdbuf());
copiedQueue.dump();
cout.rdbuf(oldCoutBuffer2);
//String streams should now have both dumps in them
//Check if they are the same
bool sameCopyDump = (testQueueDump.str() == copiedQueueDump.str());
// Return true if all conditions pass false otherwise
return SamePrioFn && SameHeapType && SameStructure && SameNumOrders && sameCopyDump;
}
bool Tester::testCopyConstructorEmpty()
{
//Create an Mqueue instance with specific heap type and structure
MQueue testQueue(getImportance, MAXHEAP, SKEW);
//Create a copy of the original queue using the copy constructor
MQueue copiedQueue(testQueue);
//Verify that the copied queue is empty
bool SameHeapType = (copiedQueue.getHeapType() == testQueue.getHeapType());
bool SameStructure = (copiedQueue.getStructure() == testQueue.getStructure());
bool isEmpty = (copiedQueue.numOrders() == 0);
//Return true if the copied queue is empty false otherwise
return isEmpty && SameStructure && SameHeapType;
}
bool Tester::testCopyConstructorNotEmpty()
{
//Create an Mqueue instance with specific heap type and structure
MQueue testQueue(getImportance, MINHEAP, LEFTIST);
//Insert some orders into the original queue
for(int i = 0; i < 50; i++) {
Order randomOrder = genRandomOrder();
testQueue.insertOrder(randomOrder);
}
//Create a copy of the original queue using the copy constructor
MQueue copiedQueue(testQueue);
//Verify that the copied queue has the same state as the original queue
bool SamePrioFn = (copiedQueue.getPriorityFn() == testQueue.getPriorityFn());
bool SameHeapType = (copiedQueue.getHeapType() == testQueue.getHeapType());
bool SameStructure = (copiedQueue.getStructure() == testQueue.getStructure());
bool SameNumOrders = (copiedQueue.numOrders() == testQueue.numOrders());
//Return true if all conditions pass false otherwise
return SamePrioFn && SameHeapType && SameStructure && SameNumOrders;
}
bool Tester::testAssignmentOperator()
{
//Create an Mqueue instance with specific heap type and structure
MQueue testQueue(getImportance, MAXHEAP, SKEW);
//Insert some orders into the original queue
for(int i = 0; i < 100; i++) {
Order randomOrder = genRandomOrder();
testQueue.insertOrder(randomOrder);
}
//We use the assignment operator to copy the testQueue to another queue
MQueue assignedQueue = testQueue;
//Verify that the assigned queue has the same state as the original queue
bool SamePrioFn = (assignedQueue.getPriorityFn() == testQueue.getPriorityFn());
bool SameHeapType = (assignedQueue.getHeapType() == testQueue.getHeapType());
bool SameStructure = (assignedQueue.getStructure() == testQueue.getStructure());
bool SameNumOrders = (assignedQueue.numOrders() == testQueue.numOrders());
//Creating arrays to hold nodes from each queue
int i =0;
int numNodes = testQueue.numOrders();
Node* testQueueNodes[numNodes];
Node* assignedQueueNodes[numNodes];
//Populate the arrays with the nodes from each queue
testQueue.extract(testQueue.m_heap, testQueueNodes, i);
//Then reset the index for the assigned queue
i = 0;
assignedQueue.extract(assignedQueue.m_heap, assignedQueueNodes, i);
//Check what we extracted into the arrays follows heap properties
bool testQueueHeapProperties = heapProperties(testQueueNodes, numNodes,testQueue.getHeapType(), testQueue.getStructure());
bool assignedQueueHeapProperties = heapProperties(assignedQueueNodes, numNodes, assignedQueue.getHeapType(), assignedQueue.getStructure());
//Return true if all conditions pass false otherwise
return SamePrioFn && SameHeapType && SameStructure && SameNumOrders && testQueueHeapProperties && assignedQueueHeapProperties;
}
bool Tester::testDestructor()
{
// Create an MQueue instance with specific heap type and structure
MQueue* testQueue = new MQueue(getImportance, MAXHEAP, LEFTIST);
//Insert orders into the queue
for(int i = 0; i < 50; i++) {
Order randomOrder = genRandomOrder();
testQueue->insertOrder(randomOrder);
}
//Store the number of orders in the queue
int numOrders = testQueue->numOrders();
//Then we delete the queue to call the destructor
delete testQueue;
//We expect 5 orders to have been added to the queue
//Can't really check i guess without valgrind for now.
return (numOrders > 0);
}
Order Tester::genRandomOrder()
{
// Initialize random number generator
static random_device rd;
// Seed the generator with the random number
static mt19937 gen(rd());
// Generate random characters
// Use 97 - 122 as ASCII character range for lower case letters
static uniform_int_distribution<> charGen(97, 122);
static uniform_int_distribution<> fifoGen(MINONE, MAX50);
static uniform_int_distribution<> processTimeGen(MINONE, MAX12);
static uniform_int_distribution<> dueTimeGen(MINONE, MAX12);
static uniform_int_distribution<> slackTimeGen(MINONE, MAX12);
static uniform_int_distribution<> materialGen(MINZERO, MAX100);
static uniform_int_distribution<> importanceGen(MINONE, MAX100);
static uniform_int_distribution<> workersGen(MINONE, MAX12);
static uniform_int_distribution<> quantityGen(MIN1000, MAX10000);
// Generate a random customer name of length 5
string customer;
for (int i = 0; i < 5; ++i) {
customer += static_cast<char>(charGen(gen));
}
// Generate random values for rest of the order
int fifo = fifoGen(gen);
int process = processTimeGen(gen);
int due = dueTimeGen(gen);
int slack = slackTimeGen(gen);
int material = materialGen(gen);
int importance = importanceGen(gen);
int workers = workersGen(gen);
int quantity = quantityGen(gen);
// Return the created Order
return Order(customer, fifo, process, due, slack, material, importance, workers, quantity);
}
bool Tester::heapProperties(Node **nodes, int numNodes, HEAPTYPE heapType, STRUCTURE structure) {
for(int i = 0; i < numNodes/2; i++) {
int left = 2 * i + 1;
int right = 2 * i + 2;
// Check heap order based on heapType
if (heapType == MINHEAP) {
if (left < numNodes && nodes[i]->getOrder().getImportance() > nodes[left]->getOrder().getImportance()) {
return false;
}
if (right < numNodes && nodes[i]->getOrder().getImportance() > nodes[right]->getOrder().getImportance()) {
return false;
}
} else { // MAXHEAP
if (left < numNodes && nodes[i]->getOrder().getImportance() < nodes[left]->getOrder().getImportance()) {
return false;
}
if (right < numNodes && nodes[i]->getOrder().getImportance() < nodes[right]->getOrder().getImportance()) {
return false;
}
}
//More checks for leftist heap
if(structure == LEFTIST) {
int NPLleft = (left < numNodes) ? nodes[left]->getNPL() : 0;
int NPLright = (right < numNodes) ? nodes[right]->getNPL() : 0;
//NPL property where left npl >= right npl
if (NPLleft < NPLright) {
return false;
}
//Check correct npl values for each node
int NPL = min(NPLleft, NPLright);
if (nodes[i]->getNPL() != NPL) {
return false;
}
}
}
return true;
}
is my tester file
currently im trying to test insertMinHeap
and im not sure if its my insertion logic that is wrong or if it's the way im checking its properties inside of the tester class or what that's causing it to fail
((((((4:ideyk:0)56:tyxxz:1(55:xajap:0))57:pevzz:2((48:zjgel:0)56:uitry:1((6:hvocw:0)15:cqafj:0)))67:ekuen:1((3:wmerx:0)44:kuaxv:0))76:mxogf:2(((37:bbfcg:0)44:vzmwp:0)61:ubakf:1(58:yemug:0)))88:cmtfc:2((32:hvsxn:0)88:jdzwf:1(64:woyzf:0)))
is the current dump when inserting 20 random customers