Esempio n. 1
0
int main() {

	struct test *dummy;
	size_t size = 13;
	HASHTABLE init = init_hash(dummy, size, (void *)casting);


	strcpy(point_one.name, "entry\0");
	strcpy(point_sec.name, "hello\0");
	strcpy(point_thi.name, "12345\0");

	point_one.x = 5;
	point_one.y = 20;
	
	point_sec.x = 17;
	point_sec.y = 30;

	point_thi.x = 11;
	point_thi.y = 2350;

	insertHash(init, point_one.name, &point_one);				
	insertHash(init, point_sec.name, &point_sec);				
	insertHash(init, point_thi.name, &point_thi);				

	dummy = getHash(init, point_sec.name);
	printf("Output Name: %s, x: %d, y: %d\n", dummy->name, dummy->x, dummy->y);


	return 1;
}
Esempio n. 2
0
/*	================== buildHead =================
 This function creates the header structure that
 contains pointers to the tree and the hash table.
 It also calls other functions to read in the data
 file.
 Pre		pHeader - pointer to HEAD structure
 fileInput - name of the file
 Post		both the tree and the hash table are
 created.
 Return	pointer to create HEAD structure
 */
HEAD* buildHead (HEAD* pHeader, char* fileInput)
{
	//	Local Declarations
	DATA* newAirport;
    FILE* fpIn;
    
	//	Statements
    fpIn = fopen(fileInput, "r");
    if (!fpIn) {
        printf("Error opening input file\n");
        exit(101);
    }
    
    if ((pHeader = (HEAD*) malloc(sizeof(HEAD))))
    {
        pHeader->pHash = buildHash(2 * countLines(fileInput));
        pHeader->pTree = BST_Create(compareCode);
    }
    else{
        printf("Memory allocation error\n");
        exit(100);
    }
    
    while (getData(pHeader->pTree, fpIn, &newAirport)) {
        BST_Insert(pHeader->pTree, newAirport);
        insertHash(pHeader->pHash, newAirport);
    }
    
    return pHeader;
}	// buildHead
Esempio n. 3
0
/*	================== addAirport =================
 This function adds another element of data into
 both the tree and hash table, through the user's
 input from keyboard.
 Pre		pHeader - pointer to HEAD structure
 Post
 Return	true if success
 false if fails
 */
