Exemplo n.º 1
0
Node* buildTree(Vector <int> & weightOfChars, char & delimiter){
    PriorityQueue<Node*> weightsOfNodes; // declare a PriorityQueue for simple sorting weights of nodes
    bool flag = 1; // set flag to prevent overwriting a delimiter
    for(int i = 0; i < weightOfChars.size(); ++i){
        if(weightOfChars[i] > 0){
            Node* node = new Node((i - 128), weightOfChars[i]);
            weightsOfNodes.enqueue(node, weightOfChars[i]);
        }
        else if((flag && (i < 128)) || (flag && (i > 159))){ // looking for a character that is not a control code and has a number of occurences which is equal zero
            delimiter = i;
            flag = 0;
        }
    }

    // if file is empty the pointer of root of the tree is a NULL
    if(weightsOfNodes.isEmpty()){
        return NULL;
    }


    while (weightsOfNodes.size() > 1) {
        Node* lNode = weightsOfNodes.dequeue();
        Node* rNode = weightsOfNodes.dequeue();
        Node* newNode = new Node(lNode, rNode);
        weightsOfNodes.enqueue(newNode, newNode->weight);
    }


    Node* root = weightsOfNodes.dequeue();


    return root;
}
Exemplo n.º 2
0
vector<Node *> dijkstrasAlgorithm(BasicGraph& graph, Vertex* start, Vertex* end) {
	graph.resetData();
    vector<Vertex*> path;
    for (Vertex* node : graph.getNodeSet()){ //initiate all nodes with an inf. cost
        node->cost = INFINITY;
    }
    PriorityQueue<Vertex*> pQueue;
    start->cost = 0;
    pQueue.enqueue(start, start->cost); //start of search

    while (!pQueue.isEmpty()){
        Vertex* v = pQueue.dequeue();
        v->visited = true;
        v->setColor(GREEN);
        if (v == end){
            return pathBuilderToStart(start, v); //same as the one bfs uses
        }else{
            for(Arc* edge : graph.getEdgeSet(v)){ //Go through each edge from the Vertex v, counting the cost for each newly visited vertex
                Vertex* next = edge->finish;
                if (!next->visited){
                    double cost = v->cost + edge->cost;
                    if (cost < next->cost){ //found a lesser cost, what dijkstra is all about
                        next->setColor(YELLOW);
                        next->cost = cost;
                        next->previous = v;
                        pQueue.enqueue(next, cost);
                        //pQueue.changePriority(next, cost); Only do this if next already is in the queue, but this should not ever occur?
                    }
                }
            }
        }
    }
    return path;
}
Exemplo n.º 3
0
int main()  {
	PriorityQueue<int> *testQueue = new PriorityQueue<int>(3);
	

	// push a few random int's
	testQueue->enqueue(4);
	testQueue->enqueue(7);
	testQueue->enqueue(1);
	
	// queue shouldn't be empty; check this
	if(testQueue->isEmpty())  {
		cout << "The queue is empty!" << endl;
	}
	
	// pop items (more items than were pushed)
	cout << testQueue->dequeue() << endl;
	cout << testQueue->dequeue() << endl;
	cout << testQueue->dequeue() << endl;
	cout << testQueue->dequeue() << endl;
	
	// should be empty now; check this
	if(testQueue->isEmpty())  {
		cout << "The queue is empty!" << endl;
	}
	
	return 0;
}
Exemplo n.º 4
0
/*
 *  Method: aStar
 *  Parameters: BasicGraph graph by reference
 *              Vertex pointer variable for path start
 *              Vertex pointer variable for path end
 *  - - - - - - - - - - - - - - - - - - - - - - - - - -
 *  Returns a Vector of Vertex pointer variables for which
 *  each index corresponds to a step in the path between
 *  the path's start and end points, if any exists.
 *  This function uses A*'s algorithm, which evaluates
 *  the estimated total cost of all neighbors' paths to the end
 *  from the starting vertex before continuing. It differs from Dijkstra's
 *  in its prioritization of location based on their estimated total cost
 *  or distance from the starting point, as opposed to the current cost
 *  up to that point. Because A* also orients subsequent vertices
 *  to their earlier parent, this function uses a helper function to
 *  rewind the shortest route from end to start, if applicable,
 *  returning an empty vector if not.
 */
Vector<Vertex*> aStar(BasicGraph& graph, Vertex* start, Vertex* end) {
    graph.resetData();
    Vector<Vertex*> path;
    PriorityQueue<Vertex*> pqueue;
    pqueue.enqueue(start, heuristicFunction(start, end));
    while(!pqueue.isEmpty()) {
        Vertex* current = pqueue.dequeue();
        visitVertex(current);
        if(BasicGraph::compare(current, end) == 0) break;
        for(Edge* edge : current->edges) {
            double cost = current->cost + edge->cost;
            if(!edge->finish->visited &&
               edge->finish->getColor() != YELLOW) {
                enqueueVertex(edge->finish, current, cost);
                pqueue.enqueue(edge->finish, cost + 
                               heuristicFunction(edge->finish, end));
            }
            if(edge->finish->getColor() == YELLOW &&
               cost < edge->finish->cost) {
                enqueueVertex(edge->finish, current, cost);
                pqueue.changePriority(edge->finish, cost + 
                                      heuristicFunction(edge->finish, end));
            }
        }
    }
    determinePath(start, end, path);
    return path;
}
Exemplo n.º 5
0
int main()
{
	PriorityQueue<TaskData> taskPQ;   // Priority queue of tasks
	TaskData task;               // Task
	int simLength,               // Length of simulation (minutes)
		minute,                  // Current minute
		numPtyLevels = 2,            // Number of priority levels
		numArrivals = 0,             // Number of new tasks arriving
		j;                     // Loop counter

	// Seed the random number generator
	srand((unsigned int)time(NULL));

//	cout << endl << "Enter the number of priority levels : ";
//	cin >> numPtyLevels;

	cout << "Enter the length of time to run the simulator : ";
	cin >> simLength;

	time_t timer;

	for (minute = 0; minute < simLength; minute++)
	{
		// Dequeue the first task in the queue (if any).
		if (taskPQ.isEmpty() == false)
		{
			task=taskPQ.dequeue();
			cout << "Priority " << task.priority << " task arrived at " << task.arrived << " & completed at " << minute << endl;
		}

		numArrivals = rand() % 4;
		switch (numArrivals)
		{
		case 2:
			task.arrived = minute;
			task.priority = rand() % numPtyLevels;
			//task.priority = rand() % numPtyLevels - (task.arrived / simLength);
			taskPQ.enqueue(task);
		case 1:
			task.arrived = minute;
			task.priority = rand() % numPtyLevels;
			taskPQ.enqueue(task);
		default:
			break;
		}


	}

	return 0;


}
Exemplo n.º 6
0
void Theta_Star::updateVertex(PriorityQueue &fringe, Node current, Node &succ, Node *vertex)
{
    if(current.parent != NULL && lineOfSight(*current.parent, succ))
    {
        // Path 2 
        double g_current = g_val[current.parent->x+current.parent->y*(blocked->getCols()+1)];
        double cost = sqrt( (succ.x-current.parent->x) * (succ.x-current.parent->x) 
                           + (succ.y-current.parent->y) * (succ.y-current.parent->y) );
        if(cost + g_current < g_val[succ.x+succ.y*(blocked->getCols()+1)])
        {
            g_val[succ.x+succ.y*(blocked->getCols()+1)] = cost + g_current;
            
            succ.h = h(succ.x,succ.y);
            succ.f = g_val[succ.x+succ.y*(blocked->getCols()+1)]+succ.h;
            f_val[succ.x+succ.y*(blocked->getCols()+1)] = succ.f;
            
            succ.parent = vertex->parent;
            
            // we didn't do this before either -> remove from fringe
            fringe.enqueue(succ);
        }
        
    }
    
    else
    {
        
        double g_current = g_val[current.x+current.y*(blocked->getCols()+1)];
        double cost = sqrt( (succ.x-current.x) * (succ.x-current.x) 
                           + (succ.y-current.y) * (succ.y-current.y) );
        
        if(g_current+cost < g_val[succ.x+succ.y*(blocked->getCols()+1)])
        {
            g_val[succ.x+succ.y*(blocked->getCols()+1)] = g_current+cost;
            
            succ.h = h(succ.x,succ.y);
            succ.f = g_val[succ.x+succ.y*(blocked->getCols()+1)]+succ.h;
            
            succ.parent = vertex;
            
            //cout << succ.f << endl; 
            
            if(succ.f < f_val[succ.x+succ.y*(blocked->getCols()+1)])
            {
                fringe.enqueue(succ);
                //cout << "enqueued " << succ.x << " " << succ.y << endl;
                f_val[succ.x+succ.y*(blocked->getCols()+1)] = succ.f;
            }
        }
        
        
    }
}
Exemplo n.º 7
0
Vector<Vertex*> dijkstrasAlgorithm(BasicGraph& graph, Vertex* start, Vertex* end) {
    graph.resetData();
    PriorityQueue<Vertex*> pqueue;
    Vector<Vertex*> path;

    pqueue.enqueue(start, 0);
    start->cost = 0.0;
    start->setColor(YELLOW);

    while(!pqueue.isEmpty())
    {
        Vertex* v = pqueue.dequeue();
        v->setColor(GREEN);

        if (v == end)
            break;

        for (auto edge : v->edges)
        {
            Vertex* next_v = edge->finish;
            if (next_v->getColor() == 0)
            {
                next_v->setColor(YELLOW);
                double next_cost = v->cost + edge->cost;
                next_v->previous = v;
                next_v->cost = next_cost;
                pqueue.enqueue(next_v, next_cost);
            }
            else if (next_v->getColor() == YELLOW)
            {
                double next_cost = v->cost + edge->cost;
                if (next_cost < next_v->cost)
                {
                    next_v->cost = next_cost;
                    next_v->previous = v;
                    pqueue.changePriority(next_v, next_v->cost);
                }
            }
        }
    }

    if (end->getColor() == GREEN)
    {
        Vertex* path_v = end;
        while (path_v->previous)
        {
            path.insert(0, path_v);
            path_v = path_v->previous;
        }
        path.insert(0, path_v);
    }
    return path;
}
Exemplo n.º 8
0
/*
 * A* search. Will explore from 'end' until it finds 'start' or can determine that no valid path exists.
 * It explores in reverse to make it easier to build path array.
 */
