// Just for testing.
int main(int argc, char* argv[]) {
  Queue<int> Q;
  Q.Enqueue(1);
  Q.Enqueue(2);
  assert(2 == Q.Max());
  assert(1 == Q.Dequeue());  // 1
  assert(2 == Q.Max());
  assert(2 == Q.Dequeue());  // 2
  Q.Enqueue(3);
  assert(3 == Q.Max());
  assert(3 == Q.Dequeue());  // 3
  try {
    Q.Max();
  }
  catch (const exception& e) {
    cout << e.what() << endl;  // throw
  }
  try {
    Q.Dequeue();
  }
  catch (const exception& e) {
    cout << e.what() << endl;  // throw
  }
  return 0;
}
Exemplo n.º 2
0
int main()
{
    //queue<char*> words;
    Queue<char*> words;
	//Kristian: Липсват подсказващи съобщения.
    int n;
    cin>>n;
    //81094: I would insert spaces around the operators for a better esthetical view.
	//Kristian: Решението определено не решава задачата. При аргумент 3 имаш повтарящи се поддуми. Пример: aaa.
	//Kristian: При аргумент 4, не се генерират всички възможни поддуми. Пример: липсва bbbb.Освен това, отново има повтарящи се: abcd.
    for(int i=1;i<=n;i++)
    {
        int* arr=new int[i];
        int symbol=(int)'a';
        for(int j=0;j<pow(3,i);j++)
        {
            IntToAnyNumSystem(j,n,arr,i);
            char* word=new char[i];
            for(int i1=0;i1<i;i1++)
                word[i1]=(char)(arr[i1]+symbol);
            word[i]='\0';
            words.Enqueue(word);
        }
        delete[] arr;
    }
    while(!words.Empty())
       printf ("%s \n", words.Dequeue());
    return 0;
}
Exemplo n.º 3
0
int main()
{
   Queue<int> line;                                  // Line-up waiting to get in

   int patrons = InitialPatrons;                     // Number people in the Inn

   int time, i, arrivals, departures, entry_time;

   Randomize();                                      // Seed the random numbers

   for (time=0; time<300; time++)                    // Each minute from 8 - 1.
   {
      arrivals = RandomNum(num_arrive[time/60]);     // arriving this minute

      for (i=0; i<arrivals; i++) line.Enqueue(time); // End of the line

      departures = RandomNum(num_depart[time/60]);   // leaving this minute

      patrons -= departures;                         // bye-bye

      while (patrons < Capacity && !line.Empty())
      {
         entry_time = line.Front();                  // move from line into Inn
         line.Dequeue();
         patrons++;
      }
      cout << setw(4) << time << ":  " << arrivals << "  " << departures
           << setw(5) << patrons << endl;
   }

   cout << setw(4) << time << ":  " << arrivals << "  " << departures
        << setw(5) << patrons << endl;

   return (0);
}
Exemplo n.º 4
0
/*----- S o l v e M a z e (  ) -----

PURPOSE
Attempt to find the shortest path through the maze.

INPUT PARAMETERS
maze           -- the maze object to be traversed
positionQueue  -- the queue of current and future positions

RETURN VALUE
true  -- a path was found.
false -- failed to find a path.
*/
bool SolveMaze(Maze &maze, Queue &positionQueue)
{
/*
const int Open     = -1;	// Cell is open
const int Obstacle = -2;	// Cell is an obstacle
const int StartCell= -3;	// Cell is the start cell
const int GoalCell = -4;	// Cell is the goal cell
const int PathCell = -5;	// Cell is on the shortest path
*/ 
	Position curPos = maze.Start();
	Position neighbor;
	positionQueue.Enqueue(curPos);
	maze.Mark(curPos, 0);
	int distance;

	while(!positionQueue.Empty()){
		curPos = positionQueue.Dequeue();
		distance = maze.State(curPos);
		neighbor = openPosition(maze, curPos);
		while(curPos != neighbor){
			maze.Mark(neighbor, distance + 1);
			if(neighbor == maze.Goal())
				return true;
			positionQueue.Enqueue(neighbor);
			neighbor = openPosition(maze, curPos);
		}
	}
	return false;
}
Exemplo n.º 5
0
    bool isBipartite() {
        int source;
        int* color = new int[num_of_vertices + 1];
        for (int i = 0; i <= num_of_vertices; ++i)color[i] = -1;
        while ((source = stillUncoloured(color, num_of_vertices + 1)) != 0) {
            color[source] = 0;
            Queue q;
            q.Enqueue(source);
            while (!q.isEmpty()) {
                int u = q.Dequeue();
                Node*p = g[u].head;
                while (p) {
                    if (color[p->x] == -1) {
                        color[p->x] = (color[u] == 0) ? 1 : 0;
                        q.Enqueue(p->x);
                    } else if (color[p->x] == color[u]) {
                        return false;
                    }
                    p = p->next;
                }
            }

        }
        delete [] color;
        return true;
    }
