Ejemplo n.º 1
0
static void
maybe_free_functor_tables(void)
{
  FunctorTable t = functorDefTable;
  while ( t )
  { FunctorTable t2 = t->prev;
    if ( t2 && !pl_functor_table_in_use(t2) )
    { t->prev = t2->prev;
      freeHeap(t2->table, t2->buckets * sizeof(FunctorDef));
      freeHeap(t2, sizeof(functor_table));
    }
    t = t->prev;
  }
}
Ejemplo n.º 2
0
void
destroyHTable(Table ht)
{
#ifdef O_PLMT
    if ( ht->mutex )
    {   simpleMutexDelete(ht->mutex);
        freeHeap(ht->mutex, sizeof(*ht->mutex));
        ht->mutex = NULL;
    }
#endif

    clearHTable(ht);
    freeHeap(ht->entries, ht->buckets * sizeof(Symbol));
    freeHeap(ht, sizeof(struct table));
}
Ejemplo n.º 3
0
static void
freeCodes(Code codes)
{ size_t size = (size_t)codes[-1];

  if ( size > 0 )		/* 0: built-in, see initSupervisors() */
    freeHeap(&codes[-1], (size+1)*sizeof(code));
}
Ejemplo n.º 4
0
void
clearHTable(Table ht)
{   int n;
    TableEnum e;

    LOCK_TABLE(ht);
    for( e=ht->enumerators; e; e = e->next )
    {   e->current = NULL;
        e->key     = ht->buckets;
    }

    for(n=0; n < ht->buckets; n++)
    {   Symbol s, q;

        for(s = ht->entries[n]; s; s = q)
        {   q = s->next;

            if ( ht->free_symbol )
                (*ht->free_symbol)(s);

            freeHeap(s, sizeof(struct symbol));
        }

        ht->entries[n] = NULL;
    }

    ht->size = 0;
    UNLOCK_TABLE(ht);
}
Ejemplo n.º 5
0
void
deleteSymbolHTable(Table ht, Symbol s)
{   int v;
    Symbol *h;
    TableEnum e;

    LOCK_TABLE(ht);
    v = (int)pointerHashValue(s->name, ht->buckets);
    h = &ht->entries[v];

    for( e=ht->enumerators; e; e = e->next )
    {   if ( e->current == s )
            rawAdvanceTableEnum(e);
    }

    for( ; *h; h = &(*h)->next )
    {   if ( *h == s )
        {   *h = (*h)->next;

            s->next = NULL;				/* force crash */
            s->name = NULL;
            s->value = NULL;
            freeHeap(s, sizeof(struct symbol));
            ht->size--;

            break;
        }
    }

    UNLOCK_TABLE(ht);
}
Ejemplo n.º 6
0
Archivo: pl-op.c Proyecto: apoc/swipl
static void
freeOperatorSymbol(Symbol s)
{ operator *op = s->value;

  PL_unregister_atom((atom_t) s->name);
  freeHeap(op, sizeof(*op));
}
Ejemplo n.º 7
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;
}
Ejemplo n.º 8
0
void
remove_string(char *s)
{ if ( s )
  { GET_LD
    freeHeap(s, strlen(s)+1);
  }
}
Ejemplo n.º 9
0
static void
unallocSourceFile(SourceFile sf)
{ freeList(&sf->procedures);
  freeList(&sf->modules);
  if ( sf->mutex )
    freeSimpleMutex(sf->mutex);
  freeHeap(sf, sizeof(*sf));
}
Ejemplo n.º 10
0
void
cleanupFunctors(void)
{ FunctorTable table = functorDefTable;

  if ( table )
  { int i;
    int builtin_count      = sizeof(functors)/sizeof(builtin_functor) - 1;
    FunctorDef builtin     = GD->functors.array.blocks[0][1];
    FunctorDef builtin_end = builtin+builtin_count;
    FunctorDef *fp0;

    freeHeap(builtin, builtin_count * sizeof(struct functorDef));

    for(i=0; (fp0=GD->functors.array.blocks[i]); i++)
    { size_t bs = (size_t)1<<i;
      size_t upto = (size_t)2<<i;
      FunctorDef *fp, *ep;

      fp0 += bs;
      fp = fp0;
      ep=fp+bs;
      if ( upto > GD->functors.highest )
	ep -= upto-GD->functors.highest;

      for(; fp<ep; fp++)
      { FunctorDef f = *fp;

	if ( !(f>=builtin && f<=builtin_end) )
	  freeHeap(f, sizeof(*f));
      }

      GD->functors.array.blocks[i] = NULL;
      PL_free(fp0);
    }

    while ( table )
    { FunctorTable prev = table->prev;
      freeHeap(table->table, table->buckets * sizeof(FunctorDef));
      freeHeap(table, sizeof(functor_table));
      table = prev;
    }
    table = NULL;
  }
}
Ejemplo n.º 11
0
void
remove_string(char *s)
{ if ( s )
  { GET_LD
    assert(s[-1] == CHAR_INUSE);

    s[-1] = CHAR_FREED;
    freeHeap(s-1, strlen(s)+2);
  }
}
Ejemplo n.º 12
0
void heapSort(int keys[], int numKeys){
    if(numKeys == 0) return;
    heapHndl H = newHeap(numKeys);
    for(int i = 0; i < numKeys; i++) insert(H, keys[i]);
    for(int i = numKeys-1; i > -1; i--){
        keys[i] = maxValue(H);
        deleteMax(H);
    }
    freeHeap(&H);
}
Ejemplo n.º 13
0
void
freeSupervisor(Definition def, Code codes, int do_linger)
{ size_t size = (size_t)codes[-1];

  if ( size > 0 )		/* 0: built-in, see initSupervisors() */
  { if ( do_linger )
      linger(&def->lingering, free_codes_ptr, codes);
    else
      freeHeap(&codes[-1], (size+1)*sizeof(code));
  }
}
Ejemplo n.º 14
0
static void
unallocSourceFile(SourceFile sf)
{ if ( sf->magic == SF_MAGIC_DESTROYING )
  { sf->magic = 0;
    freeList(&sf->procedures);
    freeList(&sf->modules);
#ifdef O_PLMT
    if ( sf->mutex )
      freeSimpleMutex(sf->mutex);
#endif
    freeHeap(sf, sizeof(*sf));
  }
}
Ejemplo n.º 15
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;
}
Ejemplo n.º 16
0
static void
freeList(ListCell *lp)
{ ListCell c;

  if ( (c=*lp) )
  { ListCell n;

    *lp = NULL;
    for( ; c; c=n )
    { n = c->next;

      freeHeap(c, sizeof(*c));
    }
  }
}
Ejemplo n.º 17
0
static void
cleanupOptListP(opt_list **listp)
{ opt_list *l, *n;

  if ( (l=*listp) )
  { *listp = NULL;

    for(; l; l=n)
    { n = l->next;

      remove_string(l->opt_val);
      freeHeap(l, sizeof(*l));
    }
  }
}
Ejemplo n.º 18
0
void
freeCodesDefinition(Definition def)
{ Code codes;

  if ( (codes=def->codes) != SUPERVISOR(virgin) )
  { if ( (codes = def->codes) )
    { size_t size = (size_t)codes[-1];

      def->codes = SUPERVISOR(virgin);
      if ( size > 0 )		/* 0: built-in, see initSupervisors() */
      { GET_LD
	freeHeap(&codes[-1], (size+1)*sizeof(code));
      }
    } else
      def->codes = SUPERVISOR(virgin);
  }
}
Ejemplo n.º 19
0
// Returns residue based on Karmarkar-Karp algorithm for array nums of length n
uint64_t kk(uint64_t* nums, int n) {
    // Initialize heap
    heap* h = createHeap(n);
    for (int i = 0; i < n; i++) {
        insert(h, nums[i]);
    }

    // Run algorithm
    while (getSize(h) > 1) {
        insert(h, pop(h) - pop(h));
    }

    // Return final element
    uint64_t residue = pop(h);
    freeHeap(h);
    return residue;
}
Ejemplo n.º 20
0
// -------------------------------------------------------------------------
int main (int argc, const char * argv[]) 
{
  int* key;
  char command;
  bool quit=false;
  printf( "Welcome to heap test program\n" );
  Heap h = newHeap( comp );
  do {
    printf( "Command: ('h' for help): " );
    scanf( " %c", &command );
    switch( toupper(command) ) {
    case 'H':			/* help */
      printf( "Commands:\n"
	      "  i num - insert number into heap\n"
	      "  d     - delete minimum element from heap\n"
	      "  p     - print heap\n"
	      "  q     - quit\n" );
      break;
    case 'I':			/* insert */
      key = safe_malloc( sizeof *key );
      scanf( "%d", key );
      insertHeap( h, key );
      break;
    case 'D':			/* delete_min */
      if (isEmptyHeap( h )) {
	printf( "Heap is empty\n" );
      }
      else {
        key = deleteMinHeap( h );
        printf( "%d\n", *key );
        free( key );
      }
      break; 
    case 'P':			/* print */
      mapHeap( print_element, h, NULL );
      printf( "\n" );
      break;
    case 'Q':
      quit=true;
    }
  } while( !quit );
  
  freeHeap( h );
  printf( "Goodbye!\n" );
}
Ejemplo n.º 21
0
static int
delModuleSourceFile(SourceFile sf, Module m)
{ ListCell *cp, c;
  int rc = FALSE;

  LOCKSRCFILE(sf);
  for(cp=&sf->modules; (c=*cp); cp=&c->next)
  { if ( c->value == m )
    { *cp = c->next;
      freeHeap(c, sizeof(*c));

      rc = TRUE;
      break;
    }
  }
  UNLOCKSRCFILE(sf);

  return rc;
}
Ejemplo n.º 22
0
static void					/* requires LOCKSRCFILE(sf) */
delAllModulesSourceFile__unlocked(SourceFile sf)
{ ListCell c = sf->modules, n;

  sf->modules = NULL;

  for(; c; c = n)
  { Module m = c->value;

    n = c->next;
    if ( m->file == sf )
    { PL_LOCK(L_MODULE);
      m->file = NULL;
      m->line_no = 0;
      clearHTable(m->public);
      PL_UNLOCK(L_MODULE);
    }

    freeHeap(c, sizeof(*c));
  }
Ejemplo n.º 23
0
void
freeTableEnum(TableEnum e)
{   TableEnum *ep;
    Table ht;

    if ( !e )
        return;

    ht = e->table;
    LOCK_TABLE(ht);
    for( ep=&ht->enumerators; *ep ; ep = &(*ep)->next )
    {   if ( *ep == e )
        {   *ep = (*ep)->next;

            freeHeap(e, sizeof(*e));
            break;
        }
    }
    UNLOCK_TABLE(ht);
}
Ejemplo n.º 24
0
int main() {
	int i;
	srand(time(NULL));
	Heap * h = createHeap(100);
	for (i = 0; i < 100; ++i) {
		if (i > 20) {
			heapAdd(h, createHeapNode(FLT_MAX, i));
			continue;
		}
		heapAdd(h, createHeapNode(rand() % 100, i));
	}

	displayHeap(h);
	for (i = 0; i < 10; ++i) {
		HeapNode *tmp = heapExtractHead(h);

		fprintf(stdout, "\nAncien noeud : ");
		displayHeapNode(tmp);
		fprintf(stdout, "\n");
		tmp->c = rand() * i % 100 + 100;
		fprintf(stdout, "Nouveau noeud : ");
		displayHeapNode(tmp);

		heapAdd(h, tmp);

		displayHeap(h);
	}

	HeapNode * tmp = heapExtract(h, 2);
	tmp->c = rand() % 100;

	heapAdd(h, tmp);

	displayHeap(h);

	freeHeap(h);

	return 0;
}
Ejemplo n.º 25
0
static void
rehashFunctors(void)
{ FunctorDef *oldtab = functorDefTable;
  int oldbucks       = functor_buckets;
  size_t index;
  int i, last = FALSE;

  functor_buckets *= 2;
  allocFunctorTable();

  DEBUG(MSG_HASH_STAT,
	Sdprintf("Rehashing functor-table to %d entries\n", functor_buckets));

  for(index=1, i=0; !last; i++)
  { size_t upto = (size_t)2<<i;
    FunctorDef *b = GD->functors.array.blocks[i];

    if ( upto >= GD->functors.highest )
    { upto = GD->functors.highest;
      last = TRUE;
    }

    for(; index<upto; index++)
    { FunctorDef f = b[index];

      if ( f )
      { size_t v = pointerHashValue(f->name, functor_buckets);

	f->next = functorDefTable[v];
	functorDefTable[v] = f;
      }
    }
  }

  freeHeap(oldtab, oldbucks * sizeof(FunctorDef));
}
Ejemplo n.º 26
0
void printTrend(BiTree *tree){
	int i;
	BiTreeNode *currentTreeNode = tree->root;
	TreeStack *treeStack = makeStack();
	TreeHeap *treeHeap = makeHeap(tree->size + 1);
	push(treeStack, currentTreeNode);
	while(isStackEmpty(treeStack) != 0){
		currentTreeNode = pop(treeStack);
		setHeapElement(treeHeap, currentTreeNode);
		if(currentTreeNode->right != NULL)
			push(treeStack, currentTreeNode->right);
		if(currentTreeNode->left != NULL)
			push(treeStack, currentTreeNode->left);
	}
	makeMaxHeapify(treeHeap);
	heapSort(treeHeap);
	fprintf(stdout, "Trending Up:\n");
	for(i = treeHeap->size - 1; i >= treeHeap->size - 5; i--)
		fprintf(stdout, "%s (%+d)\n", getTreeNodeWord(treeHeap->array[i]), getTreeNodeResult(treeHeap->array[i]));
	fprintf(stdout, "Trending Down:\n");
	for(i = 1; i < 6; i++)
		fprintf(stdout, "%s (%+d)\n", getTreeNodeWord(treeHeap->array[i]), getTreeNodeResult(treeHeap->array[i]));
	freeHeap(treeHeap);
}
Ejemplo n.º 27
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;
}
Ejemplo n.º 28
0
static Symbol
rehashHTable(Table ht, Symbol map)
{   Symbol *newentries, *oldentries;
    int     newbuckets, oldbuckets;
    int     i;
    int     safe_copy = (ht->mutex != NULL);

    newbuckets = ht->buckets*2;
    newentries = allocHTableEntries(newbuckets);

    DEBUG(MSG_HASH_STAT,
          Sdprintf("Rehashing table %p to %d entries\n", ht, ht->buckets));

    for(i=0; i<ht->buckets; i++)
    {   Symbol s, n;

        if ( safe_copy )
        {   for(s=ht->entries[i]; s; s = n)
            {   int v = (int)pointerHashValue(s->name, newbuckets);
                Symbol s2 = allocHeapOrHalt(sizeof(*s2));

                n = s->next;
                if ( s == map )
                    map = s2;
                *s2 = *s;
                s2->next = newentries[v];
                newentries[v] = s2;
            }
        } else
        {   for(s=ht->entries[i]; s; s = n)
            {   int v = (int)pointerHashValue(s->name, newbuckets);

                n = s->next;
                s->next = newentries[v];
                newentries[v] = s;
            }
        }
    }

    oldentries  = ht->entries;
    oldbuckets  = ht->buckets;
    ht->entries = newentries;
    ht->buckets = newbuckets;

    if ( safe_copy )
    {   /* Here we should be waiting until */
        /* active lookup are finished */
        for(i=0; i<oldbuckets; i++)
        {   Symbol s, n;

            for(s=oldentries[i]; s; s = n)
            {   n = s->next;

                s->next = NULL;			/* that causes old readers to stop */
                freeHeap(s, sizeof(*s));
            }
        }
    }

    freeHeap(oldentries, oldbuckets * sizeof(Symbol));
    DEBUG(CHK_SECURE, checkHTable(ht));

    return map;
}
Ejemplo n.º 29
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);
}
arbre* computeBIPtree(call_t *c, graphe* g, listeNodes* askedToRedirect, listeNodes* needsToBeCovered, int debug)
{
	struct nodedata *nodedata = get_node_private_data(c);
	arbre* bipTree = 0;
	int i, minNode, devientEmetteur, numMinNode, numVoisin;
	double coutIncremental;
	double* cle = malloc(g->nbSommets*sizeof(double));
	double* poids = malloc(g->nbSommets*sizeof(double));
	int* pere = malloc(g->nbSommets*sizeof(int));
	Heap* F = allocHeap(g->nbSommets, cle); // tas gardant les couts des noeuds pas encore dans l'arbre
	voisin *trans;
	
	if(debug)
		printf("Fixation des valeurs initiales...\n");
	for(i = 0 ; i < g->nbSommets ; i++)
	{
		cle[i] = DBL_MAX;
		poids[i] = 0;
		pere[i] = -1;
		h_insertNode(F, i);
	}
	h_changeLabel(F, g->s.num, 0);
	if(askedToRedirect == 0 || needsToBeCovered == 0)
	{
		poids[g->s.num] = getEdgeCost(g, c->node, getNearestNeighbour(c, g));
	}
	else
	{
		if(debug)
			printf("Fixation des valeurs de range deduites du paquet...\n");
		listeNodes *tmp = askedToRedirect, *tmp2 = needsToBeCovered;
		while(tmp != 0)
		{
			if(getEdgeCost(g, tmp->values.node, tmp2->values.node) != DBL_MAX)
			{
                                //printf("poids[%d] = %.1lf\n", tmp->values.node, getEdgeCost(g, tmp->values.node, tmp2->values.node));
				poids[getNumFromLabel(g,tmp->values.node)] = getEdgeCost(g, tmp->values.node, tmp2->values.node);
			}
			tmp = tmp->suiv;
			tmp2 = tmp2->suiv;
		}
	}
	if(debug)
		printf("Debut de l'algorithme...\n");
	while(!h_isEmpty(F))
	{
		if(debug)
			printf("Recuperation du min du tas...\n");
		numMinNode = h_remNode(F);
		minNode = getLabelFromNum(g,numMinNode);
		if(debug)
		{
			printf("minNode label : %d\n", minNode);
			printf("\tnum : %d\n", numMinNode);
			printf("Ajout du noeud dans l'arbre...\n");
		}
		if(pere[numMinNode] == -1)
		{
			arbre_add_pere(&(bipTree), minNode);
		}
		else
		{
			arbre_add_fils(bipTree, pere[numMinNode], minNode);
			int numPere = getNumFromLabel(g, pere[numMinNode]);
			if(poids[numPere] < getEdgeCost(g, pere[numMinNode], minNode))
			{
				if(debug)
					printf("\tChangement du poids de %d\n", pere[numMinNode]);
				poids[numPere] = getEdgeCost(g,pere[numMinNode], minNode);
			}
		}
		// pour chacun des noeuds pas dans l'arbre ie : dans le tas
		for(i = 0 ; i < g->nbSommets ; i++)
		{
			if(h_contains(F, i))
				h_changeLabel(F, i, DBL_MAX);
		}
		
		// pour chacun des noeuds dans l'arbre ie : pas dans le tas
		for(i = 0 ; i < g->nbSommets ; i++)
		{
			if(!h_contains(F, i))
			{
				// pour chacun des voisins dans le tas ie : pas dans l'arbre
				if(debug)
					printf("Recuperation du voisinage...\n");
				trans = getNeighboursFromLabel(g,getLabelFromNum(g,i));
				while(trans != 0)
				{
					numVoisin = getNumFromLabel(g,trans->vLabel);
					if(h_contains(F, numVoisin))
					{
						if(debug)
							printf("\tVoisin pas dans l'arbre : label : %d ; num : %d\n", trans->vLabel, numVoisin);
						coutIncremental = trans->cout - poids[i];
						if(coutIncremental < cle[numVoisin])
						{
							if(debug)
							{
								printf("\tCout a ameliorer : %.1lf < %.1lf\n", coutIncremental, cle[numVoisin]);
							}
							h_changeLabel(F, numVoisin, coutIncremental);
							if(debug)
								printf("\tpere[%d] devient %d...\n", trans->vLabel, getLabelFromNum(g,i));
							pere[numVoisin] = getLabelFromNum(g,i);
						}
					}
					trans = trans->vSuiv;
				}
			}
		}
	}
	
	
	free(poids);
	free(pere);
	free(cle);
	freeHeap(F);
	
	/*printf("Graphe de voisinage complet : \n");
	 printf("Graphe de voisinage : \n");
	 afficherGraphe(nodedata->g2hop);
	 printf("arbre de BIP de %d construit : \n", c->node);
	 arbre_affiche(bipTree);*/
	
	return bipTree;
}