Example #1
0
int main(void) {

	initHeap();
	initHeap();
	printBlock((struct MemBlock*)memPool);
	printf("Adresse: %p \n", memPool);
	printf("Absolute Adresse: %p \n",rel_to_Abs(7));
	printf("Relative Adresse: %d \n",abs_to_Rel(0x404107));
	printFreeBlocks();
	return EXIT_SUCCESS;
}
Example #2
0
int main() {

    int i;
    int vals[10];
    struct heapStruct *h;
    h = initHeap();

    // Insert from input stream.
    h = readIn(h);
    // print it
    printHeap(h);

    // Delete some and print delete and new heap
    for (i=0; i<9; i++) {
        printf("Delete %d\n",removeMin(h));
        printHeap(h);
    }
    freeHeap(h);

    // Test out array initialization.
    vals[0] = 12, vals[1] = 3, vals[2] = 18, vals[3] = 14, vals[4] = 5;
    vals[5] = 9, vals[6] = 1, vals[7] = 7; vals[8] = 2, vals[9] = 13;

    sort(vals, 10);

    for (i=0; i<10; i++)
        printf("%d ", vals[i]);
    printf("\n");

    system("echo \"done\"");
    return 0;
}
Example #3
0
Heap *createHeap(Heap_cmp_func cmp_func_p, int64_t capacity)
{
  int error = NO_ERROR;
  Heap *heap_p = NULL;

  assert(cmp_func_p != NULL);

  if (capacity < LEAST_HEAP_SIZE) {
    capacity = LEAST_HEAP_SIZE;
  }

  heap_p = (Heap*)malloc(sizeof(Heap));
  if (heap_p == NULL) {
    error = ER_GENERIC_OUT_OF_VIRTUAL_MEMORY;
    goto end;
  }

  initHeap(heap_p);

  error = expandHeap(heap_p, capacity);
  if (error != NO_ERROR) {
    goto end;
  }

  heap_p->base_size = capacity;
  heap_p->cmp_func_p = cmp_func_p;

end:

  if (error != NO_ERROR && heap_p != NULL) {
    destroyHeapAndSetNull(heap_p);
  }

  return heap_p;
}
Example #4
0
int main() {
    // declarare lista vida
    Element **array;
    int nrListe, j, sumElemente = 0;
	
    printf("Cate liste vrei?");
    scanf("%d", &nrListe);
    array = create_array(nrListe, &sumElemente);
    // Afisare liste
    for(j=0;j<nrListe;j++) {
		printf("\n Lista [%d]\n", j);
		Afisare(array[j]);
	}
    printf("\n");
    
    
    // Definim un nou heap in care vom tine toate elementele
    struct heapStruct *h;
    h = initHeap();
    // Testam adaugarea primelor elemente din fiecare lista
    for(j=0;j<nrListe;j++) 
		insert(h, array[j]->valoare, j);
    printHeap(h);
	
	// Incepem sa punem primul element de pe heap primul
	int *result;
	result = (int*)malloc(sizeof(int)*sumElemente);
	int c = 0;
	printf("Marimea la heap: %d", nrListe);
	printf("Cate elemente vom avea: %d", sumElemente);
	while( nrListe > 0) {         
		heapElement min;
		int i, k;
		min = removeMin(h);
		i = min.list_index;
		k = min.value;
		printf("\n [Valoare|index] = [%d|%d]\n", k, i);
		nrListe--;
		// Trebuie sa stergem nodul cu indexul i
		StergereElement(&array[i]);
		
		
		result[c++] = k;
		if (array[i] != NULL && c < 100)  {
			insert(h, array[i]->valoare, i);         
			nrListe++;
		}
	}
	
	int i;
	printf("\n");
	for(i=0;i<sumElemente;i++) 
		printf("%d  ", result[i]);
	printf("\n");
	
	// In absenta lui free apareau anumite erori interesante
    free(array);

    return 0;
}
Example #5
0
int main () {

    initHeap();

    List * list = nil();
    int i, j;
    for (i = 0; i < 5; i++) {
        List * inner = nil();
        for (j = 0; j < 5; j++)
        {
            Position * p = alloc(sizeof(Position), NULL, NULL);
            inner = cons((void *)p, inner);
        }
        list = cons((void *)inner, list);
    }

    printHeap(HEAP);
    printf("%d\n", heapSize(HEAP));


    release((void *)list);

    printf("========\n");
    printHeap(HEAP);

    return 0;
}
Example #6
0
void load_initHeap(void) {
	initHeap();
#ifndef NDEBUG
	/* allocate a lot of memory at the beginning to make the beginning of shared libraries more
	 * predictable */
	free(malloc(MAX_MEM));
#endif
}
Example #7
0
int main() {
  Heap *loadH = NULL;
  loadH = initHeap(loadH, loadComp, freeLoad);

  int i;
  for (i=0; i < 10; ++i) {
    registerLoad(loadH, NULL);
  }

  produce(30, loadConsume);
  destroyHeap(loadH);
  return 0;
}
Example #8
0
int main() {

    int i;
    int vals[10];
    struct heapStruct *h;
    h = initHeap();

    // Test out individual inserts.
    insertMine(h, 7);
    insertMine(h, 3);
    insertMine(h, 5);
    insertMine(h, 12);
    insertMine(h, 2);
    insertMine(h, 8);
    insertMine(h, 14);
    insertMine(h, 9);
    insertMine(h, 1);
/* 
 
    insert(h, 7);
    insert(h, 3);
    insert(h, 5);
    insert(h, 12);
    insert(h, 2);
    insert(h, 8);
    insert(h, 4);
    insert(h, 9);
    insert(h, 1);
*/
    printHeap(h);

    for (i=0; i<9; i++) {
        printf("Delete %d\n",removeMax(h)); //-----------------------------------------------------------------change here
        printHeap(h);
    }
    freeHeap(h);
    
    // Test out array initialization.
    vals[0] = 12, vals[1] = 3, vals[2] = 18, vals[3] = 14, vals[4] = 5;
    vals[5] = 9, vals[6] = 1, vals[7] = 7; vals[8] = 2, vals[9] = 13;
    
    sort(vals, 10);
    
    for (i=0; i<10; i++)
        printf("%d ", vals[i]);
    printf("\n");
    
 
    return 0;
}
Example #9
0
void readFromFile(char *fileName)
{
	char c; charCount = 0;
	printProc("Reading from file... ");
	printStatus("DONE",8);
	FILE *fp = fopen(fileName, "rb");
	if(fp==NULL)
		showError(2);
	while((c=fgetc(fp))!=EOF)
		if(mark[c]== 0)
			mark[c] = ++charCount, freq[charCount] = 1, charSet[charCount] = c;
		else
			freq[mark[c]]++;
	initHeap(charCount);
	fclose(fp);
}
Example #10
0
int main()
{
    printf("Enter Time Limit : ");
    scanf("%f",&TIME_LIMIT);
    int i, j;
    srand(time(NULL));
    Heap *heap;
    Ball **ball;
    Interaction *nextCollision;
    heap = initHeap();
    ball = (Ball **)malloc(PARTICLE_COUNT * sizeof(Ball *));
    gnuplotPipe = initPipe();
    for(i = 0; i < PARTICLE_COUNT; i++)
    {
        logFile[i] = initGraph(i);
        gnuplotGraphPipe[i] = initGraphPipe(i);
    }
    for(i = 0; i < PARTICLE_COUNT; i++)
    {
        ball[i] = initBallRandom(i);
        insertToHeap(heap, eventWallCollideX(heap, ball[i]));
        insertToHeap(heap, eventWallCollideY(heap, ball[i]));
        for(j = 0; j < i; j++)
            insertToHeap(heap, eventBallCollide(heap, ball[i], ball[j]));
    }
    while(sim_time < TIME_LIMIT)
    {
        nextCollision = getNextEvent(heap);
        simulateTo(ball, nextCollision->tstamp);
        printf("Collision at t=%lf\n", sim_time);
        resolveCollision(nextCollision);
        removeFromHeap(heap, nextCollision->interactee->id);
        scheduleEvent(ball, heap, nextCollision->interactee->id);
        if(nextCollision->interactor != NULL)
        {
            removeFromHeap(heap, nextCollision->interactor->id);
            scheduleEvent(ball, heap, nextCollision->interactor->id);
        }
    }
    fprintf(gnuplotPipe, "quit\n");
    saveGraph(ball);
    showGraph(ball);
    return 0;
}
Example #11
0
void* operator new[]( size_t Size)
{
	initHeap();
	void* pMem = malloc( Size );
#ifdef PSY_DEBUG // neilogd: stamp 0x69 over uninitialised memory.
	BcMemSet( pMem, 0x69, Size );
#endif
#ifdef MEM_DEBUG
	BcU32 BreakID = -1;
	if( gAllocID == BreakID )
	{
		BcBreakpoint;
	}

	BcPrintf( "PsyNew: %p - %u\n", pMem, gAllocID++ );
	printBacktrace();
#endif
	return pMem;
}
Example #12
0
void dijkstra(struct Matrix_Graph *mat_graph, struct Point_Graph *poi_graph, \
				int source)
{
	struct HeapNode *minNode;
	struct Heap heap;
	struct Edge *edge;

	initHeap(&heap, poi_graph, source);
	heapSort(heap.heapNode, heap.heap_size, \
			sizeof(struct HeapNode), compare);

	while (heap.heap_size != 0) {
		minNode = (struct HeapNode *)extractTop(heap.heapNode, \
			&(heap.heap_size), sizeof(struct HeapNode), compare);
		edge = poi_graph->node[minNode->to].start;
		while (edge) {
			decrease_key(mat_graph, &heap, source, minNode->to, edge);
			edge = edge->next;
		}
	}
}
Example #13
0
int main (int argc, char* argv[]) {
  int i; 
  pthread_t minions[MINIONS];

  /* Initialize Stuff */
  Knapsack* ks = initKnapsack(argv[1]);
  Heap* h = initHeap(DEFAULT_SIZE);
  ThreadArgs* ta = (ThreadArgs*)malloc(sizeof(ThreadArgs));
  ta->_ks = ks;
  ta->_h = h;

  /* Begin port of bb() */
  double rootUB = upperBound(ks, 0, ks->_capacity);
  Node* n = initNode(0, -1, rootUB, ks->_capacity, NULL);
  add(h, n);

  /* Create Minions */ 
  for ( i = 0; i < MINIONS; i++){
    pthread_create(&minions[i],NULL,minionDoWork,ta);
  }
  pthread_cond_signal(&ks->_cond);

  /* Return minions~ */
  for( i = 0; i < MINIONS; i++){
    pthread_join(minions[i],NULL);
  }

  /* Display Results */
  printf("Found solution: %d\n", ks->_lowerBound);
  printf("Best x=");
  for (i=0; i<ks->_nbItems-1; i++) {
    printf("%d,",ks->_bestX[i]);
  }
  printf("%d\n",ks->_bestX[ks->_nbItems-1]);
  printf("Nodes processed: %d\n", ks->_nodesProcessed);
  destroyKnapsack(ks);
  destroyHeap(h);
  free(ta);
  return 0;
}
Example #14
0
int main() 
{
	ElemType arr[] = {1, 7, 5, 3, 8, 6, 15, 13, 14};
	int i, n = sizeof(arr)/sizeof(arr[0]);

	pHeapHeader pHH = (pHeapHeader)malloc(sizeof(struct HeapHeader));
	initHeap(pHH, n);
    createHeap(pHH, arr, n);	

	InsertHeap(pHH, 10);
	for(i=0; i<pHH->currentSize; i++) {
		printf("%d\t", (pHH->point)[i]);
	}
	printf("\nMaxHeap value: %d\n", RemoveMax(pHH));
	for(i=0; i<pHH->currentSize; i++) {
		printf("%d\t", (pHH->point)[i]);
	}



	return 0;
}
Example #15
0
/*############################################################################*/
int main() {
    initHeap();
    printFreeBlocks();
    return 0;
}
Example #16
0
ox::Error init(Context *ctx) {
	ox::Error err = 0;
	err = initGfx(ctx);
	initHeap(); // this does nothing in userland builds
	return err;
}
Example #17
0
BOOLEAN mergeRuns(FILE ** sorted, int pagesize, int availableBuffers, FileList currentFiles, int * passes, int * runs, int totalRecordCount){
	RecordHeap rHeap;
	Buffer * bufferNodes;
	int bufferIndex;

/*Determine max files that can be merged in a run*/
/*That is available buffers -1 for the output buffer*/
/*This is also the output buffer indes*/
	int outputBuffIndex = availableBuffers -1;

/*Buffer array (of buffer nodes) where size of which is the number
of buffers available to store in memory*/
	bufferNodes = calloc(availableBuffers, sizeof(Buffer));
	if(!bufferNodes){
		fprintf(stderr, "Error: Failed to allocate buffer array\n");
		return FALSE;
	}

/*Allocate memory for record arrays for each buffer*/
	for(bufferIndex = 0; bufferIndex < availableBuffers; bufferIndex++){
		initBuffer(&bufferNodes[bufferIndex], pagesize);
	}

/*Initialise priority queue
It's size is the amount of files that can be merged in a run*/
/*outputBuffIndex is the last index in the buffer array*/
	if(initHeap(&rHeap, outputBuffIndex * pagesize) == FALSE){
		return FALSE;
	}

/*while more merging required, (more than 1 temporary file)*/
/*go through a pass*/
	while(currentFiles.fileCount > 1){
		int runCount = 0;
		/*Define first file to be the start of the file linked list*/
		FileNode * firstFileForRun = currentFiles.fileHeadNode;

		/*Run file list, is the files to be merged in the next pass*/
		FileList runFileList;/*= calloc(1, sizeof(FileList));*/

		float runsInPassFloat = ((float)currentFiles.fileCount/(float)(availableBuffers-1));
		int runsInPass = ceil(runsInPassFloat);

		initFileList(&runFileList);


/*while still merging required for pass*/
/*go through a run*/
		while(runCount < runsInPass){
			int buffersInUse = 0;
			int bufferIndex = 0;
			int init = 0;
			FileNode * currentRunFile = firstFileForRun;
			FILE * outputFile;
			
/*create new temp file for merge run, written to when output buffer is full*/
			if((outputFile = tmpfile()) == NULL){
				fprintf(stderr, "Error: Failed to create output temporary file for run\n");
				return FALSE;
			}

/*add file pointer to the file list for the next pass*/
			addFile(&runFileList,outputFile);

/*Read in pages from current files to buffers*/
			for(bufferIndex = 0; bufferIndex < outputBuffIndex; bufferIndex++){
				int recordPageIndex;
/*fill buffer with records from file*/
				if(currentRunFile->fp != NULL){
					for(recordPageIndex = 0; recordPageIndex < pagesize; recordPageIndex++){
						/*read in record*/
						Record record;
						if(fread(&record, sizeof(Record), 1, currentRunFile->fp) == 1){
							/*add record to page (records array)*/
							init++;
							if(addRecord(&bufferNodes[bufferIndex], record, pagesize, recordPageIndex) == FALSE)
								return FALSE;
		/*add record index to heap*/
							if(addToHeap(&rHeap, &bufferNodes[bufferIndex], recordPageIndex) == FALSE)
								return FALSE;
						}
		/*else reached file end*/
						else{
							/*temp file will be automatically deleted by the system*/
							fclose(currentRunFile->fp);
							currentRunFile->fp = NULL;
							/*removeFile(currentFiles, currentRunFile);*/
							/*add blank records*/
							/*int blankRecordCount;
							for(blankRecordCount = recordCount; blankRecordCount < pagesize; blankRecordCount++){
								int recordPageIndex = addBlankRecord(&bufferNodes[bufferIndex], pagesize);
								
								if(recordPageIndex < 0)
									return FALSE;
							}*/
							break;
						}
					}
					bufferNodes[bufferIndex].fileNode = currentRunFile;
					buffersInUse++;
					currentRunFile = currentRunFile->nextFileNode;
					if (currentRunFile == NULL)
						break;
				}
				else
					break;
			}
/*set firstFileForRun for next run*/
			firstFileForRun = currentRunFile;

/*while all buffers are not empty (there is still records in pages in
some buffer not including the output buffer)*/
			while(buffersInUse > 0 && rHeap.count > 0){
/*keep getting min record and writing to output buffer*/
/*get smallest record*/
				RecordIndex minIndex = removeMinHeap(&rHeap);
				if(minIndex.guildID == 0)
					return FALSE;
/*move smallest record from main buffer memory to output buffer*/
/*add record to output buffer*/
				addRecord(&bufferNodes[outputBuffIndex],
					minIndex.buff->pageRecords[minIndex.pgIndex], pagesize, bufferNodes[outputBuffIndex].recordCount);
/*remove the same record from original buffer*/
				removeRecord(minIndex.buff, minIndex.pgIndex);
/*if output buffer is full, write page to file*/
				if(bufferNodes[outputBuffIndex].recordCount == pagesize){
/*write page to file*/
					int written;
					written = fwrite(bufferNodes[outputBuffIndex].pageRecords, sizeof(Record),
						pagesize, outputFile);
					if(written !=pagesize){
						fprintf(stderr, "Error: Failed to write to output file, wrote %i records\n",written);
						return FALSE;
					}

					/*clear page in output buffer*/
					clearPage(&bufferNodes[outputBuffIndex], pagesize);
				}

/*if original buffer is empty, read in another page*/
				if(minIndex.buff->recordCount == 0){
					int recordPageIndex;
/*fill buffer with records from file*/
					for(recordPageIndex = 0; recordPageIndex < pagesize; recordPageIndex++){
						Record record;
						if(minIndex.buff->fileNode->fp != NULL){
							if(fread(&record, sizeof(Record), 1, minIndex.buff->fileNode->fp) == 1){
		/*add record to page (records array)*/
								if(addRecord(minIndex.buff, record, pagesize, recordPageIndex) == FALSE)
									return FALSE;
		/*add record index to heap*/
								if(addToHeap(&rHeap, minIndex.buff, recordPageIndex) == FALSE)
									return FALSE;
							}
		/*else reached file end*/
							else{
								/*temp file will be automatically deleted by the system*/
								fclose(minIndex.buff->fileNode->fp);
								minIndex.buff->fileNode->fp = NULL;
								/*removeFile(currentFiles, minIndex.buff->fileNode);*/
								break;
							}
						}
					}
				}
/*if buffer is still empty, then 0 records were read in,
therefore file is empty and the buffer is now free*/
				if(minIndex.buff->recordCount == 0)
					/*decrement buffers in use counter*/
					buffersInUse--;
			}

/*All files for run have been fully read*/
/*Write out records still in output buffer*/
			if(bufferNodes[outputBuffIndex].recordCount > 0){
/*Output buffer page was not full*/
				int i = 0;
				for(i = 0; i < pagesize; i++){
					if(bufferNodes[outputBuffIndex].pageRecords[i].GuildID != 0){
						fwrite(&bufferNodes[outputBuffIndex].pageRecords[i],
							sizeof(Record), 1, outputFile);
						removeRecord(&bufferNodes[outputBuffIndex], i);
					}
				}
			}
			/*Rewind outfile for future merge*/
			rewind(outputFile);
			runCount++;
		}
		/*set runFileListas new current file list*/
		freeFileNode(&currentFiles);
		currentFiles = runFileList;
		*passes = *passes+1;
		*runs = *runs + runCount;
		printf("Pass %i resulted in %i runs\n",*passes,runCount);
	}


/*FileList will contain link to only 1 temporary binary file*/
	if(currentFiles.fileCount != 1){
		fprintf(stderr, "Error: Number of files:%i is invalid\n",currentFiles.fileCount);
		return FALSE;
	}
	*sorted = currentFiles.fileHeadNode->fp;

	/*free allocated memory*/

	for(bufferIndex = 0; bufferIndex < availableBuffers; bufferIndex++){
		freeBuffer(&bufferNodes[bufferIndex]);
	}
	free(bufferNodes);

	freeHeap(&rHeap);

	freeFileNode(&currentFiles);

	/*free(currentFiles);*/

	return TRUE;
}
Example #18
0
void produce(unsigned int n, void *(*func)(void *)) {
  int maxHandle = 8, readyId=-1, nC = 0;
  Heap *wHeap = NULL, *restHeap = NULL;
  wHeap = initHeap(wHeap, loadComp, freeLoad);
  restHeap = initHeap(restHeap, loadComp, freeLoad);
  unsigned int minThreshold = maxHandle > n ? n : maxHandle;
  pthread_t thList[minThreshold];
  pthread_attr_t attr;
  pthread_attr_init(&attr);
#ifdef __linux__
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
#endif

  for (readyId=0; readyId < minThreshold; ++readyId) {
    unsigned int *iNew = (unsigned int *)malloc(sizeof(unsigned int));
    *iNew = readyId;
    Load *l = createLoad(iNew);
    l->thId = readyId;
    addLoad(wHeap, l);
    pthread_create(thList + readyId, &attr, func, l);
  }

  int i, minFreeLoadCount = minThreshold >> 1;
  if (readyId < n) {
    heapifyFromHead(wHeap);
    i = readyId;
    int chillThId = -1;
    Load *wHead = NULL;
    while (i < n) {
      printf("\033[32mwHeap: "); printHeap(wHeap, printLoad);
      printf("\n\033[33mrHeap: "); printHeap(restHeap, printLoad);
      printf("\ni:%d n:%d chillThId: %d\033[00m\n", i, n, chillThId);

      if ((wHead = peek(wHeap)) != NULL) {
        printf("wHead: %d\n", wHead->id);

        void *data = NULL;
        int join = pthread_join(thList[wHead->thId], &data);
        printf("newJoin: %d\n", join);
        if (! join) {
          printf("joined: %d\n", wHead->thId);
          if (data != NULL) {
            printf("\033[36m\nRetr %s :%d\033[00m\n", (char *)data, wHead->thId); 
            free(data);
          }
          chillThId = wHead->thId;
          printf("chillThId: %d\n", chillThId);
        #ifdef DEBUG
          printf("wHead->thId: %d\n", wHead->thId);
        #endif
          heapExtract(wHeap, (const void **)&wHead); 
          wHead->id = getAvailableId(restHeap);
          addLoad(restHeap, wHead); 
          printf("rHeap"); printHeap(restHeap, printLoad);
          wHead = NULL;
        }
      }

      if (getSize(wHeap) < minFreeLoadCount && peek(restHeap) != NULL) {
      #ifdef DEBUG
        printf("Peeked: %p\n", peek(restHeap));
        printf("\nrestHeap\n");
      #endif
        heapExtract(restHeap, (const void **)&wHead);
        if (wHead == NULL) continue;
      #ifdef DEBUG
        printf("wHead->thId:: %p\n", wHead);
      #endif
        wHead->thId = chillThId;
        *((int *)wHead->data) = i;

        addLoad(wHeap, wHead);
        int createStatus =\
          pthread_create(thList + wHead->thId, &attr, func, wHead);
        printf("createdStatus: %d i: %d\n", createStatus, i);
        if (! createStatus) {
          ++i;
        }
      }
    }
  }

  while (! isEmpty(wHeap)) {
    Load *tmpHead = NULL;
    if (! heapExtract(wHeap, (const void **)&tmpHead) && tmpHead != NULL) {
      void *data = NULL;
      if (! pthread_join(thList[tmpHead->thId], &data)) {
        if (data != NULL) {
          printf("i: %d Joined msg: %s\n", i, (char *)data);
          free(data);
        }
      }
    }
    freeLoad(tmpHead);
  }

  destroyHeap(wHeap);
  destroyHeap(restHeap);
}
Example #19
0
int main (int argc, char* argv[]) {
  /* Read from file input */
  FILE *fp;
  Item* temp;
  Knapsack* ks = (Knapsack*)malloc(sizeof(Knapsack));
  char* fName = argv[1];
  fp = fopen(fName,"r");
  fscanf(fp,"%d", &ks->_nbItems);

  // We randomly chose nbItems/4 as an initial heap size.
  // It's something to tweak as we go on
  Heap* h = initHeap(ks->_nbItems/4);
  ks->_items = (Item**)malloc(sizeof(Item*)*ks->_nbItems);
  ks->_lowerBound = 0;

  // Each row of input has an unused counter variable at the beginning.
  // We'll use fscanf to dump it into j. 
  int i, j;
  /* For each of the items, read in their values and create the node */
  for (i = 0; i < ks->_nbItems; i++) {
    ks->_items[i] = (Item*)malloc(sizeof(Item));
    fscanf(fp,"%d %d %d", &j, &ks->_items[i]->_value, &ks->_items[i]->_weight);
  }
  ks->_bestX = (char*)calloc(ks->_nbItems, sizeof(char));
  fscanf(fp,"%d",&ks->_capacity);

  fclose(fp);
  /* Sort 'em */
  qsort(ks->_items, ks->_nbItems, sizeof(Item*), compare); 

  /* Begin port of bb() */
  
  double rootUB = upperBound(ks, 0, ks->_capacity);
  // I don't understand why depth is -1 here but I'll go with it
  Node* n = initNode(0, -1, rootUB, ks->_capacity, NULL);
  add(h, n);

  /* Begin port of run() */
  int nodesProcessed = 0;
  while (!isEmpty(h)) {
    n = removeMax(h);
    if (n->_depth >= (ks->_nbItems-1)) {
      if (n->_value > ks->_lowerBound) {
        printf("tighten LB to %d\n", n->_value);
        ks->_lowerBound = n->_value;
        for (i=0; i < n->_depth+1; i++) {
          ks->_bestX[i] = n->_x[i];
        }
        for (i=n->_depth+1; i<ks->_nbItems; i++) {
          ks->_bestX[i] = 0;
        }
        destroyNode(n);
      }
    } else {
      processNode(ks, h, n);
      nodesProcessed++;
    }
  }
  printf("Found solution: %d\n", ks->_lowerBound);
  printf("Best x=");
  for (i=0; i<ks->_nbItems-1; i++) {
    printf("%d,",ks->_bestX[i]);
  }
  printf("%d\n",ks->_bestX[ks->_nbItems-1]);
  printf("Nodes processed: %d\n", nodesProcessed);
  // Fix those pesky memory leaks.
  destroyKnapsack(ks);
  destroyHeap(h);
  return 0;
}
Example #20
0
File: init.c Project: MLton/mlton
int GC_init (GC_state s, int argc, char **argv) {
  char *worldFile;
  int res;

  assert (s->alignment >= GC_MODEL_MINALIGN);
  assert (isAligned (sizeof (struct GC_stack), s->alignment));
  // While the following asserts are manifestly true,
  // they check the asserts in sizeofThread and sizeofWeak.
  assert (sizeofThread (s) == sizeofThread (s));
  assert (sizeofWeak (s) == sizeofWeak (s));

  s->amInGC = TRUE;
  s->amOriginal = TRUE;
  s->atomicState = 0;
  s->callFromCHandlerThread = BOGUS_OBJPTR;
  s->controls.fixedHeap = 0;
  s->controls.maxHeap = 0;
  s->controls.mayLoadWorld = TRUE;
  s->controls.mayPageHeap = FALSE;
  s->controls.mayProcessAtMLton = TRUE;
  s->controls.messages = FALSE;
  s->controls.oldGenSequenceSize = 0x100000;
  s->controls.ratios.copy = 4.0f;
  s->controls.ratios.copyGenerational = 4.0f;
  s->controls.ratios.grow = 8.0f;
  s->controls.ratios.hashCons = 0.0f;
  s->controls.ratios.live = 8.0f;
  s->controls.ratios.markCompact = 1.04f;
  s->controls.ratios.markCompactGenerational = 8.0f;
  s->controls.ratios.nursery = 10.0f;
  s->controls.ratios.ramSlop = 0.5f;
  s->controls.ratios.stackCurrentGrow = 2.0f;
  s->controls.ratios.stackCurrentMaxReserved = 32.0f;
  s->controls.ratios.stackCurrentPermitReserved = 4.0f;
  s->controls.ratios.stackCurrentShrink = 0.5f;
  s->controls.ratios.stackMaxReserved = 8.0f;
  s->controls.ratios.stackShrink = 0.5f;
  s->controls.summary = FALSE;
  s->controls.summaryFile = stderr;
  s->cumulativeStatistics.bytesAllocated = 0;
  s->cumulativeStatistics.bytesCopied = 0;
  s->cumulativeStatistics.bytesCopiedMinor = 0;
  s->cumulativeStatistics.bytesHashConsed = 0;
  s->cumulativeStatistics.bytesMarkCompacted = 0;
  s->cumulativeStatistics.bytesScannedMinor = 0;
  s->cumulativeStatistics.maxBytesLive = 0;
  s->cumulativeStatistics.maxHeapSize = 0;
  s->cumulativeStatistics.maxPauseTime = 0;
  s->cumulativeStatistics.maxStackSize = 0;
  s->cumulativeStatistics.numCardsMarked = 0;
  s->cumulativeStatistics.numCopyingGCs = 0;
  s->cumulativeStatistics.numHashConsGCs = 0;
  s->cumulativeStatistics.numMarkCompactGCs = 0;
  s->cumulativeStatistics.numMinorGCs = 0;
  rusageZero (&s->cumulativeStatistics.ru_gc);
  rusageZero (&s->cumulativeStatistics.ru_gcCopying);
  rusageZero (&s->cumulativeStatistics.ru_gcMarkCompact);
  rusageZero (&s->cumulativeStatistics.ru_gcMinor);
  s->currentThread = BOGUS_OBJPTR;
  s->hashConsDuringGC = FALSE;
  initHeap (s, &s->heap);
  s->lastMajorStatistics.bytesHashConsed = 0;
  s->lastMajorStatistics.bytesLive = 0;
  s->lastMajorStatistics.kind = GC_COPYING;
  s->lastMajorStatistics.numMinorGCs = 0;
  s->savedThread = BOGUS_OBJPTR;
  initHeap (s, &s->secondaryHeap);
  s->signalHandlerThread = BOGUS_OBJPTR;
  s->signalsInfo.amInSignalHandler = FALSE;
  s->signalsInfo.gcSignalHandled = FALSE;
  s->signalsInfo.gcSignalPending = FALSE;
  s->signalsInfo.signalIsPending = FALSE;
  sigemptyset (&s->signalsInfo.signalsHandled);
  sigemptyset (&s->signalsInfo.signalsPending);
  s->sysvals.pageSize = GC_pageSize ();
  s->sysvals.physMem = GC_physMem ();
  s->weaks = NULL;
  s->saveWorldStatus = true;

  initIntInf (s);
  initSignalStack (s);
  worldFile = NULL;

  unless (isAligned (s->sysvals.pageSize, CARD_SIZE))
    die ("Page size must be a multiple of card size.");
  processAtMLton (s, 0, s->atMLtonsLength, s->atMLtons, &worldFile);
  res = processAtMLton (s, 1, argc, argv, &worldFile);
  if (s->controls.fixedHeap > 0 and s->controls.maxHeap > 0)
    die ("Cannot use both fixed-heap and max-heap.");
  unless (s->controls.ratios.markCompact <= s->controls.ratios.copy
          and s->controls.ratios.copy <= s->controls.ratios.live)
    die ("Ratios must satisfy mark-compact-ratio <= copy-ratio <= live-ratio.");
  unless (s->controls.ratios.stackCurrentPermitReserved
          <= s->controls.ratios.stackCurrentMaxReserved)
    die ("Ratios must satisfy stack-current-permit-reserved <= stack-current-max-reserved.");
  /* We align s->sysvals.ram by s->sysvals.pageSize so that we can
   * test whether or not we we are using mark-compact by comparing
   * heap size to ram size.  If we didn't round, the size might be
   * slightly off.
   */
  uintmax_t ram;
  ram = alignMax ((uintmax_t)(s->controls.ratios.ramSlop * (double)(s->sysvals.physMem)),
                  (uintmax_t)(s->sysvals.pageSize));
  ram = min (ram, alignMaxDown((uintmax_t)SIZE_MAX, (uintmax_t)(s->sysvals.pageSize)));
  s->sysvals.ram = (size_t)ram;
  if (DEBUG or DEBUG_RESIZING or s->controls.messages)
    fprintf (stderr, "[GC: Found %s bytes of RAM; using %s bytes (%.1f%% of RAM).]\n",
             uintmaxToCommaString(s->sysvals.physMem),
             uintmaxToCommaString(s->sysvals.ram),
             100.0 * ((double)ram / (double)(s->sysvals.physMem)));
  if (DEBUG_SOURCES or DEBUG_PROFILE) {
    uint32_t i;
    for (i = 0; i < s->sourceMaps.frameSourcesLength; i++) {
      uint32_t j;
      uint32_t *sourceSeq;
      fprintf (stderr, "%"PRIu32"\n", i);
      sourceSeq = s->sourceMaps.sourceSeqs[s->sourceMaps.frameSources[i]];
      for (j = 1; j <= sourceSeq[0]; j++)
        fprintf (stderr, "\t%s\n",
                 s->sourceMaps.sourceNames[
                 s->sourceMaps.sources[sourceSeq[j]].sourceNameIndex
                 ]);
    }
  }
  /* Initialize profiling.  This must occur after processing
   * command-line arguments, because those may just be doing a
   * show-sources, in which case we don't want to initialize the
   * atExit.
   */
  initProfiling (s);
  if (s->amOriginal) {
    initWorld (s);
    /* The mutator stack invariant doesn't hold,
     * because the mutator has yet to run.
     */
    assert (invariantForMutator (s, TRUE, FALSE));
  } else {
    loadWorldFromFileName (s, worldFile);
    if (s->profiling.isOn and s->profiling.stack)
      foreachStackFrame (s, enterFrameForProfiling);
    assert (invariantForMutator (s, TRUE, TRUE));
  }
  s->amInGC = FALSE;
  return res;
}
Example #21
0
int init_suite_2(void){
  heap_kb = initHeap(1000);
  heap_mb = initHeap(1000000);
  heap_lessThan_kb = initHeap(999);
  return 0;
}
Example #22
0
static void
find_closest_pairs(double *place, int n, int num_pairs,
		   PairStack * pairs_stack)
{
    /* Fill the stack 'pairs_stack' with 'num_pairs' closest pairs int the 1-D layout 'place' */
    int i;
    PairHeap heap;
    int *left = N_GNEW(n, int);
    int *right = N_GNEW(n, int);
    Pair pair = { 0, 0 }, new_pair;

    /* Order the nodes according to their place */
    int *ordering = N_GNEW(n, int);
    int *inv_ordering = N_GNEW(n, int);

    for (i = 0; i < n; i++) {
	ordering[i] = i;
    }
    quicksort_place(place, ordering, 0, n - 1);
    for (i = 0; i < n; i++) {
	inv_ordering[ordering[i]] = i;
    }

    /* Intialize heap with all consecutive pairs */
    initHeap(&heap, place, ordering, n);

    /* store the leftmost and rightmost neighbors of each node that were entered into heap */
    for (i = 1; i < n; i++) {
	left[ordering[i]] = ordering[i - 1];
    }
    for (i = 0; i < n - 1; i++) {
	right[ordering[i]] = ordering[i + 1];
    }

    /* extract the 'num_pairs' closest pairs */
    for (i = 0; i < num_pairs; i++) {
	int left_index;
	int right_index;
	int neighbor;

	if (!extractMax(&heap, &pair)) {
	    break;		/* not enough pairs */
	}
	push(pairs_stack, pair);
	/* insert to heap "descendant" pairs */
	left_index = inv_ordering[pair.left];
	right_index = inv_ordering[pair.right];
	if (left_index > 0) {
	    neighbor = ordering[left_index - 1];
	    if (inv_ordering[right[neighbor]] < right_index) {
		/* we have a new pair */
		new_pair.left = neighbor;
		new_pair.right = pair.right;
		new_pair.dist = place[pair.right] - place[neighbor];
		insert(&heap, new_pair);
		right[neighbor] = pair.right;
		left[pair.right] = neighbor;
	    }
	}
	if (right_index < n - 1) {
	    neighbor = ordering[right_index + 1];
	    if (inv_ordering[left[neighbor]] > left_index) {
		/* we have a new pair */
		new_pair.left = pair.left;
		new_pair.right = neighbor;
		new_pair.dist = place[neighbor] - place[pair.left];
		insert(&heap, new_pair);
		left[neighbor] = pair.left;
		right[pair.left] = neighbor;
	    }
	}
    }
    free(left);
    free(right);
    free(ordering);
    free(inv_ordering);
    freeHeap(&heap);
}
Example #23
0
void mmInit(void) {
	mmInitPaging();
	mmInitVirtPaging();
	initHeap();
}