Ejemplo n.º 1
0
int main(void)
{
	hashTable ht;
	InitHashTable(&ht, 100, print, equal, hashFun);
	int a1 =2;
	int a2 =4;

	InsertHashTable(ht, &a1);

	//print(SearchHashTable(ht, &a1));
	int *r =(int*)SearchHashTable(ht, &a1);
	assert( *r == 2 );

	r = SearchHashTable(ht, &a2);
	assert( r == NULL );

	InsertHashTable(ht, &a2);
	r = SearchHashTable(ht, &a2);
	assert( *r == 4);

	DestroyHashTable(&ht);
	printf("hashTable OK\n");
	
	
	return 0;
}
Ejemplo n.º 2
0
DocID_t DTRegisterDocumentName(DocTable table, char *docname) {
  // Allocate space for the docid.
  char       *doccopy;
  DocID_t   *docid = (DocID_t *) malloc(sizeof(DocID_t));
  DocID_t   res;
  HTKeyValue kv, oldkv;
  int retval;

  // Make a copy of the docname.
  doccopy = (char *) malloc(1+strlen(docname));
  if (doccopy != NULL) {
    strncpy(doccopy, docname, 1+strlen(docname));
  }
  Verify333(table != NULL);
  Verify333(doccopy != NULL);
  Verify333(docid != NULL);

  // Check to see if the document already exists; if so,
  // free up the malloc'ed space and return the existing docid

  // STEP 2.
  res = DTLookupDocumentName(table, docname);
  if (res != 0) {
    free(doccopy);
    free(docid);
    return res;
  }

  // allocate the next docID
  table->max_id += 1;
  *docid = table->max_id;

  // STEP 3.
  // Set up the key/value for the docid_to_docname mapping, and
  // do the insert.

  kv.key = (HTKey_t)*docid;
  kv.value = (HTValue_t)doccopy;
  retval = InsertHashTable(table->docid_to_docname, kv, &oldkv);
  Verify333(retval != 0);

  // STEP 4.
  // Set up the key/value for the docname_to_docid mapping, and
  // do the insert.
  kv.key = (HTKey_t)FNVHash64((unsigned char*)docname, strlen(docname));
  kv.value = (HTValue_t)docid;
  retval = InsertHashTable(table->docname_to_docid, kv, &oldkv);
  Verify333(retval != 0);


  return *docid;
}
Ejemplo n.º 3
0
void BuildLSH(LSH** lshptr, int L, int k) {
    int i,j;

    *lshptr = malloc(sizeof(LSH));
    LSH* lsh = *lshptr;
    lsh->L = L;
    lsh->k = k;
    lsh->tables = malloc(L * sizeof(hashMap));
    value value;
    for (i = 0; i < L; i++) {

        //initialize struct for each G function depending on the metric
        lsh->tables[i].GConfiguration = data.initStruct();

        //initialize hash
        InitHashTable(&(lsh->tables[i].tables), data.tableSize,
                      sizeof(value), data.print, data.distance, data.G,
                      NULL);

        //insert each value in hash table
        for(j=0; j<GetDataSize(); j++) {
            GetIthData(j,&value);

            InsertHashTable(lsh->tables[i].tables, &value,
                            lsh->tables[i].GConfiguration);
            //value = GetNextData();
        }
    }

}
Ejemplo n.º 4
0
/* Add a vertex to the vertex set */
int AddVertex(char *name, int vid)
{
  int length = strlen(name) + 1;
  if (length > MAX_STRING) length = MAX_STRING;
  vertex[vid].name = (char *)calloc(length, sizeof(char));
  strcpy(vertex[vid].name, name);
  vertex[vid].degree = 0;
  InsertHashTable(name, vid);
  return vid;
}
Ejemplo n.º 5
0
static void ResizeHashtable(HashTable ht) {
  // Resize if the load factor is > 3.
  if (ht->num_elements < 3 * ht->num_buckets)
    return;

  // This is the resize case.  Allocate a new hashtable,
  // iterate over the old hashtable, do the surgery on
  // the old hashtable record and free up the new hashtable
  // record.
  HashTable newht = AllocateHashTable(ht->num_buckets * 9);

  // Give up if out of memory.
  if (newht == NULL)
    return;

  // Loop through the old ht with an iterator,
  // inserting into the new HT.
  HTIter it = HashTableMakeIterator(ht);
  if (it == NULL) {
    // Give up if out of memory.
    FreeHashTable(newht, &HTNullFree);
    return;
  }

  while (!HTIteratorPastEnd(it)) {
    HTKeyValue item, dummy;

    Verify333(HTIteratorGet(it, &item) == 1);
    if (InsertHashTable(newht, item, &dummy) != 1) {
      // failure, free up everything, return.
      HTIteratorFree(it);
      FreeHashTable(newht, &HTNullFree);
      return;
    }
    HTIteratorNext(it);
  }

  // Worked!  Free the iterator.
  HTIteratorFree(it);

  // Sneaky: swap the structures, then free the new table,
  // and we're done.
  {
    HashTableRecord tmp;

    tmp = *ht;
    *ht = *newht;
    *newht = tmp;
    FreeHashTable(newht, &HTNullFree);
  }

  return;
}
Ejemplo n.º 6
0
static void AddToHashtable(HashTable tab, char *word, DocPositionOffset_t pos) {
  HTKey_t hashKey;
  int retval;
  HTKeyValue kv;

  // Hash the string.
  hashKey = FNVHash64((unsigned char *) word, strlen(word));

  // Have we already encountered this word within this file?
  // If so, it's already in the hashtable.
  retval = LookupHashTable(tab, hashKey, &kv);
  if (retval == 1) {
    // Yes; we just need to add a position in using AppendLinkedList().  Note
    // how we're casting the DocPositionOffset_t position
    // variable to an LLPayload_t to store
    // it in the linked list payload without needing to malloc space for it.
    // Ugly, but it works!
    WordPositions *wp = (WordPositions *) kv.value;
    retval = AppendLinkedList(wp->positions, (LLPayload_t) ((intptr_t) pos));
    Verify333(retval != 0);
  } else {
    // STEP 8.
    // No; this is the first time we've seen this word.  Allocate and prepare
    // a new WordPositions structure, and append the new position to its list
    // using a similar ugly hack as right above.
    WordPositions *wp;
    char *newstr;
    HTKeyValue oldkv;
    bool retbool;

    // Allocate space for a new WordPositions structure.
    wp = (WordPositions *)malloc(sizeof(WordPositions));
    Verify333(wp != NULL);

    // Allocate space for the word and copy the word content.
    newstr = (char *)malloc(strlen(word) + 1);  // +1 is for "\0"
    Verify333(newstr != NULL);
    snprintf(newstr, strlen(word) +1, "%s", word);
    wp->word = newstr;

    // Set linkedlist from positions and append linked list
    wp->positions = AllocateLinkedList();
    Verify333(wp->positions != NULL);
    retbool = AppendLinkedList(wp->positions, (LLPayload_t) ((intptr_t) pos));
    Verify333(retbool);

    // Set the key value pair and add it to hashtable.
    kv.key = hashKey;
    kv.value = wp;
    retval = InsertHashTable(tab, kv, &oldkv);
    Verify333(retval == 1);
  }
}
Ejemplo n.º 7
0
int PNNRange(LSH* lsh, value query, int P,value* array) {

    int i=0;
    int hashSize=0;
    hashTable neighbors;
    double* distArr=NULL;

    for (i = 0; i < lsh->L; i++) {

        //gets bucket where the value is
        List bucketList = GetListHashTable(lsh->tables[i].tables,
                                           &query, lsh->tables[i].GConfiguration);
        hashSize+=SizeList(bucketList);
    }
    InitHashTable(&neighbors,hashSize,sizeof(value),NULL,
                  data.distance,hashFunc,NULL);

    for (i = 0; i < lsh->L; i++) {


        //gets bucket where the value is
        List bucketList = GetListHashTable(lsh->tables[i].tables,
                                           &query, lsh->tables[i].GConfiguration);
        value* lValue = GetFirst(bucketList);
        //get all neighbours in range an place them in a list
        while (lValue != NULL) {
            InsertHashTable(neighbors, lValue,NULL);
            lValue = GetNext(bucketList);
        }
    }
    value** hashArr=malloc( GetHashSize(neighbors) * sizeof(value*));
    // WARNING //
    HashToArr(neighbors,(void**)hashArr);
    distArr=malloc(GetHashSize(neighbors)*sizeof(double));


    for(i=0; i<GetHashSize(neighbors); i++) {
        distArr[i]=data.distance(hashArr[i],&query);
    }

    QuickSortValue(distArr, hashArr,  GetHashSize(neighbors));

    for(i=0; (i<P && i<GetHashSize(neighbors)-1 ); i++) {
        array[i]=*hashArr[i+1];
    }
    DestroyHashTable(&neighbors);
    free(hashArr);
    free(distArr);
    return i;
}
Ejemplo n.º 8
0
/* Add a vertex to the vertex set */
int AddVertex(char *name)
{
	int length = strlen(name) + 1;
	if (length > MAX_STRING) length = MAX_STRING;
	vertex[num_vertices].name = (char *)calloc(length, sizeof(char));
	strcpy(vertex[num_vertices].name, name);
	vertex[num_vertices].sum_weight = 0;
	num_vertices++;
	if (num_vertices + 2 >= max_num_vertices)
	{
		max_num_vertices += 1000;
		vertex = (struct ClassVertex *)realloc(vertex, max_num_vertices * sizeof(struct ClassVertex));
	}
	InsertHashTable(name, num_vertices - 1);
	return num_vertices - 1;
}
Ejemplo n.º 9
0
bool readHashTable(HashTable &hT,const char *file) {
//	std::ofstream oF("sss.txt");	oF.close();

	std::ifstream iF(file);
	if (!iF) return false;
	int size;
	iF >> size;
	table_size = size;
	InitHashTable(hT);

	ElemType data; //student
	
	while (iF >> data.id) {
		iF >> data.score;
		InsertHashTable(hT, data);
	}

	return true;
}
Ejemplo n.º 10
0
void RateItemsCosine(value* lvalue, value** nn, int size, List Rresult){
	int i,j,k,pos;
	double R;
	int *x = lvalue->content;
	hashTable rated;
	int hashSize = co.users[*x].NoOfItems*size;
	int** array = malloc(co.users[*x].NoOfItems*sizeof(int*));
	Rating rating;

	InitHashTable(&rated,hashSize,sizeof(int),NULL,
			distanceCos,IntHashFuncCos,NULL);
	//InitList(Rresult,sizeof(int),NULL,distance,NULL);

	for(i=0; i<co.users[*x].NoOfItems; ++i){
		InsertHashTable(rated, &co.users[*x].myitems[i].id,NULL);
	}
	double z = 0.0;
	for ( i = 0; i < size; ++i)
	{
		//z+=abs((-data.distance(lvalue,nn[i])-1));
		double tmp = (-data.distance(lvalue,nn[i])-1);
		z+= ( tmp <0 ? -tmp : tmp);
	}
	z = 1/z;
	double Ru = 0.0;
	for (k = 0; k < co.users[*x].NoOfItems; ++k)
	{
		Ru+=co.users[*x].myitems[k].score;
	}
	Ru/=co.users[*x].NoOfItems;
	for(i=0; i<size; ++i){
		int* curr = nn[i]->content;

		for(j=0; j<co.users[*curr].NoOfItems; ++j ){
			if(SearchHashTable(rated, &co.users[*curr].myitems[j].id)!=NULL){
				continue;
			}
			InsertHashTable(rated, &co.users[*curr].myitems[j].id,NULL);
			double sum = 0.0;
			int avg = 0;
			for (k = 0; k < co.users[*curr].NoOfItems; ++k)
			{
				avg+=co.users[*curr].myitems[k].score;
			}
			avg/=co.users[*curr].NoOfItems;
			for(k=0; k<size; ++k){
				int l;
				int *index = nn[k]->content;
				// for(l=0; l<co.users[*index].NoOfItems; l++){
				// 	printf("%d ",co.users[*index].myitems[l].id );
				// }
				// printf("\n");
				
				pos=BinarySearchCosine(co.users[*index].myitems,co.users[*index].NoOfItems,co.users[*curr].myitems[j].id);
				//printf("%d %d\n", co.users[*curr].myitems[j].id,pos);
				if(pos == -1)
					continue;
				sum+= (-data.distance(lvalue,nn[k])+1)*(co.users[k].myitems[pos].score-avg);
				//printf("dist %f score %d \n", (-data.distance(lvalue,nn[k])+1),co.users[k].myitems[pos].score);
			}
			R = Ru+z*sum;
			rating.rate = R;
			rating.id = co.users[*curr].myitems[j].id;
			InsertValueList(Rresult, &rating);
			//printf("%f , %d\n",R, co.users[*curr].myitems[j].id);
		}

	}
}
Ejemplo n.º 11
0
// our main function; here, we demonstrate how to use some
// of the hash table functions
int main(int argc, char **argv) {
  ExampleValuePtr evp;
  HashTable ht;
  HTIter iter;
  HTKeyValue kv, old_kv;
  HTKey_t i;

  // allocate a hash table with 10,000 initial buckets
  ht = AllocateHashTable(10000);
  Verify333(ht != NULL);

  // insert 20,000 elements (load factor = 2.0)
  for (i = 0; i < 20000; i++) {
    evp = (ExampleValuePtr) malloc(sizeof(ExampleValue));
    Verify333(evp != NULL);
    evp->num = i;

    // make sure HT has the right # of elements in it to start
    Verify333(NumElementsInHashTable(ht) == (HWSize_t) i);

    // insert a new element
    kv.key = FNVHashInt64((HTValue_t)i);
    kv.value = (HTValue_t)evp;
    Verify333(InsertHashTable(ht, kv, &old_kv) == 1);

    // make sure hash table has right # of elements post-insert
    Verify333(NumElementsInHashTable(ht) == (HWSize_t) (i+1));
  }

  // look up a few values
  Verify333(LookupHashTable(ht, FNVHashInt64((HTValue_t)100), &kv) == 1);
  Verify333(kv.key == FNVHashInt64((HTValue_t)100));
  Verify333(((ExampleValuePtr) kv.value)->num == 100);

  Verify333(LookupHashTable(ht, FNVHashInt64((HTValue_t)18583), &kv) == 1);
  Verify333(kv.key == FNVHashInt64((HTValue_t)18583));
  Verify333(((ExampleValuePtr) kv.value)->num == 18583);

  // make sure non-existent value cannot be found
  Verify333(LookupHashTable(ht, FNVHashInt64((HTValue_t)20000), &kv) == 0);

  // delete a value
  Verify333(RemoveFromHashTable(ht, FNVHashInt64((HTValue_t)100), &kv) == 1);
  Verify333(kv.key == FNVHashInt64((HTValue_t)100));
  Verify333(((ExampleValuePtr) kv.value)->num == 100);
  ExampleValueFree(kv.value);   // since we malloc'ed it, we must free it

  // make sure it's deleted
  Verify333(LookupHashTable(ht, FNVHashInt64((HTValue_t)100), &kv) == 0);
  Verify333(NumElementsInHashTable(ht) == (HWSize_t) 19999);

  // loop through using an iterator
  i = 0;
  iter = HashTableMakeIterator(ht);
  Verify333(iter != NULL);

  while (HTIteratorPastEnd(iter) == 0) {
    Verify333(HTIteratorGet(iter, &kv) == 1);
    Verify333(kv.key != FNVHashInt64((HTValue_t)100));   // we deleted it

    // advance the iterator
    HTIteratorNext(iter);
    i++;
  }
  Verify333(i == 19999);

  // free the iterator
  HTIteratorFree(iter);

  // free the hash table
  FreeHashTable(ht, &ExampleValueFree);
  return 0;
}