vector<Node *> aStar(BasicGraph& graph, Vertex* start, Vertex* end) {
    graph.resetData();
    vector<Vertex*> path;
    PriorityQueue<Vertex*> openQueue;

    //Setup starting state
    end->cost = 0;
    end->visited = true;
    openQueue.enqueue(end, end->cost);
    Vertex* current = nullptr;

    //While there are still reachable nodes to explore
    while(!openQueue.isEmpty()){

        //Set current node to the next node in the queue
        current = openQueue.dequeue();
        current->setColor(GREEN);

        //If current node is target, build path and return
        if(current == start){

            rewind(end, start, path);
            return path;
        }

        //Add any unvisited neighbor to queue, adjust cost for already visited neighbor nodes
        for(Vertex* neighbor : graph.getNeighbors(current)){

            if(!neighbor->visited){

                neighbor->previous = current;
                neighbor->visited = true;
                neighbor->cost = current->cost + graph.getArc(current, neighbor)->cost;
                openQueue.enqueue(neighbor, neighbor->cost + neighbor->heuristic(start));
                neighbor->setColor(YELLOW);
            }else{

                double newCost = current->cost + graph.getArc(current, neighbor)->cost;
                if(neighbor->cost > newCost){

                    neighbor->previous = current;
                    neighbor->cost = newCost;
                    openQueue.changePriority(neighbor, neighbor->cost + neighbor->heuristic(start));
                    neighbor->setColor(YELLOW);
                }
            }
        }
    }
    return path;
}
Exemplo n.º 9
0
void find_path(NavGridLocation from, NavGridLocation to)
{
    int grid_size = gs.grid.get_width() * gs.grid.get_height();
    int from_id = hash_location(from);

    std::vector<AiNode> nodes (grid_size);
    for (int i = 0; i < nodes.size(); i++) {
        AiNode& node = nodes[i];
        node.id = i;
        node.visited = false;
        node.prev_node = nullptr;
        node.true_score = std::numeric_limits<float>::max();
        node.guess_score = std::numeric_limits<float>::max();
        node.pq_node = nullptr;
    }
    nodes[from_id].true_score = 0.f;
    nodes[from_id].guess_score = heuristic_cost(unhash_location(from_id), to);
    PriorityQueue<AiNode*> pq;
    nodes[from_id].pq_node = pq.enqueue(&nodes[from_id], -nodes[from_id].guess_score);
    update_prev(nodes);
    while (!pq.is_empty()) {
        AiNode* current = pq.get_front();
        pq.dequeue();
        current->pq_node = nullptr;
        current->visited = true;
        if (current->id == hash_location(to)) {
            break;
        }
        for (const NavGridLocation& adj : gs.grid.get_adjacent(unhash_location(current->id))) {
            AiNode* adj_node = &nodes[hash_location(adj)];
            if (adj_node->visited) 
                continue;
            float new_score = current->true_score + 1;
            if (new_score >= adj_node->true_score)
                continue;
            adj_node->prev_node = current;
            adj_node->true_score = new_score;
            adj_node->guess_score = new_score + heuristic_cost(unhash_location(adj_node->id), to);
            if (adj_node->pq_node) {
                pq.update(adj_node->pq_node, -adj_node->guess_score);
            } else {
                adj_node->pq_node = pq.enqueue(adj_node, -adj_node->guess_score);
            }
        }
    }
    update_prev(nodes);
    update_path(nodes, to);
}
Exemplo n.º 10
0
int main()
{
    PriorityQueue<int> *temp = new PriorityQueue<int>();

    temp->enqueue(1, 3);
    temp->enqueue(2, 9);
    temp->enqueue(3, 2);

    cout << temp->dequeue() << endl;
    cout << temp->dequeue() << endl;
    cout << temp->dequeue() << endl;
    cout << temp->dequeue() << endl;
    delete temp;

    return 0;
}
Exemplo n.º 11
0
int main(){
	PriorityQueue<int> pq;
	std::cout << pq.size() << std::endl;
	pq.enqueue(1);
	pq.present();
	pq.enqueue(5);
	pq.present();
	pq.enqueue(9);
	pq.present();
	std::cout << pq.size() << " - " << pq.peek() << std::endl;

	pq.enqueue(7);
	pq.present();
	pq.enqueue(3);
	pq.present();
	pq.enqueue(0);
	pq.enqueue(10);
	pq.present();
	std::cout << pq.size() << " - " << pq.peek() << std::endl;

	pq.dequeue();
	pq.present();
	pq.dequeue();
	pq.present();
	std::cout << pq.size() << " - " << pq.peek() << std::endl;

	return 0;
}
Exemplo n.º 12
0
/* Function: buildEncodingTree
 * Usage: Node* tree = buildEncodingTree(frequency);
 * --------------------------------------------------------
 * Given a map from extended characters to frequencies,
 * constructs a Huffman encoding tree from those frequencies
 * and returns a pointer to the root.
 *
 * This function can assume that there is always at least one
 * entry in the map, since the PSEUDO_EOF character will always
 * be present.
 */