Exemplo n.º 6
0
int main()
{
    Queue<int> queue;
    queue.Enqueue(10);
    queue.Enqueue(20);
    cout<<queue.IsEmpty()<<endl;
    cout<<queue.IsFull()<<endl;
    cout<<queue.Front()<<endl;
    queue.Dequeue();
    cout<<queue.Front()<<endl;
    return 0;
}
Exemplo n.º 7
0
/*----- S o l v e M a z e (  ) ------------------------------

PURPOSE
Attempt to find the shortest path through the maze.

INPUT PARAMETERS
maze           -- the maze object to be traversed
positionQueue  -- the queue of current and future positions

RETURN VALUE
true  -- a path was found.
false -- failed to find a path.
-------------------------------------------------------------*/
bool SolveMaze(Maze &maze, Queue &positionQueue)
{
	maze.Mark(maze.Start(), 0);					// Mark the maze start with distance 0
	positionQueue.Enqueue(maze.Start());		// Add maze start to queue
	CellState distance = 0;						// cell distance from start

	while (!positionQueue.Empty())
	{
		while (((maze.State(positionQueue.Head() + StepEast)) == Open)			// While head position has any unmarked neighbors
			|| ((maze.State(positionQueue.Head() + StepSouth)) == Open) 
			|| ((maze.State(positionQueue.Head() + StepWest)) == Open) 
			|| ((maze.State(positionQueue.Head() + StepNorth)) == Open)) 	
		{
			distance = maze.State(positionQueue.Head());										// Set distance

			if ((maze.State(positionQueue.Head() + StepEast)) == Open)							// Is east cell open?
			{
				maze.Mark(positionQueue.Head() + StepEast, distance + 1);						// Mark cell with proper distance
				if ((positionQueue.Head() + StepEast) == maze.Goal())							// Is open cell the goal?
					return true;
				
				positionQueue.Enqueue(positionQueue.Head() + StepEast);							// Add it to the queue
			}
			else if ((maze.State(positionQueue.Head() + StepSouth)) == Open)					// Is south cell open?
			{
				maze.Mark(positionQueue.Head() + StepSouth, distance + 1);						// Mark cell with proper distance
				if ((positionQueue.Head() + StepSouth) == maze.Goal())							// Is open cell the goal?
					return true;
				
				positionQueue.Enqueue(positionQueue.Head() + StepSouth);						// Add it to the queue
			}
			else if ((maze.State(positionQueue.Head() + StepWest)) == Open)						// Is West cell open?
			{
				maze.Mark(positionQueue.Head() + StepWest, distance + 1);						// Mark cell with proper distance
				if ((positionQueue.Head() + StepWest) == maze.Goal())							// Is open cell the goal?
					return true;
				
				positionQueue.Enqueue(positionQueue.Head() + StepWest);							// Add it to the queue
			}
			else if ((maze.State(positionQueue.Head() + StepNorth)) == Open)					// Is North cell open?
			{
				maze.Mark(positionQueue.Head() + StepNorth, distance + 1);						// Mark cell with proper distance
				if ((positionQueue.Head() + StepNorth) == maze.Goal())							// Is open cell the goal?
					return true;
				
				positionQueue.Enqueue(positionQueue.Head() + StepNorth);						// Add it to the queue
			}
		}
		positionQueue.Dequeue();
	}
	return false;
}
Exemplo n.º 8
0
void main()
{
	Queue<Rechteck*> queue;

	queue.Enqueue(new Rechteck(3, 4));
	queue.Enqueue(new Rechteck(6, 7));

	while (queue.GetCount() > 0)
	{
		auto rechteck = queue.Dequeue();
		delete rechteck;
	}
}
void LevelOrders(Tree T){
	Queue<node_t> Q;
	node_t tmp = Root(T);
	while (Label(tmp,T) != ""){
		cout << Label(tmp,T);
		node_t child = Leftmost_Child(tmp,T);
		while (Right_Sibling(child,T) != 0){
			Q.Enqueue(child);
			child = Right_Sibling(child,T);
		}
		Q.Enqueue(child);
		tmp = Q.Front();
		Q.Dequeue();
	}

}
Exemplo n.º 10
0
int main()
{
	for (int i = 0; i < 10; i++)
	{
		q.Enqueue(i);
	}

	for (int i = 0; i < 10; i++)
	{
		cout << "Queue item: " << q.Peek() << endl;		//Get the item to print
		q.Dequeue();	// Removing the item from the queue
	}

	getchar();

	return 0;
}
Exemplo n.º 11
0
int main()
{
    /*Driver Code to test the implementation
    Printing the elements in Queue after each Enqueue or Dequeue
    */
    Queue Q; // creating an instance of Queue.
    Q.Enqueue(2);
    Q.Print();
    Q.Enqueue(4);
    Q.Print();
    Q.Enqueue(6);
    Q.Print();
    Q.Dequeue();
    Q.Print();
    Q.Enqueue(8);
    Q.Print();
}
Exemplo n.º 12
0
int main()
{
    Queue<int, 3> Q;

    try
    {
        Q.Enqueue(1);
        Q.Enqueue(3);
        Q.Enqueue(4);
        while (!Q.Empty())
            std::printf("%d\n", Q.Dequeue());
    }
    catch (Queue<int, 3>::BadOp& e)
    {
        std::puts("Queue::BadOp caught!");
    }
}
Exemplo n.º 13
0
bool testQueue()
{
	Queue<int> myQ;
	myQ.Enqueue(1);
	myQ.Enqueue(2);
	myQ.Enqueue(3);

	assert(myQ.Front() == 1);

	myQ.Dequeue();
	assert(myQ.Front() == 2);

	Queue<int> myQcopy(myQ);
	assert(myQcopy.Front() == 2);
	myQcopy.Dequeue();
	assert(myQcopy.Front() == 3);

	return true;
}
Exemplo n.º 14
0
 int * BFS(int source) {
     int* dist = new int[num_of_vertices + 1];
     for (int i = 0; i <= num_of_vertices; ++i)dist[i] = -1;
     dist[source] = 0;
     Queue q;
     q.Enqueue(source);
     while (!q.isEmpty()) {
         int u = q.Dequeue();
         Node*p = g[u].head;
         while (p) {
             if (dist[p->x] == -1) {
                 dist[p->x] = dist[u] + 1;
                 q.Enqueue(p->x);
             }
             p = p->next;
         }
     }
     return dist;
 }