bool addAirport (HEAD* pHeader)
{
	//	Local Declarations
    bool result = false;
    DATA tempAirport;
    DATA* newAirport = NULL;
    char tempCode [28];
    char tempName [128];
    int i;
    
	
	printf ("Enter airport code: ");
	scanf (" %s", tempCode);
    
    if (strlen(tempCode) != 3) {
        printf("Your airport code has to have 3 characters\n");
        return result;
    }
	
    for (i = 0; i<strlen(tempCode); i++) {
        tempCode[i] = toupper(tempCode[i]);
    }
    
    strcpy(tempAirport.arpCode, tempCode);
    newAirport = findHash(pHeader->pHash, &tempAirport);
    if (newAirport == NULL)
    {
        if (!(newAirport = (DATA*) malloc(sizeof(DATA)))) {
            printf("Error allocating new airport\n");
            exit(100);
        }
        strcpy(newAirport->arpCode, tempCode);
        printf("Enter airport city: ");
        scanf(" %[^\n]", tempName);
        newAirport->city = (char*) calloc(strlen(tempName) + 1, sizeof(char));
        strcpy(newAirport->city, tempName);
        
        printf("Enter airport latitude: ");
        while(!(scanf("%f", &newAirport->latitude)))
        {
            printf("Invalid input, please try entering the latitude again: ");
            while(getchar() != '\n');
        }
        printf("Enter airport longitude: ");
        while(!(scanf("%f", &newAirport->longitude)))
        {
            printf("Invalid input, please try entering the longitude again: ");
            while(getchar() != '\n');
        }
        
        insertHash(pHeader->pHash, newAirport);
        BST_Insert(pHeader->pTree, newAirport);
        result = true;
    }
    else{
        printf("This airport already exists\n");
        processScreen(newAirport);
    }
    return result;
}	// addAirport
Esempio n. 4
0
/** Reinitialize hash list. @internal */
void KZoneAllocator::initHash()
{
    if (d->hashList) {
        for (unsigned int i = 0; i < d->hashSize; i++) {
            delete d->hashList[i];
        }
        delete [] d->hashList;
        d->hashList = 0;
    }
    d->hashSize = 1;
    while (d->hashSize < d->num_blocks) {
        d->hashSize <<= 1;
    }
    if (d->hashSize < 1024) {
        d->hashSize = 1024;
    }
    if (d->hashSize > 64 * 1024) {
        d->hashSize = 64 * 1024;
    }
    d->hashList = new QList<MemBlock *> *[d->hashSize];
    memset(d->hashList, 0, sizeof(QList<MemBlock *> *) * d->hashSize);
    d->hashDirty = false;
    for (MemBlock *b = d->currentBlock; b; b = b->older) {
        insertHash(b);
    }
}
Esempio n. 5
0
void searchName (HEAD* head)
{
	HASH* hashTable = head->pHash;
	int found = 0;
    int i;
	int key;
	LIST_NODE* tempNode = NULL;
    LIST_NODE* tempPre = NULL;
	CRICKET* player = NULL;
	char* searchVal;
	char searchValTemp[30];

    printf("     Enter a name to search: ");
    gets(searchValTemp);

	searchVal = makeString(searchValTemp);
	searchVal = makeToupper(searchVal);

	key = convertToHash(searchVal);

    tempNode = hashTable[key].list;

	while (tempNode != NULL && !found)
    {
	    if (strcmp(searchVal, ((CRICKET*)(tempNode->dataPtr))->name)==0)
        {
			player = tempNode->dataPtr;
            found = 1;
			playerStats(player);
			disconnectNode(tempNode, tempPre, hashTable, key);
        }
        if (!found)
        {
			tempPre = tempNode;
            tempNode = tempNode->next;
        }

    }
    if (!found)
        printf("     Player not found\n");
	else
	{
		insertHash(player, hashTable, key);
		free(tempNode);
		hashTable[key].count--;
	}

	free(searchVal);
    return;
}
Esempio n. 6
0
/** Add a new memory block to the pool of blocks,
    and reorganize the hash lists if needed.
    @param b block to add
    @internal
*/
void KZoneAllocator::addBlock(MemBlock *b)
{
  b->newer = 0;
  b->older = currentBlock;
  if (currentBlock)
    b->older->newer = b;
  currentBlock = b;
  num_blocks++;
  /* If we either have no hashList at all, or since it's last construction
     there are now many more blocks we reconstruct the list.  But don't
     make it larger than a certain maximum.  */
  if (hashList && ((num_blocks / 4) > hashSize && hashSize < 64*1024))
    hashDirty = true;
  /* Only insert this block into the hashlists, if we aren't going to
     reconstruct them anyway.  */
  if (hashList && !hashDirty)
    insertHash (b);
}
Esempio n. 7
0
/** Reinitialize hash list. @internal */
void KZoneAllocator::initHash()
{
  if (hashList) {
    for (unsigned int i = 0; i < hashSize; i++)
      delete hashList[i];
    delete [] hashList;
    hashList = 0;
  }
  hashSize = 1;
  while (hashSize < num_blocks)
    hashSize <<= 1;
  if (hashSize < 1024)
    hashSize = 1024;
  if (hashSize > 64*1024)
    hashSize = 64*1024;
  hashList = new QValueList<MemBlock *> *[hashSize];
  memset (hashList, 0, sizeof(QValueList<MemBlock*> *) * hashSize);
  hashDirty = false;
  for (MemBlock *b = currentBlock; b; b = b->older)
    insertHash(b);
}
Esempio n. 8
0
/**
 * Loads dictionary into memory.  Returns true if successful else false.
 */
