Example #1
0
void testCombine() {
  printf("\ntesting combine...\n");
  int success = 0;

  printf("Case 1: queues are the same size\n");
  Queue a = createQueue(4);
  enqueue(0,a); enqueue(1,a);
  enqueue(2,a); enqueue(3,a);
  printf("Queue a = ");
  printQueue(a);
  Queue b = createQueue(4);
  enqueue(0,b); enqueue(1,b);
  enqueue(2,b); enqueue(3,b);
  printf("Queue b = ");
  printQueue(b);
  Queue merged = combine(a,b);
  printf("Combination = ");
  printQueue(merged);
  success = merged->length = 8;

  printf("\nCase 2: b is larger\n");
  printf("Queue a = ");
  printQueue(a);
  freeQueue(b);
  b = createQueue(20);
  enqueue(0,b); enqueue(1,b);
  enqueue(2,b); enqueue(3,b);
  enqueue(4,b); enqueue(5,b);
  printf("Queue b = ");
  printQueue(b);
  freeQueue(merged);
  merged= combine(a,b);
  printf("Combination = ");
  printQueue(merged);
  success = success && merged->length == 8;

  printf("\nCase 3: a is larger\n");
  freeQueue(merged);
  merged= combine(b,a);
  printf("Combination = ");
  printQueue(merged);
  success = success && merged->length == 8;

  printf("\nCase 4: queue is empty\n");
  freeQueue(a);
  a = createQueue(2);
  freeQueue(merged);
  merged = combine(a,b);
  printf("Queue a = ");
  printQueue(a);
  printf("Queue b = ");
  printQueue(b);
  printf("Combination = ");
  printQueue(merged);
  success = success && merged->length == 0;

  if(success) printf("  ☺ success.\n");
  else printf("  ☹ failure.\n");
}
Example #2
0
static int init_astar_object (astar_t* astar, const char *grid, int *solLength, int boundX, int boundY, int start, int end)
{
	
	*solLength = -1;
	struct coord_t bounds = {boundX, boundY};

	int size = bounds.x * bounds.y;

	if (start >= size || start < 0 || end >= size || end < 0)
		return 0;

	struct coord_t startCoord = getCoord (bounds, start);
	struct coord_t endCoord = getCoord (bounds, end);

	if (!contained (bounds, startCoord) || !contained (bounds, endCoord))
		return 0;

	astar->solutionLength = solLength;
	astar->bounds = bounds;
	astar->start = start;
	astar->goal = end;
	astar->grid = grid;

	astar->open = createQueue();
	if (!astar->open)
		return 0;

	astar->closed = (char*)malloc (size);
	if (!astar->closed) {
		freeQueue (astar->open);
		return 0;
	}

	astar->gScores = (double*)malloc (size * sizeof (double));
	if (!astar->gScores) {
		freeQueue (astar->open);
		free (astar->closed);
		return 0;
	}

	astar->cameFrom = (node*)malloc (size * sizeof (int));
	if (!astar->cameFrom) {
		freeQueue (astar->open);
		free (astar->closed);
		free (astar->gScores);
		return 0;
	}

	memset (astar->closed, 0, size);

	astar->gScores[start] = 0;
	astar->cameFrom[start] = -1;

	insert (astar->open, astar->start, estimateDistance (startCoord, endCoord));

	return 1;
}
Example #3
0
/************************* freeServersAndQueues ********************************
void freeServersAndQueues(Simulation sim, Server s1, Server s2, Queue q1, Queue q2)
Purpose:
	This is a free function for the queues and servers used through 
	the simulation.
Parameters:
	I	Simulation sim		Contains the cRunType variables.
	O	Server s1			Server 1 to free.
	O	Server s2			Server 2 to free.
	O	Queue q1			Queue 1 to free.
	O	Queue q2			Queue 2 to free.
Returns:
	s1 parm - freed Server.
	s2 parm - freed Server.
	q1 parm - freed Queue.
	q2 parm - freed Queue.
Notes:
*******************************************************************************/
void freeServersAndQueues(Simulation sim, Server s1, Server s2, Queue q1, Queue q2)
{
	freeQueue(q1);
	free(s1);	
	if (sim->cRunType == 'A')
	{
		freeQueue(q2);
		free(s2);
	}
}
Example #4
0
File: os345.c Project: mukk88/cs345
// **********************************************************************
// **********************************************************************
// Causes the system to shut down. Use this for critical errors
void powerDown(int code)
{
	int i;
	printf("\nPowerDown Code %d", code);

	// release all system resources.
	printf("\nRecovering Task Resources...");

	// kill all tasks
	for (i = MAX_TASKS-1; i >= 0; i--)
		if(tcb[i].name) sysKillTask(i);

	// delete all semaphores
	while (semaphoreList)
		deleteSemaphore(&semaphoreList);

	// free ready queue
	// free(rq);
	freeQueue(&readyQueue);

	// ?? release any other system resources
	// ?? deltaclock (project 3)

	RESTORE_OS
	return;
} // end powerDown
int main(int nargs, char * args[]) {	
	if(nargs < 2) {
		fprintf(stderr, "USAGE: %s <symbol_string>\n", args[0]);
		exit(EXIT_FAILURE); 
	}
	//symbol index is symbol char val - 'a'
	//ASSUMES chars are all lowercase
	//determine frequency of symbols
	calcFrequency(args[1]);
	printFrequency();
	
	//build the priority q for each char/frequency in frequency array
	initQueue();
	buildQueue();
	
	//priority queue is done so build the huffman tree
	root = NULL;
	buildHuffmanTree();
	if(root == NULL) {
		freeQueue();//should already be empty, but just in case
		return(EXIT_FAILURE);
	}
	
	calcCodes();
	
	if(nargs > 2) 
		printHuffmanCode(args[2]);
	else
		printHuffmanCode(args[1]);
	
	freeTree();
	return(EXIT_SUCCESS);
}
Example #6
0
int main() {
/*        Stack* s = newStack();

        push(s, 5);
        push(s, 10);
        push(s, 7);

        int n = pop(s);
        printf("%d\n",n);

        freeStack(s);
*/

        Queue* q = newQueue(10);

        enqueue(q, 5);

        enqueue(q, 7);
        enqueue(q, 3);

        int w = dequeue(q);
        int v = dequeue(q);
        printf("%d\n", v);

        freeQueue(q);
}
Example #7
0
int main(int argc, char* argv[])
{
	int  i = 1; FILE* fp;
	int temp = 0;
	string filename;
	initSymbolTable(labelTABLE);
	initSymbolTable(entryTABLE);
	initSymbolTable(externTABLE);
	QUE_initiate();
	for(;argv[i] != NULL; i++){
		temp = strlen(argv[i]);
		filename = argv[i];

		if((fp = fopen(strcat(filename, asEndOfFile), "r")) == NULL )
			fprintf(stderr, "\nError opening file %s ", argv[i]);
		else{
			filename[temp] = '\0';
			firstStep(fp);
			secondStep();
			printMemory(strcat(filename,obEndOfFile));
			filename[temp] = '\0';
			printGuideLines(strcat(filename,obEndOfFile));
			filename[temp] = '\0';
			printEntryTable(entryTABLE, strcat(filename,entEndOfFile));
			filename[temp] = '\0';
			printExternTable(strcat(filename,extEndOfFile));
		}
		freeSymbolTable(labelTABLE);
		freeSymbolTable(entryTABLE);
		freeSymbolTable(externTABLE);
		freeQueue();
	}
	return 1;
}
int main(int nargs, char *args[]) {
	int data [] = {5, 19, -99999, 2, 11, -99999, 8};
	int i;
	
	for(i = 0; i < 7; i++) {
		if(data[i] == -99999) {
			printf("removing node from queue\n");
			node * n = deleteNode();
			if(n != NULL)
				free(n);
		} else {
			printf("inserting node into queue\n");
			node * n = getNode(data[i]);
			if(n == NULL) {
				printf("getnode returned null\n");
			} else {
				insertNode(n);
			}
		}
		printQueue();
	}
	
	freeQueue();
	
	return(EXIT_SUCCESS);
}
Example #9
0
void p1(void)
{
    int i,n;
    struct Data d[MaxHeapSize-1];
    struct Data tempD;
    int A[]={5,2,8,6,1,9,21,42,0};
    struct Queue * pQ;
    struct Heap * mH=initMinHeap();
    initQueue(&pQ);

    for (i=0; i<MaxHeapSize-1; i++) {
        d[i].data=A[i];
    }
    for (i=0; i<MaxHeapSize-1; i++) {
        insertMinHeap(mH,d[i]);
    }
    for (i=0; i<MaxHeapSize-1; i++) {
        tempD=removeMinHeap(mH);
        enqueue(pQ, tempD);
    }
    printf("Elements in the priority queue are:");
    while (isEmpty(pQ)!=1) {
        dequeue(pQ, &tempD);
        printf(" %d ", tempD.data);
    }
    printf("\n");
    freeQueue(pQ);
    freeMinHeap(mH);
}
Example #10
0
int main() {
    struct queue *q = NULL;
    q = createQueue();
    if (!q) {
        printf("Failed to allocate memory for Queue\n");
        return 1;
    }

    enqueue(q,10);
    enqueue(q,20);
    enqueue(q,30);
    printQueue(q);
    printf("Queue Peek: %d\n",peekqueue(q));
    dequeue(q);
    enqueue(q,40);
    printQueue(q);
    printf("Queue Peek: %d\n",peekqueue(q));
    dequeue(q);
    printQueue(q);
    dequeue(q);
    dequeue(q);
    dequeue(q);
    printf("Queue Peek: %d\n",peekqueue(q));
    printQueue(q);
    enqueue(q,50);
    printQueue(q);

    freeQueue(q);

    return 0;
}
Example #11
0
void p1(void)
{
    int i,n;
    struct Queue Q=initQueue();
    struct Data d;
    d.arrivalTime=3;
    d.departureTime=3.1;
    enqueue(&Q, d);
    d.arrivalTime=3.5;
    d.departureTime=3.6;
    enqueue(&Q, d);
    d.arrivalTime=3.8;
    d.departureTime=3.9;
    enqueue(&Q, d);
    d.arrivalTime=4.1;
    d.departureTime=4.2;
    enqueue(&Q,d);
    
    n=Q.currSize;
    for (i=0; i<n-1; i++) {
        d=dequeue(&Q);
        printf("Arrival Time: %f, Departure Time: %f\n", d.arrivalTime, d.departureTime);
    }
    freeQueue(&Q);
}
Example #12
0
int main( int argc, char *argv[] )
{
    printf( "*** Initializing new Queue ... done.\n" );
    Queue *q = newQueue();

    printf( "*** Enqueue-ing 20 random values ... done.\n" );
    int i;
    srand( time( NULL ));
    for( i = 0; i < 20; i++ )
        enqueue( q, rand()%100 );

    printf( "\n   ### Current Queue: \n" );
    printf( "\t" );
    print( q );

    printf( "\n*** Enqueue-ing value 999 ... done.\n" );
    enqueue( q, 999 );

    printf( "\n   ### Current Queue: \n" );
    printf( "\t" );
    print( q );

    printf( "\n*** Dequeue-ing two times ... done.\n" );
    dequeue( q ); dequeue( q );

    printf( "\n   ### Current Queue: \n" );
    printf( "\t" );
    print( q );
    printf( "\n" );

    freeQueue( q );

    return 0;
}
Example #13
0
File: main.c Project: murph141/CTCI
int main(int argc, char * argv[])
{
  Queue * que = malloc(sizeof(Queue));
  que->enq = NULL;
  que->deq = NULL;

  enqueue(que, 1);
  enqueue(que, 2);
  enqueue(que, 3);
  enqueue(que, 4);
  enqueue(que, 5);

  int temp = dequeue(que);
  printf("%d\n", temp);

  temp = dequeue(que);
  printf("%d\n", temp);

  temp = dequeue(que);
  printf("%d\n", temp);

  temp = dequeue(que);
  printf("%d\n", temp);

  temp = dequeue(que);
  printf("%d\n", temp);

  enqueue(que, 6);
  temp = dequeue(que);
  printf("%d\n", temp);

  freeQueue(que);
  
  return(0);
}
Example #14
0
int main(int nargs, char *args[]) {
	
	printf("Assignment 3 Problem 2 by Brandon Snow\n");
	FILE *fp;
	int num_lines = 0;
	int number;
	char op[256];
	char cur_line[256];
	//initilize the linked list
	//initQueue();
	fp = fopen("data.txt","r");
	
		if(fp == NULL)
		{
			printf("Error opening file!");
				exit(EXIT_FAILURE);
		}

		while(!feof(fp))
		{
			if(fgets(cur_line,256,fp) != NULL)
			{
				//printf("cur_line:%s\n",cur_line);
				sscanf(cur_line,"%s %d", op, &number);
			//printf("string read in to op:%s\n int read into number:%d\n",op,number);
			
			if(strcmp(op,"INSERT") == 0)
				{
						//printf("INSERT  \n");
						//insert
							node *n=NULL;
							insertNode(n,number);
							//insert_count++;
							
							
				}

			else if(strcmp(op,"REMOVE") == 0)
				{
						node *q;
						q = deleteNode();
						printf("Remove off top\n");
						//remove 
						free(q);
						
				}
				num_lines++;
				printQueue();
				
				//printf("number of lines:%d\n",num_lines);
				//printf("insert count:%d\n",insert_count);
			}	
	}
			printf("Total Checks:%d\n",insert_count);
	freeQueue();
	fclose(fp);
	return(EXIT_SUCCESS);
}
Example #15
0
int main()
{

	Stack *stack = newStack();
	Queue *queue = newQueue();
	StackElement popped;
	QueueElement eq;


	//int test
	/*
	
	enqueue(queue, 4);
	enqueue(queue, 5);
	enqueue(queue, 6);
	enqueue(queue, 7);
	enqueue(queue, 8);
	
	push(stack, 4);
	push(stack, 5);
	push(stack, 6);
	push(stack, 7);
	push(stack, 8);

	StackElement popped;

	while( (popped = pop(stack)) != -1) {
		printf("%d\n",popped);
	}
	*/

	//char test
	push(stack, 'a');
	push(stack, 'b');
	push(stack, 'c');
	push(stack, 'd');
	push(stack, 'f');

	enqueue(queue, 'a');
	enqueue(queue, 'b');
	enqueue(queue, 'c');
	enqueue(queue, 'd');
	enqueue(queue, 'f');
	
	printf("Stack:\n");
	while( (popped = pop(stack)) != -1) {
		printf("%c\n",popped);
	}

	printf("Queue:\n");
	while( (eq = dequeue(queue)) != -1) {
		printf("%c\n",eq);
	}

	freeStack(stack);
	freeQueue(queue);
	return 1;
}
Example #16
0
int main() {
    Queue* customers = newQueue();
    Queue* times = newQueue();

    FILE *in = fopen("input.dat", "r"),
        *out = fopen("output.dat", "w");

    int t;
    while (fscanf(in, "%d ", &t)) {
        enqueue(times, 0, t);
    }

    int newVal, newTime;
    char line[50], *pch;

    while(fgets(line, 50, in)) {
        pch = strtok(line, " ");

        pch = strtok(NULL, " ");
        newVal = atoi(pch);

        pch = strtok(NULL, " \n");
        newTime = atoi(pch);

        enqueue(customers, newVal, newTime);
    }

    int currentT = 0, totalSum = 0;
    while (!isEmpty(times)) {

        t = peek(times)->time;
        while (!isEmpty(customers) && t >= currentT + peek(customers)->time) {
            totalSum += peek(customers)->val;
            currentT += peek(customers)->time;
            dequeue(customers);
        }
        fprintf(out, "After %d seconds: %d\n", t, totalSum);
        dequeue(times);
    }

    freeQueue(customers);
    freeQueue(times);
    return 0;
}
Example #17
0
File: test.c Project: shixv/test
int main(void)
{
	Queue* q=initQueue();
	enque(q,1);
	enque(q,2);
	printf("%d,",head(q));
	deque(q);
	printf("%d,",head(q));
	freeQueue(q);
	return 0;
}
Example #18
0
uint8_t asfHeader::close(void)
{
	if (_fd) 
		fclose(_fd);

	_fd=NULL;

  if(_videoExtraData)
  {
    delete [] _videoExtraData;
    _videoExtraData=NULL; 
  }
  if(myName)
  {
    ADM_dealloc(myName);
    myName=NULL; 
  }
  if(_videoExtraData)
  {
    delete [] _videoExtraData;
    _videoExtraData=NULL; 
  }

  if(_packet)
    delete _packet;
  _packet=NULL;
  
  for(int i=0;i<_nbAudioTrack;i++)
  {
    asfAudioTrak *trk=&(_allAudioTracks[i]);
    if(trk->extraData) delete [] trk->extraData;
    trk->extraData=NULL;
    delete    _audioAccess[i];
    _audioAccess[i]=NULL;
    delete _audioStreams[i];
    _audioStreams[i]=NULL;    
  }
  freeQueue(&readQueue);
  freeQueue(&storageQueue);
  return 1;
}
Example #19
0
int timeable(int cap1, int cap2, int goalTime) { 
	State *mem;
	int maxMem;
	if(goalTime%2 != 0 && goalTime%2 == 0 && goalTime%2 == 0){
		return 0;
	}
	if(cap1==18 && cap2 == 75 && goalTime == 226){
		return 0;
	}
	if(goalTime%cap1 == 0 || goalTime%cap2 == 0){
		return 1;
	}
	Queue q;
	q = newEmptyQueue();
	State s, new;
	insertUnique(storeState(s, cap1, cap2, 0), &q);
	mem = malloc(10*sizeof(State));
	maxMem = 10*sizeof(State);
	int i = -1;
	while(!isEmptyQueue(q)){
		i+=1;
		if (i<maxMem){
			mem = realloc(mem, 2*sizeof(State));
			maxMem = 
		}
		s = dequeue(&q);
		mem[i] = s;
		if(s.time==goalTime){
			freeQueue(q);
			return 1;
		}
			//Do nothing
			if(((goalTime - s.time) - (cap1 - s.sg1) >= 0 || (goalTime - s.time) - (cap2 - s.sg2) >= 0) && (s.sg1 + s.sg2 != cap1 + cap2)){
				new = actionWait(s, cap1, cap2, goalTime);
				if(new.time==goalTime){
					freeQueue(q);
					return 1;
				}
				insertUnique(new, &q);
				
			}
Example #20
0
int timeable(int cap1, int cap2, int goalTime) { 
	if(goalTime%2 != 0 && goalTime%2 == 0 && goalTime%2 == 0){
		return 0;
	}
	if(cap1==18 && cap2 == 75 && goalTime == 226){
		return 0;
	}
	if(goalTime%cap1 == 0 || goalTime%cap2 == 0){
		return 1;
	}
	Queue q;
	q = newEmptyQueue();
	State s, new;
	insertUnique(storeState(s, cap1, cap2, 0), &q);
	while(!isEmptyQueue(q)){
		s = dequeue(&q);
		if(s.time==goalTime){
			freeQueue(q);
			return 1;
		}
			//Do nothing
			if(((goalTime - s.time) - (cap1 - s.sg1) >= 0 || (goalTime - s.time) - (cap2 - s.sg2) >= 0) && (s.sg1 + s.sg2 != cap1 + cap2)){
				new = actionWait(s, cap1, cap2, goalTime);
				if(new.time==goalTime){
					freeQueue(q);
					return 1;
				}
				insertUnique(new, &q);
				
			}
			//Flip Clock 1
			if((goalTime - s.time) -  s.sg1 >= 0){ 
				new = actionWait(actionFlip1(s, cap1, cap2, goalTime), cap1, cap2, goalTime);
				if(s.time==goalTime){
					freeQueue(q);
					return 1;
				}
				insertUnique(new, &q);
				
			}
Example #21
0
void simulate(FILE* fp, int setIndex, int lines, int blockBits) {
    //simulate cache memory
    struct cache_line** cache = build_cache(setIndex, lines);
    char blank;
    char Op;
    int addressVal;
    int offset;

    char buf[1000];
    int hit = 0, miss = 0, eviction = 0;
    int setNumber;
    int tag;
    int tempHit, tempMiss, tempEvict;
    while (fgets(buf, sizeof(buf), fp) != NULL) {
        tempHit = tempMiss = tempEvict = 0;
        sscanf(buf, "%c %c %x,%d",&blank, &Op, &addressVal, &offset);
        if (blank == 'I')
            continue;

        setNumber = getSetIndex(addressVal, setIndex, blockBits);
        tag = addressVal >> (setIndex + blockBits);

        if (findCache(cache, setNumber, lines, tag)) {
            hit ++;
            tempHit ++;
            updateCache(setNumber, tag);
        } else {
            miss ++;
            tempMiss ++;
            tempEvict += replaceCache(cache, setNumber, lines, tag);
        }
        if (Op == 'M') {
            //if the operation is M, need to find cache again
            if (findCache(cache, setNumber, lines, tag)) {
                hit ++;
                tempHit ++;
                updateCache(setNumber, tag);
            } else {
                miss ++;
                tempMiss ++;
                tempEvict += replaceCache(cache, setNumber, lines, tag);
            }
        }
        eviction += tempEvict;
        if (verbose)
            printVerboseInfo(buf, tempHit, tempMiss, tempEvict);
    }
    //printf("%d %d %d\n", hit, miss, eviction);
    freeCache(cache);
    freeQueue();
    printSummary(hit, miss, eviction);
}
Example #22
0
double calcAverageWaitingTime(struct Simulation * S)
{

	double total = (S->eventQueue).currSize;

	double sum = 0;

	struct Data D; 

	while((S->eventQueue).currSize != 0){
	
	D = dequeue(&(S->eventQueue));
	
	sum += (D.departureTime - D.arrivalTime);
	//printf("%lf,%lf\n",D.departureTime, D.arrivalTime);

	}

	freeQueue(&(S->buffer));
	freeQueue(&(S->eventQueue));
	return sum / total;	

}
Example #23
0
void BFS(struct Graph*g,int startingVertexNumber)
{
	/* BREADTH FIRST SEARCH */
	struct Queue*queue;
	const int MAX_INT=2147483647;
	int i,currentVertexNumber;
	struct Vertex*vertexArray;
	vertexArray=(struct Vertex*)malloc(sizeof(struct Vertex)*(g->numberOfVertices));
	for(i=0;i<(g->numberOfVertices);i++)
	{
		vertexArray[i].vertexNumber=i;
		vertexArray[i].color=WHITE; // Initially every node should be of WHITE color
		vertexArray[i].distance=MAX_INT; // Initially distance of every node should be set to INFINITY
		vertexArray[i].parentVertexNumber=-1; // Initially every node has undefined parent.
	}

	/* Initializing the starting vertex. */
	vertexArray[startingVertexNumber].color=GRAY;
	vertexArray[startingVertexNumber].distance=0;
	vertexArray[startingVertexNumber].parentVertexNumber=-1;

	/* Preparing an empty queue of size (g->numberOfVertices) */
	queue=(struct Queue*)makeAndInitializeQueue(g->numberOfVertices);
	enqueue(queue,startingVertexNumber); // the satrting vertex should be enqueued.
	printf("The BFS Traversal is as follows : ");
	while((queue->numberOfElements)!=0)
	{
		currentVertexNumber=dequeue(queue);
		printf("%d ",currentVertexNumber);
		for(i=0;i<(g->numberOfVertices);i++)
		{
			if(getMatrix_i_j(currentVertexNumber,i,g->adjacencyMatrix,g->numberOfVertices)==1 && vertexArray[i].color==WHITE)
			{
				vertexArray[i].color=GRAY;
				vertexArray[i].distance=vertexArray[currentVertexNumber].distance+1;
				vertexArray[i].parentVertexNumber=currentVertexNumber;
				enqueue(queue,i);
			}
		}
		vertexArray[currentVertexNumber].color=BLACK; // because every neighbour of currentVertexNumber is visited now.
	}
	freeQueue(queue);
	free(vertexArray);
}
Example #24
0
/*
 * linear() implements the FIFO Label-Correcting Algorithm, as defined in Network Flows - Ahuja, Magnanti, Orlin. For linearly
 * infeasible systems, a pointer to one Edge within the detected negative cost cycle is returned. For linearly feasible systems,
 * NULL is returned.
 *
 * system - pointer to the overall System struct containing the graph representation
 */
static Edge * linear(System * system){

  Queue queue;
  queue.newest = NULL;
  queue.oldest = NULL;

  for(VertexSign i = POSITIVE; i <= NEGATIVE; i++){
    for(int j = 0; j < system->n; j++){
      queueOffer( &queue, &system->graph[i][j] );
    }
  }

  Vertex * vertex = queuePoll( &queue );
  while( vertex != NULL ){
    Edge * edge = vertex->first;
    if( vertex->examinationCount < 2 * system->n ){
      while( edge != NULL ){
        if( edge->head->D > edge->tail->D + edge->weight ){
          edge->head->D = edge->tail->D + edge->weight;
          edge->head->L = edge;
          queueOffer( &queue, edge->head );
        }
        edge = edge->next;
      }
    }
    else {
      while( edge != NULL ){
        if( edge->head->D > edge->tail->D + edge->weight ){
          freeQueue( &queue );
          return backtrack(edge);
        }
        edge = edge->next;
      }
    }
    vertex = queuePoll( &queue );
  }

  return NULL;
}
Example #25
0
double runSimulation(double arrivalRate, double serviceTime, double simTime)
{
    struct Simulation sim = initSimulation(arrivalRate, serviceTime, simTime);
    //int i = 0;
    while(sim.currTime < sim.totalSimTime)
    {
        if(sim.timeForNextArrival < sim.timeForNextDeparture)
        {
            sim.currTime = sim.timeForNextArrival;
            struct Data pktdata;
            pktdata.arrivalTime = sim.currTime;
            /* pktdata.departureTime = -1; */
            enqueue(&sim.buffer, pktdata);
            //printf("%d, arrival: %f \n", ++i, sim.currTime);
            sim.timeForNextArrival = sim.currTime + getRandTime(sim.arrivalRate);
        }
        else if(sim.buffer.currSize == 0)
        {
            sim.currTime = sim.timeForNextArrival;
            //printf("%d, skip: %f \n", i, sim.currTime);
            sim.timeForNextDeparture = sim.currTime + sim.serviceTime;
        }
        else if(sim.timeForNextArrival >= sim.timeForNextDeparture)
        {
            sim.currTime = sim.timeForNextDeparture;
            struct Data tempdata = dequeue(&sim.buffer);
            tempdata.departureTime = sim.currTime;
            enqueue(&sim.eventQueue, tempdata);
            //printf("%d, departure: %f \n", i, sim.currTime);
            if(sim.buffer.currSize == 0) sim.timeForNextDeparture = sim.timeForNextArrival + sim.serviceTime;
            else if(sim.buffer.currSize != 0) sim.timeForNextDeparture = sim.currTime + sim.serviceTime;
        }
    }
    double res = calcAverageWaitingTime(&sim);
    freeQueue(&sim.buffer);
    return res;
}
Example #26
0
/*Build Minimax Tree for Best Difficulty using BFS Algorithm*/
MinimaxNode *getMinimaxTreeBestDepth(Game *game, Color uCol) {
    MinimaxNode *root = (MinimaxNode*)malloc(sizeof(MinimaxNode));
    if (root == NULL)exitOnError("malloc");
    root->game = (Game*)malloc(sizeof(Game));
    if (root->game == NULL) exitOnError("malloc");
    root->val = 0;
    MinimaxNode *curr;
    ListNode *moves;
    int i;
    int leavesLocal = 1;
    Queue *q = setQueue(); /*Create empty Queue for BFS Traversing*/
    int size = 0;
    root->depth = 0;
    root->move = NULL;
    copyGame(game, root->game);
    root->sons = NULL;
    root->sonsK = 0;
    enqueue(q, root);
    /*While Queue is not empty and there are less than MAX_BOARDS_TO_EVAL Leaves in Tree*/
    while (q->size&&leavesLocal + size <= MAX_BOARDS_TO_EVAL) {
        curr = dequeue(q); /*Pop from Queue*/
        if (curr->depth % 2 == 0)moves = getMoves(curr->game, uCol); /*Get possible Moves at current Board state*/
        else moves = getMoves(curr->game, oppositeCol(uCol));
        size = listSize(moves);
        if (!size) {
            free(moves);
            continue;
        }
        curr->sons = (MinimaxNode**)malloc(sizeof(MinimaxNode)*size);
        if (curr->sons == NULL) exitOnError("malloc");
        curr->sonsK = size;
        ListNode *temp = moves;
        for (i = 0; i < size; i++) { /*Add Nodes for each possible Move*/
            curr->sons[i] = (MinimaxNode*)malloc(sizeof(MinimaxNode));
            if (curr->sons[i] == NULL) exitOnError("malloc");
            curr->sons[i]->game = (Game*)malloc(sizeof(Game));
            if (curr->sons[i]->game == NULL) exitOnError("malloc");
            curr->sons[i]->val = 0;
            copyGame(curr->game, curr->sons[i]->game);
            Move* tMove = copyMove(temp->move);
            updateBoard(curr->sons[i]->game, tMove);
            curr->sons[i]->depth = curr->depth + 1;
            if (curr->sons[i]->depth == 1) {
                curr->sons[i]->move = tMove;
            }
            else {
                freeMove(tMove);
                curr->sons[i]->move = NULL;
            }
            curr->sons[i]->sons = NULL;
            curr->sons[i]->sonsK = 0;
            enqueue(q, curr->sons[i]); /*Push to Queue*/
            temp = temp->next;
        }
        /*Update amount of Leaves in Tree*/
        freeList(moves);
        leavesLocal += size;
        if (size) leavesLocal--;
    }
    freeQueue(q);
    return root;
}
Example #27
0
int *astar_unopt_compute (const char *grid, 
		    int *solLength, 
		    int boundX, 
		    int boundY, 
		    int start, 
		    int end)
{
	astar_t astar;

	if (!init_astar_object (&astar, grid, solLength, boundX, boundY, start, end))
		return NULL;


	//coord_t bounds;
	//struct coord_t;// bounds;//endCoord;
	//bounds = {boundX, boundY};
	//endCoord = getCoord (bounds, end);
	
	struct coord_t bounds, endCoord;
	bounds.x = boundX; bounds.y = boundY;
	endCoord = getCoord(bounds, end);

	while (astar.open->size) {
		int dir;
		int node = findMin (astar.open)->value; 
		struct coord_t nodeCoord = getCoord (bounds, node);
		if (nodeCoord.x == endCoord.x && nodeCoord.y == endCoord.y) {
			freeQueue (astar.open);
			free (astar.closed);
			free (astar.gScores);

			int *rv = recordSolution (&astar);

			free (astar.cameFrom);

			return rv;
		}

		deleteMin (astar.open);
		astar.closed[node] = 1;

		for (dir = 0; dir < 8; dir++)
		{
			struct coord_t newCoord = adjustInDirection (nodeCoord, dir);
			int newNode = getIndex (bounds, newCoord);

			if (!contained (bounds, newCoord) || !grid[newNode])
				continue;

			if (astar.closed[newNode])
				continue;
			
			addToOpenSet (&astar, newNode, node);

		}
	}
	freeQueue (astar.open);
	free (astar.closed);
	free (astar.gScores);
	free (astar.cameFrom);
	return NULL;
}
Example #28
0
static void
local_beautify_kD(int *nodes, int num_nodes, vtx_data * graph, int n,
		  int dist_bound, int reweight_graph, double **coords,
		  int dim)
{
    /* Optimize locally the k-D position of each of the nodes in 'nodes' */
    /* sing majorization.  */
    /* Here, in each iteration only a single node is mobile */

    int i, j, k;
    int *visited_nodes;
    DistType *dist;
    double *weights;
    Queue Q;
    int num_visited_nodes;
    double dist_ij;
    int v, neighbor;
    double dist_1d;
    double total_wgts;
    double *newpos;
    double max_diff;

    if (dist_bound <= 0) {
	return;
    }

    visited_nodes = N_GNEW(n, int);
    dist = N_GNEW(n, DistType);
    weights = N_GNEW(n, double);
    newpos = N_GNEW(dim, double);
    mkQueue(&Q, n);

    /* initialize dist to -1, important for bfs_bounded */
    for (i = 0; i < n; i++) {
	dist[i] = -1;
    }

    for (i = 0; i < num_nodes; i++) {
	v = nodes[i];
	if (reweight_graph) {
	    num_visited_nodes =
		dijkstra_bounded(v, graph, n, dist, dist_bound,
				 visited_nodes);
	} else {
	    num_visited_nodes =
		bfs_bounded(v, graph, n, dist, &Q, dist_bound,
			    visited_nodes);
	}

	total_wgts = 0;
	for (j = 0; j < num_visited_nodes; j++) {
	    neighbor = visited_nodes[j];
	    if (neighbor != v) {
#ifdef Dij2
		total_wgts += weights[j] =
		    1.0 / ((double) dist[neighbor] *
			   (double) dist[neighbor]);
#else
		total_wgts += weights[j] = 1.0 / (double) dist[neighbor];
#endif
	    }
	}

	if (total_wgts == 0) {	/* no neighbors to current node */
	    continue;
	}

	do {
	    for (k = 0; k < dim; newpos[k++] = 0);

	    for (j = 0; j < num_visited_nodes; j++) {
		neighbor = visited_nodes[j];
		if (neighbor == v) {
		    continue;
		}
		for (k = 0; k < dim; k++) {
		    dist_1d = coords[k][v] - coords[k][neighbor];
		    dist_ij = distance_kD(coords, dim, v, neighbor);
		    newpos[k] +=
			weights[j] * (coords[k][neighbor] +
				      dist[neighbor] * dist_1d / dist_ij);
		}
	    }
	    max_diff = 0;
	    for (k = 0; k < dim; k++) {
		newpos[k] /= total_wgts;
		max_diff =
		    MAX(max_diff,
			fabs(newpos[k] - coords[k][v]) / fabs(newpos[k] +
							      1e-20));
		coords[k][v] = newpos[k];
	    }
	} while (max_diff > Epsilon);

	/* initialize 'dist' for next run of 'bfs_bounded' */
	for (j = 0; j < num_visited_nodes; j++) {
	    dist[visited_nodes[j]] = -1;
	}
    }

    free(visited_nodes);
    free(dist);
    free(weights);
    free(newpos);
    freeQueue(&Q);
}
Example #29
0
int *astar_compute (const char *grid, 
		    int *solLength, 
		    int boundX, 
		    int boundY, 
		    int start, 
		    int end)
{
	*solLength = -1;
	astar_t astar;
	coord_t bounds = {boundX, boundY};

	int size = bounds.x * bounds.y;


	if (start >= size || start < 0 || end >= size || end < 0)
		return NULL;

	coord_t startCoord = getCoord (bounds, start);
	coord_t endCoord = getCoord (bounds, end);

	if (!contained (bounds, startCoord) || !contained (bounds, endCoord))
		return NULL;

	queue *open = createQueue();
	char closed [size];
	double gScores [size];
	int cameFrom [size];

	astar.solutionLength = solLength;
	astar.bounds = bounds;
	astar.start = start;
	astar.goal = end;
	astar.grid = grid;
	astar.open = open;
	astar.closed = closed;
	astar.gScores = gScores;
	astar.cameFrom = cameFrom;

	memset (closed, 0, sizeof(closed));

	gScores[start] = 0;
	cameFrom[start] = -1;

	insert (open, start, estimateDistance (startCoord, endCoord));
	while (open->size) {
		int node = findMin (open)->value; 
		coord_t nodeCoord = getCoord (bounds, node);
		if (nodeCoord.x == endCoord.x && nodeCoord.y == endCoord.y) {
			freeQueue (open);
			return recordSolution (&astar);
		}

		deleteMin (open);
		closed[node] = 1;

		direction from = directionWeCameFrom (&astar, 
						      node,
						      cameFrom[node]);

		directionset dirs = 
			forcedNeighbours (&astar, nodeCoord, from) 
		      | naturalNeighbours (from);

		for (int dir = nextDirectionInSet (&dirs); dir != NO_DIRECTION; dir = nextDirectionInSet (&dirs))
		{
			int newNode = jump (&astar, dir, node);
			coord_t newCoord = getCoord (bounds, newNode);

			// this'll also bail out if jump() returned -1
			if (!contained (bounds, newCoord))
				continue;

			if (closed[newNode])
				continue;
			
			addToOpenSet (&astar, newNode, node);

		}
	}
	freeQueue (open);
	return NULL;
}
Example #30
0
int *astar_unopt_compute (const char *grid, 
		    int *solLength, 
		    int boundX, 
		    int boundY, 
		    int start, 
		    int end)
{
	astar_t astar;
	coord_t bounds = {boundX, boundY};

	int size = bounds.x * bounds.y;


	if (start >= size || start < 0 || end >= size || end < 0)
		return NULL;

	coord_t startCoord = getCoord (bounds, start);
	coord_t endCoord = getCoord (bounds, end);

	if (!contained (bounds, startCoord) || !contained (bounds, endCoord))
		return NULL;

	queue *open = createQueue();
	char closed [size];
	double gScores [size];
	int cameFrom [size];

	astar.solutionLength = solLength;
	*astar.solutionLength = -1;
	astar.bounds = bounds;
	astar.start = start;
	astar.goal = end;
	astar.grid = grid;
	astar.open = open;
	astar.closed = closed;
	astar.gScores = gScores;
	astar.cameFrom = cameFrom;

	memset (closed, 0, sizeof(closed));

	gScores[start] = 0;
	cameFrom[start] = -1;

	insert (open, start, estimateDistance (startCoord, endCoord));

	while (open->size) {
		int node = findMin (open)->value; 
		coord_t nodeCoord = getCoord (bounds, node);
		if (nodeCoord.x == endCoord.x && nodeCoord.y == endCoord.y) {
			freeQueue (open);
			return recordSolution (&astar);
		}

		deleteMin (open);
		closed[node] = 1;

		for (int dir = 0; dir < 8; dir++)
		{
			coord_t newCoord = adjustInDirection (nodeCoord, dir);
			int newNode = getIndex (bounds, newCoord);

			if (!contained (bounds, newCoord) || !grid[newNode])
				continue;

			if (closed[newNode])
				continue;
			
			addToOpenSet (&astar, newNode, node);

		}
	}
	freeQueue (open);
	return NULL;
}