Exemplo n.º 15
0
int main(){

  Queue q;

  for(int i=0;i<9;i++){
    q.Enqueue(i);
  }

  q.print();
  std::cout << "front is : "<< q.Front() << std::endl;

  for(int i=0;i<=10;i++){
    q.Dequeue();
  }

  q.print();
  std::cout << "front is : "<< q.Front() << std::endl;


  return 0;
}
Exemplo n.º 16
0
void Matrix::BFS(Point start, int rows, int cols, LinkedList<Point>& path)
{
	if (matrix[start.getX()][start.getY()] == '#')
	{
		cout << "The position is invalid!\n";
		return;
	}

	int dr[] = { 0, -1, 0, 1 };
	int dc[] = { -1, 0, 1, 0 };
	Queue<Point> queue;

	queue.Enqueue(start);
	matrix[start.getX()][start.getY()] = '?';

	cout << "Starting from point: ";
	cout << "(" << start.getX() << ", " << start.getY() << ")" << " : " << endl;

	while (!queue.isEmpty())
	{
		start = queue.Front();
		queue.Dequeue();

		for (int d = 0; d < 4; d++)
		{
			Point nextPos(start.getX() + dr[d], start.getY() + dc[d]);
			
			if (canPass(rows, cols, nextPos))
			{
				path.Push_Back(nextPos);
				queue.Enqueue(nextPos);

				matrix[nextPos.getX()][nextPos.getY()] = '?';			
			}
		}
	}
}
Exemplo n.º 17
0
int main(void){
    
    int N = 10;    

    // instantiate a Queue that stores integers
    //
    Queue<int> *q = new Queue<int>();
     
    for(int i=1; i < N; ++i)
        q->Enqueue(i); 
    q->PrintItems();
    if(q->IsEmpty()) cout << "Queue is empty\n";    

    // Access the front in the Queue
    //
    cout << "Front Item: " << q->Front() << endl;
    cout << "Removing Front Item\n";
    // Remove the front item in the Queue
    q->Dequeue();

    // Print the Items
    q->PrintItems();
    return 0;
}
Exemplo n.º 18
0
int TPTCPChild(void* Ptr){

	static char* SuccessResponse =
		" 200 OK\n"
		"Content-type: text/html\n"
		"Connection: close\n"
		"\n";
	static char *NotFoundResponse =
		" 404 Not Found\n"
		"Content-type: text/html\n"
		"Connection: close\n"
		"\n";
	static char* BadMethodResponse =
		" 501 Method Not Implemented\n"
		"Content-type: text/html\n"
		"Connection: close\n"
		"\n";
	
	int Recv = 0;
	int Send = 0;
	int SentLength = 0;
	int ReadLength = 0;
	int FileLength = 0;
	int PktSize = 1024;

	char *Method;
	char *URI;
	char *Version;
	char *ReceiveBuf;
	char *HeaderBuf;
	char ContentBuf[1025];
	char * FileBuffer = 0;
	
	Method = (char *)malloc(sizeof(char)* 20);
	URI = (char *)malloc(sizeof(char)* 256);
	Version = (char *)malloc(sizeof(char)* PktSize);
	HeaderBuf = (char *)malloc(sizeof(char)* PktSize);
	ReceiveBuf = (char *)malloc(sizeof(char)* PktSize);
	
	FILE * f;
	SOCKET TCPSock;
	
	while (1){
		mtx_lock(&ThMutex);
		if (SocketQueue.size == 0){
			cnd_wait(&cond, &ThMutex);
		}
		TCPSock = SocketQueue.Dequeue(&SocketQueue);
		mtx_unlock(&ThMutex);

		while (1){
			if ((Recv = recv(TCPSock, ReceiveBuf, PktSize, 0)) == SOCKET_ERROR){
				printf("recv() failed with error code: %d\n", WSAGetLastError());
				return 0;
			}
			else{
				sscanf(ReceiveBuf, "%s %s %s", Method, URI, Version);
				if (strcmp(Method, "GET") == 0){
					
					if (strcmp(URI, "/") == 0 || strcmp(URI, "/index.html") == 0){
						f = fopen("index.html", "r");
						strcat(Version, SuccessResponse);
					}
					else if (strcmp(URI, "/readme.html") == 0){
						f = fopen("readme.html", "r");
						strcat(Version, SuccessResponse);
					}
					else{
						f = fopen("404error.html", "r");
						strcat(Version, NotFoundResponse);
					}
				}
				else{
					f = fopen("404error.html", "r");
					strcat(Version, BadMethodResponse);
				}
				fseek(f, 0, SEEK_END);
				FileLength = ftell(f);
				fseek(f, 0, SEEK_SET);
				
				HeaderBuf = Version; //Store the header file
				while (1){
					if ((Send = send(TCPSock, HeaderBuf, strlen(HeaderBuf), 0)) == SOCKET_ERROR){
						printf("\nConnection failed with error code: %d\n", WSAGetLastError());
						break;
					}
					else{
						/*debug info*/
						//printf("send0 is finished\n");
						break;
					}
				}
				while (SentLength < FileLength){
					ReadLength = fread(ContentBuf, sizeof(char), 1024, f);
					ReadLength = send(TCPSock, ContentBuf, ReadLength, 0);
					SentLength = SentLength + ReadLength;
				}
				fclose(f);
				SentLength = 0;
				//Sleep(500);
				closesocket(TCPSock);
				break;
			}
		}
	}
}
Exemplo n.º 19
0
void QueueTest()
{
	Queue<int> aqueue;

	cout << "Testing isEmpty(): " << aqueue.isEmpty() << endl;
	cout << "Testing Enqueue()" << endl;
	for (int i = 0; i < 10; i++)
	{
		try
		{
			aqueue.Enqueue(i);
		}
		catch (Exception & except)
		{
			cout << except << endl;
		}
	}

	cout << "Testing isEmpty(): " << aqueue.isEmpty() << endl;
	cout << endl << "Testing Dequeue()" << endl;
	for (int i = aqueue.Size(); i >= 0; i--)
	{
		try
		{
			aqueue.Dequeue();
		}
		catch (Exception & except)
		{
			cout << except << endl;
		}
		cout << aqueue.Size() << endl;
	}

	for (int i = 0; i < 10; i++)
	{
		aqueue.Enqueue(i);
		cout << aqueue.Front() << endl;
	}

	cout << endl << "Testing copy constructor" << endl;
	Queue<int> bqueue = aqueue;
	cout << endl << "BSIZE " << bqueue.Size() << endl << endl;
	for (int i = bqueue.Size(); i > 4; i--)
	{
		cout << bqueue.Dequeue() << endl;
	}

	cout << endl << "Testing assignment operator" << endl;
	aqueue = bqueue;

	cout << "Testing isEmpty(): " << aqueue.isEmpty() << endl;
	for (int i = aqueue.Size(); i > 0; i--)
	{
		cout << aqueue.Dequeue() << endl;
	}

	cout << "Testing the ability to manipulate data at the front of the queue" << endl;
	aqueue.Enqueue(99);
	int &num = aqueue.Front();

	cout << "The value stored at the front of the queue is: " << num << endl;
	num = num + 1;
	cout << "The value stored at the front of the queue is now: " << aqueue.Front() << endl;
}
Exemplo n.º 20
0
int main()
{
    Queue<int> q;
    q.Enqueue(42);
    std::cout << q.Dequeue() << std::endl;
}
Exemplo n.º 21
0
//reads from command line
int main(int argc, char *argv[])
{	
	//shows how program needs to run if command line entry was wrong
	if (argc != 2)
	{
		cout << "usage: "<< argv[0] <<  " </../nameOfFile.txt>" << endl;
	}
	//actual program
	else
	{
		string fileName = argv[1];
		ifstream file(fileName);
		
		//check if did not open
		if (!file.is_open())
		{
     	cout<< "Could not open file" << endl;
		}
    	//if file is open
    	else 
    	{
    		//greats Queue object of types students
    		Queue<Student> studentQueue;
    		    		
    		//declared variables for implementation
    		int numWindows;		//for getting number of windows
			int timeEnter;		//for when student enters queue
			int numberStudents;	//for reading when number of students arrive at a time to the queue
			int studentTimeNeeded;		//for reading in time needed at windwo
			int queueTimeTotal = 0; 	//for end calculations
			int windowsOpen;			//for simulation loop to end simulation
			int studentArr = 0;	 		//for placement into array for student wait times
			int numStudents;			//number of students total in queue
			string line;				//for reading in line
    		
    		//READ FROM FILE
    		
    		//gets number of windows
    		getline(file, line);
    		numWindows = atoi(line.c_str());			//gets first line, number of windows
    		Window* windows = new Window[numWindows];	//creates array of type window
    		
    		while (!file.eof())
    		{
    			//gets student time entered queue
    			getline(file, line);
    			timeEnter = atoi(line.c_str());
    			
    			//gets number of students who enter at specific time
    			getline(file, line);
    			numberStudents = atoi(line.c_str());
    			
    			//loop to get next lines depending on how many students entered queue at said time
    			//adds students to the queue
    			for (int i = 0; i < numberStudents; ++i)
    			{
    				getline(file, line);
    				studentTimeNeeded = atoi(line.c_str());
    				Student student(studentTimeNeeded, timeEnter); 
    				studentQueue.Enqueue(student);
    			}
    		}
    		
    		//creates int array for wait times while in the queue
    		int* studentQueueArray = new int[studentQueue.getQueueSize()];
    		numStudents = studentQueue.getQueueSize();
    		
    		//RUN SIMULATION
    		
    		//main simulation for assignment
    		for (int time = 0; time < 1000000000; ++time)
    		{	
    			//for ending the simulation, counts every window if open and if the queue is empty
    			windowsOpen = 0;
    			for (int i = 0; i < numWindows; ++i)
    			{
    				if (windows[i].isOpen() && studentQueue.isQueueEmpty())
    				{
    					++windowsOpen;
    				}
    			}
    			//end simulation if number of open windows equals total number of windows
    			if (windowsOpen == numWindows)
    			{
    				//reset idle times for all windows
    				for (int i = 0; i < numWindows; ++i)
    				{
    					windows[i].resetIdle();
    				}
    				//ends simulation
    				break;
    			}
    			
    			//for adding student to window
    			for (int i = 0; i < numWindows; ++i)
    			{
    				//checks to see if queue is not empty, if it is no need to add students to window
    				if (!studentQueue.isQueueEmpty())
    				{
    					//gets the first student's data in the queue
    					Student getStudent = studentQueue.getQueueFront();
    					//checks if window is open and if time is greater than or equal to when student entered
	    				if (windows[i].isOpen() && (time >= getStudent.timeEnterQueue()))
	    				{
		    				windows[i].resetIdle(); //reset idle
	    					windows[i].getStudent(getStudent.windowTime(), time); //puts student at the window
	    					queueTimeTotal += getStudent.queueWait(time); //add students wait time to total, for mean
	    					studentQueueArray[studentArr] = getStudent.queueWait(time);	//puts wait time in array
	    					studentQueue.Dequeue();	//dequeue student						
	    					++studentArr;		//increment position in array for next student
	    				}
    				}
    				
    				//for incrementing idle for windows without students
    				if (windows[i].isOpen())
    				{
    					++windows[i].idle;
    				}
    				
    				//freeing up window if student is ready to leave
    				if (!windows[i].isOpen())
    				{
    					windows[i].canTakeStudent(time);
    				}
    			}
    		}
    		
			//DISPLAY DATA
			
			//student mean
			cout << "Mean student Wait time: " << (float) queueTimeTotal/numStudents << endl;;
			
			//student median
			sort(studentQueueArray, studentQueueArray + numStudents);	//sorts array
			//if total number of students is even
			if (numStudents % 2 == 0)
			{
				int a = (numStudents/2) - 1;
				int b = (numStudents/2);
				cout << "Median student wait time: " << (float) (studentQueueArray[a] + studentQueueArray[b])/2 << endl;
			}
			//total number of students is odd
			else
			{
				cout << "Median student wait time: " << (float) studentQueueArray[numStudents/2] << endl;
			}
			
			//longest wait, since sorted get the last number in the array
			cout << "Longest Student wait time: " << studentQueueArray[numStudents-1] << endl;
			
			//student Wait over 10
			int numWait10 = 0;
			for (int i = 0; i < numStudents; ++i)
			{
				if (studentQueueArray[i] > 10)
				{
					++numWait10;
				}
			}
			cout << "Number of Students waiting over 10 minutes: " << numWait10 << endl;
			
			//mean and longest window idle time
			int totalMaxIdle = 0;
			int longestMaxIdle = 0;
			int numOver5 = 0;
			for (int i = 0; i < numWindows; ++i)
			{
				totalMaxIdle += windows[i].getMaxIdle();
				if (longestMaxIdle < windows[i].getMaxIdle())
				{
					longestMaxIdle = windows[i].getMaxIdle();
				}
				if (windows[i].getMaxIdle() > 5)
				{
					++numOver5;
				}
			}
			cout << "Mean window idle time: " << (float) totalMaxIdle/numWindows << endl;
			cout << "Longest window idle time: " << longestMaxIdle << endl;
			cout << "Number of windows idle over 5 min: " << numOver5 << endl;
			
			//deallocating arrays to free up memory
			delete [] studentQueueArray;
			delete [] windows;
			
		}
		//closes file stream
		file.close();
	}
	return 0;	
}