Node* buildEncodingTree(Map<ext_char, int>& frequencies) {
  PriorityQueue<Node*> NodePQ;
  foreach(ext_char ch in frequencies){
    Node* newNode = new Node;
    newNode->zero=NULL;
    newNode->one=NULL;
    newNode->weight=frequencies[ch];
    newNode->character=ch;
    NodePQ.enqueue(newNode, newNode->weight);
  }
Exemplo n.º 13
0
int main()
{
	PriorityQueue PQ;
	string command;

	cout << "추가 : en, 삭제 : de, 종료 : quit" << endl;

	while (true)
	{
		cin >> command;

		if (command.compare("en") == 0)
		{
			int data;
			cin >> data;
			PQ.enqueue(data);
		}
		else if (command.compare("de") == 0)
Exemplo n.º 14
0
Set<Edge*> kruskal(BasicGraph& graph) {
    Set<Vertex*> vertexs = graph.getVertexSet();
    Set<Edge*> edges = graph.getEdgeSet();
    map<Vertex*, int> vet_index;
    PriorityQueue<Edge*> pqueue;

    for (Edge* edge : edges)
        pqueue.enqueue(edge, edge->cost);

    int N = vertexs.size();
    DisjointSet union_set(N);

    int i = 0;
    for (Vertex* vert : vertexs)
    {
        vet_index[vert] = i;
        ++i;
    }

    Set<Edge*> mst;

    while (union_set.count() > 1)
    {
        Edge* edge = pqueue.dequeue();
        int p = vet_index[edge->start];
        int q = vet_index[edge->finish];

        if (!union_set.connected(p, q))
        {
            union_set.connect(p, q);
            mst.add(edge);
        }

    }

    return mst;
}
Exemplo n.º 15
0
int main()
{
    //to be able to do fair benchmarks we better use a constant seed
    srand(42);
    PriorityQueue<int> pq;
    for (int i = 1; i < 11; i++)
    {
        pq.enqueue(i);
    }
    pq.enqueue(1);
    pq.enqueue(99);
    pq.enqueue(2);
    pq.enqueue(10);
    pq.enqueue(3);
    pq.enqueue(7);
    while(!pq.empty())
    {
        cout << pq.front() << endl;
        pq.dequeue();
    }
    return 0;
}
Exemplo n.º 16
0
int main()
{
  cout << "\n\nLab 12b, PriorityQueueBigOh.cpp\n";
  cout << "Programmer: Aysin Oruz \n";
  cout << "Editor(s) used: JNotePad and Xcode \n";
  cout << "Compiler(s) used: Xcode and Terminal \n";
  cout << "Description: The purpose of this lab is for you to learn how to create and apply 12b, PriorityQueueBigOh and get values with BigO().\n";
  cout << "File: " <<  __FILE__ << endl;
  cout << "Compiled: " << __DATE__ << " at " << __TIME__ << endl;
  
  const int REPS = 100000; // for timing fast operations, use REPS up to 100th of the starting n
  int n = 10000000; // THE STARTING PROBLEM SIZE (MAX 250 MILLION)
  string bigOh = "O(log n)"; // YOUR PREDICTION: O(1), O(log n), O(n), O(n log n), or O(n squared)
  int elapsedTimeTicksNorm = 0;
  double expectedTimeTicks = 0;
  
  
  cout << "\nEnqueue() O(log n)\n" << endl;
  for (int cycle = 0; cycle < 4; cycle++, n*= 2)
  {
    //Declare PQ
    PriorityQueue<int> List;
    
    //Go thru loop to enter values
    for (int i = n; i > 0; i--)
      List.enqueue(i);
    
    clock_t startTime = clock();  // start the timer
    
    assert(List.getSize() == n);
    
    for(int j = 0; j < REPS; j++ )
      List.enqueue(n + j);
    assert(List.getSize() == n + REPS);
    
    clock_t endTime = clock(); //stop time
    
    for (int i = 0; i < List.getSize(); i++)
    {
      int first = List.dequeue();
      int second = List.dequeue();
      assert(first >= second);
    }
    
    // compute timing results
    long elapsedTimeTicks = (long)(endTime - startTime);
    double factor = pow(2.0, cycle);
    if (cycle == 0)
      elapsedTimeTicksNorm = elapsedTimeTicks;
    else if (bigOh == "O(1)")
      expectedTimeTicks = elapsedTimeTicksNorm;
    else if (bigOh == "O(log n)")
      expectedTimeTicks = log(double(n)) / log(n / factor) * elapsedTimeTicksNorm;
    else if (bigOh == "O(n)")
      expectedTimeTicks = factor * elapsedTimeTicksNorm;
    else if (bigOh == "O(n log n)")
      expectedTimeTicks = factor * log(double(n)) / log(n / factor) * elapsedTimeTicksNorm;
    else if (bigOh == "O(n squared)")
      expectedTimeTicks = factor * factor * elapsedTimeTicksNorm;
    
    cout << elapsedTimeTicks;;
    if (cycle == 0) cout << " (expected " << bigOh << ')';
    else cout << " (expected " << expectedTimeTicks << ')';
    cout << " for n = " << n << endl;
  }
  
  {
    const int REPS = 10000; // for timing fast operations, use REPS up to 100th of the starting n
    int n = 1000000; // THE STARTING PROBLEM SIZE (MAX 250 MILLION)
    
    cout << "\nDequeue() O(log n)\n" << endl;
    for (int cycle = 0; cycle < 4; cycle++, n*= 2)
    {
      
      PriorityQueue<int> List;
      for(int i = n; i > 0; i--)
        List.enqueue(i);
      assert(List.getSize() == n);
      
      //start timing
      clock_t startTime = clock();
      for(int j = 0; j < REPS; j++)
        List.dequeue();
      clock_t endTime = clock(); //stop timign
      assert(List.getSize() == n - REPS);
      
      for (int i = 0; i < List.getSize(); i++)
      {
        int first = List.dequeue();
        int second = List.dequeue();
        assert(first >= second);
      }
      
      // compute timing results
      long elapsedTimeTicks = (long)(endTime - startTime);
      double factor = pow(2.0, cycle);
      if (cycle == 0)
        elapsedTimeTicksNorm = elapsedTimeTicks;
      else if (bigOh == "O(1)")
        expectedTimeTicks = elapsedTimeTicksNorm;
      else if (bigOh == "O(log n)")
        expectedTimeTicks = log(double(n)) / log(n / factor) * elapsedTimeTicksNorm;
      else if (bigOh == "O(n)")
        expectedTimeTicks = factor * elapsedTimeTicksNorm;
      else if (bigOh == "O(n log n)")
        expectedTimeTicks = factor * log(double(n)) / log(n / factor) * elapsedTimeTicksNorm;
      else if (bigOh == "O(n squared)")
        expectedTimeTicks = factor * factor * elapsedTimeTicksNorm;
      
      // reporting block
      cout << elapsedTimeTicks;;
      if (cycle == 0) cout << " (expected " << bigOh << ')';
      else cout << " (expected " << expectedTimeTicks << ')';
      cout << " for n = " << n << endl;
    }}
  
}
Exemplo n.º 17
0
int  main()
   {
    PriorityQueue<DataType> testPQA;
    PriorityQueue<DataType> testPQB;
    PriorityQueue<DataType> testPQC;
    char cmdChar;
    DataType dataItem;
    int qPriority;
    char qProcess[ SMALL_STR_LEN ];
    bool dataChanged;

    ShowMenu();

    do
       {
        dataChanged = false;

        cout << endl << "Command: ";                  // Read command
        
        cmdChar = GetCommandInput( qProcess, qPriority );

        switch ( cmdChar )
           {
            case 'c': case 'C':  // clear priority queue

               while( !testPQA.isEmpty() )
                  {
                   testPQA.dequeue( dataItem );
                  }

               if( VERBOSE )
                  {
                   cout << "  Priority Queue has been cleared " << endl;
                  }

               dataChanged = true;

               break;

            case 'd': case 'D':  // dequeue one data item

               testPQA.dequeue( dataItem );

               if( VERBOSE )
                  {
                   cout << "  Process: " << dataItem.process
                        << " has been dequeued with a priority of "
                        << dataItem.priority << PERIOD << endl;
                  }

               dataChanged = true;

               break;

            case 'e': case 'E':  // enqueue

               testPQA.enqueue( qPriority, qProcess );

               if( VERBOSE )
                  {
                   cout << "  Process: " << qProcess
                        << " has been enqueued with a priority of "
                        << qPriority << PERIOD << endl;
                  }

               dataChanged = true;

               break;

            case 'h': case 'H':  // help request

               ShowMenu();

               break;

            case 'p': case 'P':  // peek at next item

               testPQA.peekAtFront( dataItem );

               if( VERBOSE )
                  {
                    cout << "  Process: " << dataItem.process
                         << " with priority: " << dataItem.priority
                         << " found at front of queue." << endl;
                  }
               break;

            case 'q': case 'Q':  // quit the test program

               if( VERBOSE )
                  {
                   cout << "  End Program Requested" << endl;
                  }

               cout << endl;

               break;

            case 'x': case 'X':  // create copy constructor PQ

               // tempPQ constructed in code block to control scope
                  { 
                   PriorityQueue<DataType> tempPQ( testPQA );

                   testPQC = tempPQ;
                  }

               if( VERBOSE )
                  {
                   cout << "  Test PQ \'C\' has been constructed with test PQ \'A\'." 
                        << endl;
                  }

               dataChanged = true;

               break;

            case 'z': case 'Z':  // assign to b PQ

               testPQB = testPQA;

               if( VERBOSE )
                  {
                   cout << "  Test PQ \'A\' has been assigned to test PQ \'B\'." 
                        << endl;
                  }

               dataChanged = true;

               break;

            default :            // Invalid command

               // clear to end of line in case further data input
               cin.ignore( SMALL_STR_LEN, ENDLINE_CHAR );

               if( VERBOSE )
                  {
                   cout << "  Inactive or invalid command" << endl;
                  }
           }

        if( dataChanged )
           {
            testPQA.showStructure( 'A' );
            testPQB.showStructure( 'B' );
            testPQC.showStructure( 'C' );
           }
       }
    while ( cmdChar != 'q' && cmdChar != 'Q' );

    return 0;
   }
Exemplo n.º 18
0
/* main() manages the user interface;
 * instantiates priority queue object, then operates loop to read input 
 * from user and call the appropriate priority queue method
 */
int main() {
   PriorityQueue pq;
   TokenScanner scanner;
   while (true) {
      string line = getLine("> ");
      scanner.setInput(line);
      scanner.ignoreWhitespace();
      string cmd=scanner.nextToken();
      if (cmd == "help") {
         helpCommand();
      }      
      else if (cmd == "enqueue") {
	if(scanner.hasMoreTokens()){
	  string value=scanner.nextToken();
	  if(scanner.hasMoreTokens()){
	    scanner.scanNumbers();
	    string priorityStr=scanner.nextToken();
	    double priority=stringToDouble(priorityStr);	
	    pq.enqueue(value,priority);
	  }
	  else
	    pq.enqueue(value);
	}
      }    
      else if (cmd == "dequeue") {
	if(pq.isEmpty())
	  cout<<"The queue is empty"<<endl;
	else
	  cout<<pq.dequeue()<<endl;
      }
      else if (cmd == "peek") {
	if(pq.isEmpty())
	  cout<<"The queue is empty"<<endl;
	else
	  cout<<pq.peek()<<endl;
      }
      else if (cmd == "peekPriority"||cmd=="peekpriority") {
	if(pq.isEmpty())
	  cout<<"The queue is empty"<<endl;
	else
	  cout<<pq.peekPriority()<<endl;
      }
      else if (cmd == "clear") {
	pq.clear();
      }
      else if (cmd == "size") {
	cout<<pq.size()<<endl;
      }
      else if (cmd == "isEmpty"||cmd=="isempty") {
	if(pq.isEmpty())
	  cout<<"true";
	else
	  cout<<"false";
	cout<<endl;
      }
      else if(cmd=="list")
	list(pq);
      else {
         cout << "Undefined command: " << cmd << endl;
      }
   }
   return 0;
}
Exemplo n.º 19
0
void testPriorityQueue(){
    PriorityQueue<int> mycontainer;

    cout << "\n\n Begin test function for the PriorityQueue<T> class\n";

    // Testing the enqueue function
    cout << "Testing size of new empty container: " << mycontainer.length() << endl;
    cout << "Testing enqueue(1), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    mycontainer.enqueue(1);
    cout << "Size is " << mycontainer.length() << endl;
    cout << "Testing enqueue(2), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    mycontainer.enqueue(2);
    cout << "Size is " << mycontainer.length() << endl;
    cout << "Testing enqueue(2), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    mycontainer.enqueue(2);
    cout << "Size is " << mycontainer.length() << endl;
    cout << "Testing enqueue(2), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    mycontainer.enqueue(2);
    cout << "Size is " << mycontainer.length() << endl;
    cout << "Testing enqueue(2), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    mycontainer.enqueue(2);
    cout << "Size is " << mycontainer.length() << endl;
    cout << "Testing enqueue(2), length(), and isEmpty() functions. mycontainer is empty? "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");
    cout << "Size is " << mycontainer.length() << endl << endl;

    int size = mycontainer.length();
    cout << "Testing pop_back(), front(), back(), length() and isEmpty() functions \n"
            << "in a for loop with iterations greater than container size.";
    for (int i = 0; i < size + 1; i++) {
        cout << "\nIteration: " << i + 1 << "\n";
        if (!mycontainer.isEmpty()) {
            cout << " mycontainer is empty? " << (mycontainer.isEmpty() ? " true\n" : "false\n");
            cout << "PriorityQueue size before pop is " << mycontainer.length() << endl;
            //cout<<"Front of container is " << mycontainer.front()<<endl;
            //cout<<"Back of container is " << mycontainer.back()<<endl;
            //cout << "Popping: " << mycontainer.front() << endl << endl;
            mycontainer.pop_back();
        } else {
            cout << "The PriorityQueue is empty.\n";
        }

        cout << "PriorityQueue size is now: " << mycontainer.length() << endl;
    }
    cout << "\nFinished for loop\n";

    cout << "\nTesting the reference for front() and back() functions.\n";
    cout << "Start with int test = 7. mycontainer.enqueue(test)\n";
    int test = 7;
    mycontainer.enqueue(test);
    cout << "Testing with test = 8. test=mycontainer.front(). mycontainer.front() = 13 \n";
    test = 8;
    test = mycontainer.front();
    mycontainer.front() = 13;
    cout << "Test is now " << test << " front of container is " << mycontainer.front()
            << " back of container is " << mycontainer.back() << endl;
    test = 11;
    mycontainer.enqueue(test);
    cout << "Back of container is: " << mycontainer.back() << endl;
    cout << "Test is now " << test << " front of container is " << mycontainer.front()
            << " back of container is " << mycontainer.back() << endl;
    mycontainer.back() = test;
    cout << "Test is now " << test << " front of container is " << mycontainer.front()
            << " back of container is " << mycontainer.back() << endl;

    cout << "mycontainer size is " << mycontainer.length() << endl;

    cout << "\nTesting the clear() function: \n";
    mycontainer.clear();
    cout << "mycontainer size now is " << mycontainer.length()
            << " mycontainer is empty: "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");


    cout << "\nTesting assignment operator: container2 = mycontainer\n";
    cout << "Filling mycontainer with ints starting at 42\n";
    size = 5;
    // Fill mycontainer with ints to test copy constructor
    for (int i = 0; i < size; i++) {
        mycontainer.enqueue(i + 41);
    }

    cout << "mycontainer size now is " << mycontainer.length()
            << " mycontainer is empty: "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");

    PriorityQueue<int> container2;
    container2 = mycontainer;
    cout << "mycontainer size is: " << mycontainer.length() << endl;
    cout << "container2 size is: " << container2.length() << endl;
    cout << "Testing the contents of container2 and mycontainer using back() and pop_back() functions:\n";
    size = container2.length();
    for (int i = 0; i < size; i++) {
        cout << "Attempting front and pop functions. Iteration: " << i + 1 << "\n";

        // Don't perform the operation if either container is empty. 
        // Output should be the same for both containers
        if (!container2.isEmpty() || !mycontainer.isEmpty()) {
            cout << "\tcontainer2 - front(): " << container2.front()
                    << " back(): " << container2.back() << endl;
            container2.pop_back();
            cout << "\tmycontainer - front(): " << mycontainer.front()
                    << " back(): " << mycontainer.back() << endl;
            mycontainer.pop_back();
        } else {
            cout << "Containers are empty.\n";
        }
    }

    cout << "\nTesting the copy constructor. Filling mycontainer ints\n";
    size = 5;
    // Fill mycontainer with ints to test copy constructor
    for (int i = 0; i < size; i++) {
        mycontainer.enqueue(i + 41);
    }

    cout << "mycontainer size now is " << mycontainer.length()
            << " mycontainer is empty: "
            << (mycontainer.isEmpty() ? " true\n" : "false\n");

    PriorityQueue<int> container3(mycontainer);

    cout << "container3 size is: " << container3.length();
    cout << "\nTesting the contents of container3 and mycontainer using back() and pop_back() functions:\n";
    size = container3.length();
    for (int i = 0; i < size; i++) {
        cout << "Attempting front and pop functions. Iteration: " << i + 1 << "\n";

        // Don't perform the operation if either container is empty. 
        // Output should be the same for both containers
        if (!container3.isEmpty() || !mycontainer.isEmpty()) {
            cout << "\tcontainer3 - front(): " << container3.front()
                    << " back(): " << container3.back() << endl;
            container3.pop_back();
            cout << "\tmycontainer - front(): " << mycontainer.front()
                    << " back(): " << mycontainer.back() << endl;
            mycontainer.pop_back();
        } else {
            cout << "Containers are empty.\n";
        }
    }
    cout << "\nEnd of test function for the PriorityQueue<T> class\n\n";
}
int main()
{
    // print my name and this assignment's title
    cout << "Lab 12b, The \"PriorityQueueBigOh.cpp\" Program \n";
    cout << "Programmer: JEREMY THOMPSON\n";
    cout << "Editor(s) used: JNotePad\n";
    cout << "Compiler(s) used: VC++ 2013\n";
    cout << "File: " << __FILE__ << endl;
    cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl;

    int N = 8000000;
    const int REPS = (N / 100); // REPS for each cycle, less than 1%
    string bigOh = "O(log n)"; // YOUR PREDICTION: O(1), O(log n), O(n), O(n log n), or O(n squared)

    for (int iteration = 1; iteration < 3; iteration++) // 2 cycles per iteration
    {
        int n = N;
        int elapsedTimeTicksNorm = 0;
        double expectedTimeTicks = 0;

        if (iteration == 1) cout << "enqueue, O(log n)" << endl;
        if (iteration == 2) cout << "\ndequeue, O(log n)" << endl;

        for (int cycle = 0; cycle < 4; cycle++, n *= 2) // runs 4 cycles and doubles n each time
        {
            // Creation of test object
            PriorityQueue<double> pQueue;

            for (int i = n; i > 0; i--) pQueue.enqueue(i); // assigning of decreasing values

            assert(pQueue.getSize() == n); // assertion to confirm n is the size of the data struct
            PriorityQueue<double> pQueueCopy(pQueue); // default priority queue

            // START TIMER
            clock_t startTime = clock();

            if (iteration == 1) for (int reps = 0; reps < REPS; reps++) pQueue.enqueue(n + reps);
            if (iteration == 2) for (int reps = 0; reps < REPS; reps++) pQueue.dequeue();

            // STOP TIMER
            clock_t endTime = clock();

            if (iteration == 1) assert(pQueue.getSize() == (n + REPS)); // assertion for size
            if (iteration == 1) assert(pQueue.getSize() == (n + REPS));

            // compute timing results
            long elapsedTimeTicks = (long)(endTime - startTime);
            double factor = pow(2.0, cycle);
            if (cycle == 0)
                elapsedTimeTicksNorm = elapsedTimeTicks;
            else if (bigOh == "O(1)")
                expectedTimeTicks = elapsedTimeTicksNorm;
            else if (bigOh == "O(log n)")
                expectedTimeTicks = log(double(n)) / log(n / factor) * elapsedTimeTicksNorm;
            else if (bigOh == "O(n)")
                expectedTimeTicks = factor * elapsedTimeTicksNorm;
            else if (bigOh == "O(n log n)")
                expectedTimeTicks = factor * log(double(n)) / log(n / factor) * elapsedTimeTicksNorm;
            else if (bigOh == "O(n squared)")
                expectedTimeTicks = factor * factor * elapsedTimeTicksNorm;

            // reporting block
            cout << "\n  " << elapsedTimeTicks;
            if (cycle == 0) cout << " (expected " << bigOh << ')';
            else cout << " (expected " << expectedTimeTicks << ')';
            cout << " for n=" << n;
        }
    }

    cout << "\nPress ENTER to continue...";
    cin.get();
}
Exemplo n.º 21
0
int main()
{
  cout << "\n\nLab 12a, PriorityQueueDriver.cpp\n";
  cout << "Programmer: Aysin Oruz \n";
  cout << "Editor(s) used: JNotePad and Xcode \n";
  cout << "Compiler(s) used: Xcode and Terminal \n";
  cout << "Description: The purpose of this lab is for you to learn how to create and apply our PriorityQueue file.";
  cout << "File: " <<  __FILE__ << endl;
  cout << "Compiled: " << __DATE__ << " at " << __TIME__ << endl;
  
  PriorityQueue<int> PQlist;
  
  cout << "Building a Priority Queue\n\n";
  cout << "1-)Testing getsize function when queue is empty\n";
  cout << "Expected  >> 0\n";
  assert(PQlist.getSize() == 0);
  cout << "Actual >> " << PQlist.getSize() << endl;
  
  cout << "\n2-)Testing enqueue function by adding new values\n";
  for (int i = 0; i < 8; i++)
    PQlist.enqueue(i);
  assert(PQlist.getSize());
  cout << "Expected >> 8\n";
  cout << "Actual >> " << PQlist.getSize() << endl;
  
  cout << "\n3-) Testing Dequeue Function by removing largest value\n";
  cout << "Removed value >> " << PQlist.dequeue() << endl;
  
  cout << "\n4-)Testing getsize function after dequeue\n";
  cout << "Expected  >> 7\n";
  assert(PQlist.getSize() == 7);
  cout << "Actual >> " << PQlist.getSize() << endl;
  
  cout << "\n5-) Testing Dequeue Function by removing largest value\n";
  cout << "Removed value >> " << PQlist.dequeue() << endl;
  
  cout << "\n6-)Testing getsize function after dequeue\n";
  cout << "Expected  >> 6\n";
  assert(PQlist.getSize() == 6);
  cout << "Actual >> " << PQlist.getSize() << endl;
  
  cout << "\n7-) Testing Dequeue Function by removing largest values\n";
  cout << "Removed value >> " << PQlist.dequeue() << endl;
  cout << "Removed value >> " << PQlist.dequeue() << endl;
  cout << "Removed value >> " << PQlist.dequeue() << endl;
  cout << "Removed value >> " << PQlist.dequeue() << endl;
  cout << "Removed value >> " << PQlist.dequeue() << endl;
  cout << "Removed value >> " << PQlist.dequeue() << endl;
  
  cout << "\n8-)Testing getsize function after dequeue\n";
  cout << "Expected  >> 0\n";
  assert(PQlist.getSize() == 0);
  cout << "Actual >> " << PQlist.getSize() << endl;
  
  cout << "\nValues added back to PQ\n";
  for (int i = 0; i < 8; i++)
    PQlist.enqueue(i);
  assert(PQlist.getSize());
  //Const object copy testing with assignment UPON declaration
  {
    const PriorityQueue<int> copy= PQlist;
    cout << "\nCONST object copy testing with assignment UPON declaration\n";
    cout << "\nTesting getsize()\nExpected >> 8\n";
    cout << "Actual >> " << copy.getSize() << endl;
    assert(copy.getSize() == 8);
  }
  
  //object copy testing with assignment UPON declaration
  {
    PriorityQueue<int> copy = PQlist;
    cout << "\nobject copy testing with assignment UPON declaration\n";
    cout << "\nTesting getsize()\nExpected >> 8\n";
    cout << "Actual >> " << copy.getSize() << endl;
    assert(copy.getSize() == 8);
    
    cout << "\nDequeue all the values in the PQ\n";
    assert(copy.dequeue() == 7); assert(copy.dequeue() == 6);
    assert(copy.dequeue() == 5); assert(copy.dequeue() == 4);
    assert(copy.dequeue() == 3); assert(copy.dequeue() == 2);
    assert(copy.dequeue() == 1); assert(copy.dequeue() == 0);
    
    cout << "\nGetsize() after dequeue\n";
    cout << "Expected >> 0\n";
    cout << "Actual >> " << copy.getSize() << endl;
  }
  // object copy testing with assignment Afterdeclaration
  {
    PriorityQueue<int> copy; copy = PQlist;
    cout << "\nobject copy testing with assignment AFTER declaration\n";
    cout << "\nTesting getsize()\nExpected >> 8\n";
    cout << "Actual >> " << copy.getSize() << endl;
    assert(copy.getSize() == 8);
    
    cout << "\nDequeue all the values in the PQ\n";
    assert(copy.dequeue() == 7); assert(copy.dequeue() == 6);
    assert(copy.dequeue() == 5); assert(copy.dequeue() == 4);
    assert(copy.dequeue() == 3); assert(copy.dequeue() == 2);
    assert(copy.dequeue() == 1); assert(copy.dequeue() == 0);
    
    cout << "\nGetsize() after dequeue\n";
    cout << "Expected >> 0\n";
    cout << "Actual >> " << copy.getSize() << endl;
  }
 
  
  cout << "\nDequeue() - Empty the list\n";
  for (int i = 0; i < 8; i++)
    PQlist.dequeue();
  assert(PQlist.getSize() == 0);
  cout << "List is empty!\n";

}
Exemplo n.º 22
0
//this is the same as dijkstrasAlgorithm except for one thing which is commented
vector<Node *> aStar(BasicGraph& graph, Vertex* start, Vertex* end) {
    graph.resetData();
    Vertex* unDefined;
    Vertex*  currentNode;
    start->cost=0.0;
    PriorityQueue<Vertex*> vertexPrioQueue;
    map<Vertex*,Vertex*> predecessor;
    for (Node *node :graph.getNodeSet()){
        if (node!=start){
            node->cost=INFINITY;
            predecessor[node]=unDefined;
        }
        vertexPrioQueue.enqueue(node,node->cost);;

    }
    double alt;
    while (!vertexPrioQueue.isEmpty()){
        currentNode= vertexPrioQueue.front();

        vertexPrioQueue.dequeue();
        currentNode->setColor(YELLOW);
        currentNode->visited=true;
        if (currentNode==end){
            break;
        }
        for(Node *node :graph.getNeighbors(currentNode)){
            if (!node->visited){
                alt=currentNode->cost+graph.getArc(currentNode,node)->cost;
                if (alt<node->cost){
                    node->cost=alt;
                    predecessor[node]=currentNode;
                    //this is the change, the queuepriority comes from the node cost + the heuristic
                    vertexPrioQueue.changePriority(node,node->cost+node->heuristic((end)));

                }
            }
        }
        currentNode->setColor(GREEN);

    }

    if(predecessor[end]==unDefined){
        vector<Vertex*> path;
        return path;
    }
    else{
        stack<Vertex*> vertexStack;
        vector<Vertex*> path;
        currentNode=end;
        while (currentNode!=start){
            vertexStack.push(currentNode);
            currentNode=predecessor[currentNode];

        }
        vertexStack.push(start);
        while (!vertexStack.empty()){
            path.push_back(vertexStack.top());
            vertexStack.pop();
        }
        return path;
    }
}
Exemplo n.º 23
0
vector<Node *> dijkstrasAlgorithm(BasicGraph& graph, Vertex* start, Vertex* end) {
    graph.resetData();
    //set as predescessor if that is undefined
    Vertex* unDefined;

    //the current node we are checking
    Vertex*  currentNode;

    //sets startnode cost to zero
    start->cost=0.0;

    //create prioqueue
    PriorityQueue<Vertex*> vertexPrioQueue;

    //used to keep track of all predeccesors
    map<Vertex*,Vertex*> predecessor;

    //set all costs, sets predecessor and adds the to the queue
    for (Node *node :graph.getNodeSet()){
        //all nodes but start should have infinity cost
        if (node!=start){
            node->cost=INFINITY;
            predecessor[node]=unDefined;
        }
        //add all nodes to queue
        vertexPrioQueue.enqueue(node,node->cost);

    }
    //keep track of the alternative cost
    double alt;
    //while the queue is not empty
    while (!vertexPrioQueue.isEmpty()){
        //put current node to the one with highest priority
        currentNode= vertexPrioQueue.front();
        vertexPrioQueue.dequeue();
        currentNode->setColor(YELLOW);
        currentNode->visited=true;
        if (currentNode==end){
            break;
        }

        //check all the node's neighbors
        for(Node *node :graph.getNeighbors(currentNode)){
            //if we have not visited that node
            if (!node->visited){
                //we check the alternative cost
                alt=currentNode->cost+graph.getArc(currentNode,node)->cost;
                //if the alternative cost is lower then we set that to our new cost
                if (alt<node->cost){
                    node->cost=alt;
                    predecessor[node]=currentNode;
                    vertexPrioQueue.changePriority(node,alt);

                }
            }
        }
        currentNode->setColor(GREEN);

    }
    //if we havent found end
    if(predecessor[end]==unDefined){
        vector<Vertex*> path;
        return path;
    }
    else{
        //if we have found end we trace through the predecessor map to find the path
        stack<Vertex*> vertexStack;
        vector<Vertex*> path;
        currentNode=end;
        while (currentNode!=start){
            vertexStack.push(currentNode);
            currentNode=predecessor[currentNode];

        }
        vertexStack.push(start);
        while (!vertexStack.empty()){
            path.push_back(vertexStack.top());
            vertexStack.pop();
        }
        return path;
    }
}
Exemplo n.º 24
0
int main()
{
  // print my name and this assignment's title
  cout << "Lab 11a, The \"Write And Test A Priority Queue Template\" Program \n";
  cout << "Programmer: Licong Wang\n";
  cout << "Editor(s) used: Visual studio 2013\n";
  cout << "Compiler(s) used:  Microsoft c++ complier\n";
  cout << "File: " << __FILE__ << endl;
  cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl << endl;

  PriorityQueue<int> pq;

  cout << "\nTest size and empty" << endl;
  cout << "The expected size is 0, the acutal size is " << pq.size() << endl;
  assert(pq.size() == 0);
  cout << "Expect it to be empty: ";
  if (pq.empty())
    cout << "Empty" << endl;
  else
    cout << "Not Empty" << endl;
  assert(pq.empty());

  cout << "\nEnqueue values 1 to 5" << endl;
  for (int i = 1; i < 6; i++)
  {
    pq.enqueue(i);
  }

  cout << "\nTest size and empty again" << endl;
  cout << "The expected size is 5, the acutal size is " << pq.size() << endl;
  assert(pq.size() == 5);
  cout << "Expect it to be not empty: ";
  if (pq.empty())
    cout << "Empty" << endl;
  else
    cout << "Not Empty" << endl;
  assert(!(pq.empty()));

  cout << "\nCheck its front and back, expecting 5 and 3, accroding to the rule of binary tree" << endl;
  cout << "Front: " << pq.front() << endl;
  cout << "back: " << pq.back() << endl;
  assert(pq.front() == 5);
  assert(pq.back() == 3);

  cout << "\nCheck the heap array using copy pop, expecting values from 5-1, "
    << "since the highest value is popped each time" << endl;
  for (PriorityQueue<int> copy = pq; copy.size(); )
    cout << copy.dequeue() << " ";

  cout << "\n\nNow dequeue once" << endl;
  pq.dequeue();

  cout << "\nTest size again" << endl;
  cout << "The expected size is 4, the acutal size is " << pq.size() << endl;
  assert(pq.size() == 4);

  cout << "\nCheck its front and back, expecting 4 and 1" << endl;
  cout << "Front: " << pq.front() << endl;
  cout << "back: " << pq.back() << endl;
  assert(pq.front() == 4);
  assert(pq.back() == 1);

  cout << "\ncheck the heap array using copy pop, expecting values from 4-1, "
    << "since 5 is already dequeued" << endl;
  for (PriorityQueue<int> copy = pq; copy.size(); )
    cout << copy.dequeue() << " ";
  cout << endl;

  {
    cout << "\nObject Copy Testing" << endl;
    const PriorityQueue<int> copy = pq;

    cout << "\nTest size and empty" << endl;
    cout << "The expected size is 4, the acutal size is " << pq.size() << endl;
    assert(pq.size() == 4);
    cout << "Expect it to be not empty: ";
    if (pq.empty())
      cout << "Empty" << endl;
    else
      cout << "Not Empty" << endl;
    assert(!(pq.empty()));

    cout << "\ncheck the heap array using copy pop, expecting values from 4-1" << endl;
    for (PriorityQueue<int> copy2 = copy; copy2.size(); )
      cout << copy2.dequeue() << " ";
    cout << endl;
  }

  {
    cout << "\nObject Assignment Testing" << endl;
    PriorityQueue<int> copy; copy = pq;

    cout << "\nTest size and empty" << endl;
    cout << "The expected size is 4, the acutal size is " << pq.size() << endl;
    assert(pq.size() == 4);
    cout << "Expect it to be not empty: ";
    if (pq.empty())
      cout << "Empty" << endl;
    else
      cout << "Not Empty" << endl;
    assert(!(pq.empty()));

    cout << "\ncheck the heap array using copy pop, expecting values from 4-1" << endl;
    for (PriorityQueue<int> copy2 = copy; copy2.size();)
      cout << copy2.dequeue() << " ";
    cout << endl;
  }

  cout << "\nBack to original object, test clear" << endl;
  pq.clear();

  cout << "\nTest size and empty" << endl;
  cout << "The expected size is 0, the acutal size is " << pq.size() << endl;
  assert(pq.size() == 0);
  cout << "Expect it to be empty: ";
  if (pq.empty())
    cout << "Empty" << endl;
  else
    cout << "Not Empty" << endl;
  assert(pq.empty());

  cout << "\nCheck its front and back, expecting 0 and 0, dummy got returned" << endl;
  cout << "Front: " << pq.front() << endl;
  cout << "back: " << pq.back() << endl;
  assert(pq.front() == 0);
  assert(pq.back() == 0);

  cout << "\nPress ENTER to continue..." << endl;
  cin.get();
}
int main()
{
  // problem setup goes here
  bool test1=true, test2=true;
  PriorityQueue<double> pq;
  int i, REPS = 1000000;
  srand (time(NULL));


  while(test1) // operator[] assignment at zeroth index, O(1)
  {
	cout << "\n  Test 1 - enqueue, O(log n)\n\n";
    // programmer customizations go here
    double n = 500000; // THE STARTING PROBLEM SIZE
    string bigOh = "O(log n)"; // YOUR PREDICTION: O(1), O(log n), O(n), O(n log n), or O(n squared)
	
    int elapsedTimeTicksNorm;
    double expectedTimeTicks, m;
    for (int cycle=0; cycle<4; cycle++, n*=2)
    {
      // more problem setup goes here -- the stuff not timed
	  for(i=0; i<n; i++)
	    pq.enqueue(rand() % RAND_MAX);
	  long elapsedTimeTicks = 0;
	  for (i=0; i<REPS; i++) 
      { 
		m = rand() % RAND_MAX;
	    assert(pq.size()==n);

	    // initize the timer
        clock_t startTime = clock();

        // do something where n is the "size" of the problem
	    pq.enqueue(m);

        // compute timing results
        clock_t endTime = clock(); 
        elapsedTimeTicks += (long)(endTime - startTime);
		pq.dequeue(m);
	  }

      double factor = pow(2.0, cycle);
      if (cycle == 0)
        elapsedTimeTicksNorm = elapsedTimeTicks;
      else if (bigOh == "O(1)")
        expectedTimeTicks = elapsedTimeTicksNorm;
      else if (bigOh == "O(log n)")
        expectedTimeTicks = log(double(n)) / log(n / factor) * elapsedTimeTicksNorm;
      else if (bigOh == "O(n)")
        expectedTimeTicks = factor * elapsedTimeTicksNorm;
      else if (bigOh == "O(n log n)")
        expectedTimeTicks = factor * log(double(n)) / log(n / factor) * elapsedTimeTicksNorm;
      else if (bigOh == "O(n squared)")
        expectedTimeTicks = factor * factor * elapsedTimeTicksNorm;

      // reporting block
      cout << elapsedTimeTicks;
      if (cycle == 0) cout << " (expected " << bigOh << ')';
      else cout << " (expected " << expectedTimeTicks << ')';
      cout << " for n=" << n << endl;
	  pq.makeEmpty();
      assert(pq.isEmpty());
    }
    test1=false;
  }


  REPS = 500000;

  while(test2) // operator[] assignment at 100th index, O(1)
  {
	cout << "\n\n  Test 2 - dequeue, O(log n)\n\n";
    // programmer customizations go here
    double n = 500000; // THE STARTING PROBLEM SIZE
    string bigOh = "O(log n)"; // YOUR PREDICTION: O(1), O(log n), O(n), O(n log n), or O(n squared)


    int elapsedTimeTicksNorm;
    double expectedTimeTicks;
    for (int cycle=0; cycle<4; cycle++, n*=2)
	{
      // more problem setup goes here -- the stuff not timed
      for(i=0; i<n; i++)
	    pq.enqueue(rand() % RAND_MAX); // fill pq 
	  long elapsedTimeTicks = 0;
	  clock_t startTime, endTime;
	  double j;
	  for (i=0; i<REPS; i++) 
	  {
	    assert(pq.size()==n);
        // initize the timer
        startTime = clock();

        // do something where n is the "size" of the problem
	    pq.dequeue(j);

        // compute timing results
        endTime = clock(); 
	    elapsedTimeTicks += (long)(endTime - startTime);
		pq.enqueue(j);
	  }
	  double factor = pow(2.0, cycle);
      if (cycle == 0)
        elapsedTimeTicksNorm = elapsedTimeTicks;
      else if (bigOh == "O(1)")
        expectedTimeTicks = elapsedTimeTicksNorm;
      else if (bigOh == "O(log n)")
        expectedTimeTicks = log(double(n)) / log(n / factor) * elapsedTimeTicksNorm;
      else if (bigOh == "O(n)")
        expectedTimeTicks = factor * elapsedTimeTicksNorm;
      else if (bigOh == "O(n log n)")
        expectedTimeTicks = factor * log(double(n)) / log(n / factor) * elapsedTimeTicksNorm;
      else if (bigOh == "O(n squared)")
        expectedTimeTicks = factor * factor * elapsedTimeTicksNorm;

      // reporting block
      cout << elapsedTimeTicks;
      if (cycle == 0) cout << " (expected " << bigOh << ')';
      else cout << " (expected " << expectedTimeTicks << ')';
      cout << " for n=" << n << endl;
	  pq.makeEmpty();
      assert(pq.isEmpty());
    }
    test2=false;
  }
	 
  cout << endl;
  return 0;
}
Exemplo n.º 26
0
/*
 * Function: aStar
 * --------------------
 * This function implements aStar search (variation of dijkstras with a heuristic)
 *
 * Preconditions:
 *
 *  @param: graph: The graph to be searched
 *          start: The start vertex
 *          end:The end vertex
 *  @return: returns a vector of vertexes containing the path (empty if no path)
 */
Vector<Vertex*> aStar(BasicGraph& graph, Vertex* start, Vertex* end) {

    graph.resetData(); // reset
    Vector<Vertex*> path; // the return path
    Set<Vertex*> inQueue; // A vector holding the values that we have already put into the queue

    // INitialize every vertex to have infinite cost
    for(Vertex* s:graph.getVertexSet()){
        s->cost = POSITIVE_INFINITY;
    }

    PriorityQueue<Vertex*> pq; // A pq to see where to search next (cost+heuristic = priority)
    // Set start's cost to 0 + heuristicFxn val
    start->cost = 0 + heuristicFunction(start,end);
    // Enqueue start vertex
    pq.enqueue(start,0);
    start->setColor(YELLOW);
    inQueue.add(start);

    // While there are still elements in the pq to try
    while(!pq.isEmpty()){
        Vertex* v = pq.dequeue();
        inQueue.remove(v);

        v->visited = true;
        v->setColor(GREEN);

        // We can stop (reached end)
        if(v == end){
            // We have reached the end, deconstruct
            path.clear();

            Vertex* temp = v;
            path.insert(0,temp);

            while(temp->previous!=NULL){ // deconstruct
                temp = temp->previous;
                path.insert(0,temp);
            }
            break;
        }
        // For each unvisited neighbor of v vertex
        for (Vertex* n: graph.getNeighbors(v)){
            // And it's unvisited
            if(n->visited == false){
                // v's cost plus weight of edge
                Edge* e = graph.getEdge(v,n);
                double edgeCost = e->cost;
                double costToVertexN = v->cost + edgeCost;
                // If the costToVertexN < n->cost, we know this is a better way to get to
                // vertex n
                if(costToVertexN < n->cost){
                    n->cost = costToVertexN;
                    n->previous = v;
                    n->setColor(YELLOW);

                    // Check to see if pq already contains n
                    if(inQueue.contains(n)){ // Priority now includes heuristic
                        pq.changePriority(n,costToVertexN + heuristicFunction(n,end));
                    } else {
                        pq.enqueue(n,costToVertexN + heuristicFunction(n,end));
                    }
                }

            }
        }

    }
    return path;
}
Exemplo n.º 27
0
int main()
{
  // print my name and this assignment's title 
  cout << "LAB 11a: Write And Test A Priority Queue Template\n"; 
  cout << "Programmer: Jacky Chow\n"; 
  cout << "Editor(s) used: Notepad++\n"; 
  cout << "Compiler(s) used: Visual C++\n"; 
  cout << "File: " << __FILE__ << endl; 
  cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl << endl;
  
  PriorityQueue<int> pq;
  int temp;
  cout << "Created a PriorityQueue<int> named pq\n";
  cout << "Its size should be 0. It is: " << pq.size() << endl; 
  assert(0 == pq.size());
  if(pq.empty()) cout << "pq.empty() returned true that it was empty\n";
  else cout << "Error: pq.empty() returned false for empty PQ\n";
  assert(pq.empty());
  cout << "\nEnqueuing the ints 13, 8, 4, 20, 10 into pq\n";
  pq.enqueue(13);
  pq.enqueue(8);
  pq.enqueue(4);
  pq.enqueue(20);
  pq.enqueue(10);
  
  if(!pq.empty()) cout << "pq.empty() returned false that it was empty\n";
  else cout << "Error: pq.empty() returned true for a non-empty PQ\n";
  assert(!pq.empty());  
  cout << "\nIts size should now be 5. It is: " << pq.size() << endl;
  assert(5 == pq.size());  
  cout << "The front should be 20. It is: " << pq.front() << endl;
  assert(20 == pq.front()); 
  cout << "The back should be 10. It is: " << pq.back() << endl;
  assert(10 == pq.back());  
  
  //const copy constructor test
  {
    cout << "\nCreating const copy with copy constructor\n";
    const PriorityQueue<int> copy = pq;
    if(!copy.empty()) cout << "copy.empty() returned false that it was empty\n";
    else cout << "Error: copy.empty() returned true for a non-empty PQ\n";
    assert(!copy.empty());  
    cout << "Copy size should now be 5. It is: " << copy.size() << endl;
    assert(5 == copy.size());  
  }
  
  //operator= copy test
  {
    cout << "\nCreating copy with with operator=\n";
    PriorityQueue<int> copy;
    cout << "Should initially have size 0. It is: " << copy.size() << endl;
    assert(copy.empty());
    cout << "Assigning copy to = pq\n";
    copy = pq;
    if(!copy.empty()) cout << "copy.empty() returned false that it was empty\n";
    else cout << "Error: copy.empty() returned true for a non-empty copy\n";
    assert(!copy.empty());  
    cout << "Copy 2's size should now be 5. It is: " << copy.size() << endl;
    assert(5 == copy.size());  
    cout << "The front should be 20. It is: " << copy.front() << endl;
    assert(20 == copy.front()); 
    cout << "The back should be 10. It is: " << copy.back() << endl;
    assert(10 == copy.back());  
    cout << "Dequeuing the entire copy of pq: \n";
    for(; copy.size();)
      cout << copy.dequeue() << ' '; 
    cout << "\nCopy should now be size 0. It is: " << copy.size() << endl;
    assert(copy.empty());    
    if(copy.empty()) cout << "copy.empty() returned true that it was empty\n";
    else cout << "Error: copy.empty() returned false for an empty copy\n";
    assert(copy.empty()); 
  }
  
  temp = pq.dequeue();
  cout << "\nDequeuing root of pq. It should return 20. It is: " << temp << endl;
  assert(20 == temp);  
  
  cout << "\nIts size should now be 4. It is: " << pq.size() << endl;
  assert(4 == pq.size());    
  cout << "The front should be 13. It is: " << pq.front() << endl;
  assert(13 == pq.front());    
  cout << "The back should be 8. It is: " << pq.back() << endl;
  assert(8 == pq.back());    
  cout << "\nNow using clear to clear pq\n";
  
  pq.clear();
  cout << "Size should now be 0. It is: " << pq.size() << endl;
  assert(0 == pq.size());  
  if(pq.empty()) cout << "pq.empty() returned true that it was empty\n";
  else cout << "Error: pq.empty() returned false for empty PQ\n";
  assert(pq.empty());  
}
Exemplo n.º 28
0
/*
 *  Method: enqueueEdges
 *  Parameters: BasicGraph graph by reference
 *              PriorityQueue of Edge pointer variables
 *              that comprise the graph
 *  - - - - - - - - - - - - - - - - - - - - - - - - - -
 *  Returns by reference a Priority Queue of Edge pointer
 *  variables according to their randomly assigned weights.
 *  This PQueue is then used to construct the minimum spanning tree.
 */
void enqueueEdges(BasicGraph& graph, PriorityQueue<Edge*>& pqueue) {
    Set<Edge*> graphEdges = graph.getEdgeSet();
    for(Edge* edge : graphEdges) {
        pqueue.enqueue(edge, edge->cost);
    }
}