bool load(const char* dictionary)
{
    // open the dictionary file
    FILE* dict = fopen(dictionary, "r");
    
    //check to make sure the dictionary file opened
    if (dict != NULL)
        return false;
        
    //create a hashTable of words
    HashTable ht[HASHTABLE_SIZE];
    
    //read in the words one at a time
    int word[LENGTH];
    do
    {
        for (int i = 0; i < LENGTH; i++)
        {
            word[i] = fgetc(dict);
            
            //check if the eol marker was reached
            if (word[i] == '\n')
                break;
        }
    
        //calculate the hash value for the word
        int hash = getHash(word, HASHTABLE_SIZE);
        
        insertHash(ht, word, hash);
        
        
    }while (feof(dict) != 0);
    
    
    //close the dictionary file
    fclose(dict);
    return false;
}
Esempio n. 9
0
int main()
{
	int Msize,n,i=0,ctrl,flag=0;
	hash hashTable;
	scanf("%d %d",&Msize,&n);
	while(!isPrime(Msize))	//如果不是素数
		Msize++;
	hashTable.table=(int*)malloc(Msize*sizeof(int));
	memset(hashTable.table,0,Msize*sizeof(int));
	hashTable.Msize=Msize;
	for(i=0;i<n;i++){
		ctrl=insertHash(&hashTable);
		if(!flag)
			flag=1;
		else
			printf(" ");
		if(ctrl!=-1)
			printf("%d",ctrl);
		else
			printf("-");
	}
	return 0;
}
Esempio n. 10
0
void BufRead(int blkno, void* pData)
{
	Buf* pBuf;

	pBuf = BufFind(blkno);
	if( pBuf != NULL )
	{
		removeLru(blkno);
		insertLru(pBuf);
		copyBlock((char*)pBuf->pMem, (char*)pData);
		return;
	}

	pBuf = popFree();
	pBuf->blkno = blkno;
	//pBuf->pMem = (void*)malloc(BLOCK_SIZE);
	DevReadBlock(blkno, (char*)pBuf->pMem);
	insertHash(pBuf);
	insertClean(pBuf);
	removeLru(blkno);
	insertLru(pBuf);

	copyBlock((char*)pBuf->pMem, (char*)pData);
}
Esempio n. 11
0
int main(void) {

    printf("\n");
    printf("TESTING HASHTABLE ADT\n");
    printf("\n");

    /* createHash testing */
    hashTable * newTable;
    newTable = createHash(10);
    printf("\t---CREATEHASH\n");
    printf("Input to createHash: 10\n");
    printf("Return from createHash: %p\n", newTable);
    printf("The element of the hashtable representing table size: %d\n", newTable->hashSize);
    printf("\n");

    /* phoneHashFunction testing */
    printf("\t---PHONEHASHFUNCTION\n");
    printf("Input: integer array containing {9, 0, 5, 4, 1, 6, 6, 4, 7, 0},\n");
    printf("       %p (the pointer value for the table we just created)\n", newTable);
    int testNum[10] = {9, 0, 5, 4, 1, 6, 6, 4, 7, 0};
    printf("Output: %d\n", phoneHashFunction(testNum, newTable));
    printf("Expecting zero if the hash table size is 10 and the last digit in the number is 0");
    printf("\n");

    /* insertHash testing */
    printf("\t---INSERTHASH\n");
    char * name = "John Smith\0";
    printf("Input: %p (the pointer value for the table we just created),\n", newTable);
    printf("       integer array containting the same numbers inputed for phone hash Function,\n");
    printf("       %s (a string representing the name we wish to add)\n", name);
    insertHash(newTable, testNum, name);
    printf("Expected to be in the first index of the table and in the first node of the separate chain\n");
    printf("Printing that location: Name: \"%s\", Number: \"", ((person*)newTable->listHead[0]->data)->name);
    int x;
    for (x = 0; x < 10; ++x)
        printf("%d", ((person*)newTable->listHead[0]->data)->phoneNum[x]);
    printf("\"\n");
                                            //Testing anotuher name
    printf("-\n");
    printf("- Adding another name corresponding to the same index -\n");
    printf("-\n");
    char * name2 = "Jane Doe\0";
    testNum[0] = 3;
    printf("Input: %p (the pointer value for the table we just created),\n", newTable);
    printf("       integer array corresponding with the same number with a changed first digit,\n");
    printf("       %s (a string representing the name submitted\n", name2);
    insertHash(newTable, testNum, name2);
    printf("Expected to be in the first index of the table and in the first node of the separate chain since we added it to the front\n");
    printf("Printing that location: Name: \"%s\", Number: \"", ((person*)newTable->listHead[0]->data)->name);
    for (x = 0; x < 10; ++x)
        printf("%d", ((person*)newTable->listHead[0]->data)->phoneNum[x]);
    printf("\"\n");
    printf("Printing the second node: Name: \"%s\", Number: \"", ((person*)newTable->listHead[0]->next->data)->name);
    for (x = 0; x < 10; ++x)
        printf("%d", ((person*)newTable->listHead[0]->next->data)->phoneNum[x]);
    printf("\"\n");
    printf("-\n");
    printf("- Adding another name corresponding to a different index\n");
    printf("-\n");
    char * name3 = "Jake Hurrell\0";
    testNum[9] = 1;
    printf("Input: %p (the pointer value for the table we just created),\n", newTable);
    printf("       integer array corresponding with the same number as Jane Doe with a changed last digit,\n");
    printf("       %s (a string representing the name submitted\n", name2);
    insertHash(newTable, testNum, name3);
    printf("Expected to be in the SECOND index of the table and in the first node of the separate chain.\n");
    printf("Printing that location: Name: \"%s\", Number: \"", ((person*)newTable->listHead[1]->data)->name);
    for (x = 0; x < 10; ++x)
        printf("%d", ((person*)newTable->listHead[1]->data)->phoneNum[x]);
    printf("\"\n");
    printf("And just to be absolutely certain, printing the first index-first node, first index-second node respectively below\n");
    printf("Name: \"%s\", Number: \"", ((person*)newTable->listHead[0]->data)->name);
    for (x = 0; x < 10; ++x)
        printf("%d", ((person*)newTable->listHead[0]->data)->phoneNum[x]);
    printf("\"\n");
    printf("Name: \"%s\", Number: \"", ((person*)newTable->listHead[0]->next->data)->name);
    for (x = 0; x < 10; ++x)
        printf("%d", ((person*)newTable->listHead[0]->next->data)->phoneNum[x]);
    printf("\"\n");
    printf("\n");

    /* lookUpHash testing */
    printf("\t---LOOKUPHASH\n");
    int lookUpNum[10] = {9, 0, 5, 4, 1, 6, 6, 4, 7, 0};
    printf("Input: %p (the pointer value for the table we just created),\n", newTable);
    printf("       integer array: ");
    for (x = 0; x < 10; ++x)
        printf("%d ", lookUpNum[x]);
    printf("\n");
    printf("Expected output: <John Smith>\n");
    char * output;
    output = lookUpHash(newTable, lookUpNum);
    printf("Output: <%s>\n", output);
    free(output);
    printf("- Another -\n");
    lookUpNum[0] = 3;
    printf("Input: %p (the pointer value for the table we just created),\n", newTable);
    printf("       integer array corresponding to a phone number for Jane Doe previously inserted\n");
    printf("Expected output: <Jane Doe>\n");
    output = lookUpHash(newTable, lookUpNum);
    printf("Output: <%s>\n", output);
    free(output);
    lookUpNum[9] = 1;
    lookUpNum[0] = 9;
    printf("- Another -\n");
    printf("Input: %p (the pointer value for the table we just created),\n", newTable);
    printf("       integer array corresponding to a phone number for Jake Hurrell previously inserted\n");
    printf("Expected output: <Jake Hurrell>\n");
    output = lookUpHash(newTable, lookUpNum);
    printf("Output: <%s>\n", output);
    free(output);
    printf("- Another -\n");
    lookUpNum[0] = 3;
    lookUpNum[9] = 1;
    printf("Input: %p (the pointer value for the table we just created),\n", newTable);
    printf("       an integer array corresponding to a person not in the table (0054166471)\n");
    printf("Expected output: an error message\n");
    output = lookUpHash(newTable, lookUpNum);
    printf("Output: <%s>\n", output);
    printf("\n");

    /* printTable testing */
    printf("\t---PRINTTABLE\n");
    printf("Input: %p (the pointer value for the table we just created),\n", newTable);
    printTable(newTable);
    printf("\n");

    printf("END TESTING HASHTABLE ADT\n");
    printf("\n");

    return 0;
}
/* Rehashing the hash table whenever the load factor
   is greater than or equal to 75%
   PRE:  hash - pointer to the header of the hash table
         load - int ( the load factor)
   POST: return the updated hash table
		 (either the new one after rehash or the old one)
*/
HASH *rehash(HASH *hash, int load)
{
	int i, count, success;
	int size = ((load*100)/hash->size);
	int flag = 0;
	DATA exc;
	DATA *temp;
	HASH *out = NULL;

	if( size >= 75)
	{
		printf("The hash table is going to rehash!\n");
		printf(".\n");
		printf("..\n");
		printf("...\n");
		size = getPrime(load*2);
		out = createHashTable(size);

		for (i = 0; i < hash->size; i++)
		{
			flag = 0;
			if(hash->table[i].card.name != NULL)
			{
				strcpy(exc.CCN, hash->table[i].card.CCN);
				exc.cvc = hash->table[i].card.cvc;
				exc.name = hash->table[i].card.name;
				strcpy(exc.exp,hash->table[i].card.exp);
				insertHash(out, exc);
				if (hash->table[i].list->count != 0)
				{
					count = hash->table[i].list->count;
					while(flag < count)
					{
						success = removeSNODE(hash->table[i].list, hash->table[i].list->head->dataPtr, (void**)&temp);
						if(success)
						{
							strcpy(exc.CCN, temp->CCN);
							exc.cvc = temp->cvc;
							exc.name = temp->name;
							strcpy(exc.exp, temp->exp);
							insertHash (out, exc);
							free(temp);
						}
						flag++;
					}
				}
			}
			free(hash->table[i].list);
		}

		free(hash->table);
		free(hash);
		hash = out;
		printf("DONE rehashing!\n");
	}
	else
		printf("The efficiency is less than 75. No rehashing!\n");


	return hash;
}
Esempio n. 13
0
//===================================================================
// Reads in the data from a file and inserts into BST and hashed
// array.
//===================================================================
void readInFile(DATA_HEAD *data) {
    FILE *dataFile;
    COMPANY *companyNode;
    char filename[MAX_CHARS], tmpName[MAX_CHARS];
    char ch;
    int tmpRev, tmpProfit, tmpNumEmployee;
    int i = 0, isDuplicate, len, size;

    do {
        printf("Please enter a filename [enter for default]:");
        fgets(filename, MAX_CHARS, stdin);

        if (filename[0] == '\n')
            strcpy(filename, default_file);
        else {
            //flush new line
            len = strlen(filename);

            if (filename[len - 1] == '\n' || filename[len - 1] == '\r')
                filename[len - 1] = '\0'; // change '\n' to '\0'
            else // no '\n' read, so flush to '\n'
                while ((ch = getchar()) != '\n' && ch != '\r');
        }

        dataFile = fopen(filename, "r");
    } while(!dataFile);

    //Creates structures
    data->pTree  = createBST(myStringCompare);
    data->pStack = createStack();

    size = getArrSize(dataFile);
    //need to reopen connection
    dataFile = fopen(filename, "r");

    data->arraySize = size;
    data->count = 0;
    data->pHash = (HASH *)malloc(sizeof(DATA_HEAD) *data->arraySize);

    //initialize hashed array
    for (i = 0; i < data->arraySize; i++) {
        data->pHash[i].status = 0;
        data->pHash[i].numOfCollisions = 0;
        data->pHash[i].numOfProbes = 0;
        data->pHash[i].hashData = NULL;
    }

    //Reads in, parses, mallocs, assigns
    while (fscanf(dataFile, " %[^,],%d,%d,%d[^\n]", tmpName, &tmpRev, &tmpProfit, &tmpNumEmployee) != EOF)
    {
        companyNode = (COMPANY *)malloc(sizeof(COMPANY));

        //Checks to see if allocated properly
        if (!companyNode)
            exit(1);

        companyNode->companyName = (char *)malloc(strlen(tmpName) + 1);

        //Checks to see if allocated properly
        if (!(companyNode->companyName))
            exit(1);

        strcpy(companyNode->companyName, tmpName);
        companyNode->numberOfEmployees = tmpNumEmployee;
        companyNode->revenuePerBillion = tmpRev;
        companyNode->profitPerMillion = tmpProfit;

        //Inserts company data (name, revenue, profit, employees) into the BST
        //If duplicate, print an error
        isDuplicate = searchHash(data, tmpName, companyNode);
        if (isDuplicate == 1)
            printf("ERROR: DUPLICATE DATA\n");
        else
        {
            insertHash(data, companyNode);
            insertBST(data->pTree, companyNode);
            data->count++;
        }
    }
    printf("\nNumber Of Data Records read in: %d\n\n", data->count);
    fclose(dataFile);
}