Question

C programming Problem 3 [Set via Hashing] As mentioned in the lecture, a hash table can...

C programming

Problem 3 [Set via Hashing]

As mentioned in the lecture, a hash table can be used to implement a Set ADT. Let's try to use the template below to implement a Set with double hashing. Here we assume the Set contains names with 3 characters long. Since it is a Set, we do not need to have an explicit value for each key. We will use a token value of 1 if a name belongs to the Set. Let's reuse the exact hash functions we have seen in example in Part 7 of the lecture notes, page 3. As a reminder, we had the following hash function for the string s of length n on a table size m = 10:

h(s) = (s[0] * 31n-1 + s[1] * 31n-2 + … s[n-1]) % m For the double hashing we will use the following second hash function (we want to avoid 0 for an obvious reason):

h2(s) = (s[0] * 37n-1 + s[1] * 37n-2 + … s[n-1]) % 7 + 1

where 7 is a random prime number we picked. By definition, for double hashing, when collision happens, we will pick the next index for probing by the formula:

(h(s) + i * h2(s)) % m

for i = 1...m-1 consecutively.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define HASHTABLE_SIZE 10

typedef struct {

    char key[4];     // in this example, key is always 3 characters long!

    int value;     // since we are implementing a set, value is 1 or 0

} KeyValuePair;

void printHashtable(KeyValuePair* table[]) {

    // print out the hash table so that you will see if you have done

    // things correctly!

    int i;

    for (i=0;i<HASHTABLE_SIZE;i++) {

        if (table[i] == NULL) {

            printf("%2d: -\n",i);

        } else {

            printf("%2d: <%s,%d>\n",i,table[i]->key,table[i]->value);

        }   

    }

}

int hashFunc(char key[]) {

    // we assume key is always 3 characters long and always valid characters!

   

    // TODO implement

    return 0;

}

int hashFunc2(char key[]) {

    // same assumption as hashFunc

   

    // TODO implement

    return 1;

}

void insert(KeyValuePair* table[], char key[]) {

    // insert a key and value

    printf("inserting %s to the set...\n",key);

    int hash = hashFunc(key);

    int index = hash;

    if (table[index] != NULL) {

        printf("collision! we should use double hashing this time\n");

       

        // TODO implement

        // HINT: int newIndex = (index + hashFunc2(key) * i) % HASHTABLE_SIZE;

        return;

    } else {

        // add the new key-value pair to the correct position

        printf("Entry inserted at position %d\n",index);

        KeyValuePair* newEntry = (KeyValuePair*) malloc(sizeof(KeyValuePair));

        strcpy(newEntry->key,key);

        newEntry->value = 1;

        table[index] = newEntry;

    }

}

int lookup(KeyValuePair *table[], int key) {

    // look up a key and return 1 if it is in the set, 0 otherwise

    int hash = hashFunc(key);

    int index = hash;

    if (table[index] != NULL) {

        if (strcmp(table[index]->key,key) == 0)

            return 1;

        else

            // collision happened? should we do something?

            // TODO implement

  

            return 0;

    } else {

        return 0;

    }

}

int main()

{

   

    KeyValuePair* hashtable[HASHTABLE_SIZE] = {NULL};

    insert(hashtable,"Ted");

    insert(hashtable,"Joe");

    insert(hashtable,"May");

    insert(hashtable,"Ken");

    insert(hashtable,"Bob");

   

    printHashtable(hashtable);

    printf("Lookup %s - result: %d\n", "Ted", lookup(hashtable,"Ted"));

    printf("Lookup %s - result: %d\n", "Joe", lookup(hashtable,"Joe"));

    printf("Lookup %s - result: %d\n", "Bob", lookup(hashtable,"Bob"));

    printf("Lookup %s - result: %d\n", "Ken", lookup(hashtable,"Ken"));

    return 0;

}

If done correctly, you should get the following output:

0: <Ken,1>                                                                                                                 
1: -                                                                                                          
2: -                                                                                                                 
3: -                                                                                                                  
4: -                                                                                                                 
5: <Ted,1>                                                                                                            
6: <Joe,1>                                                                                                           
7: <May,1>                                                                                                            
8: -                                                                                                                 
9: <Bob,1>

                                                                                                          
Lookup Ted - result: 1                                                                                                
Lookup Joe - result: 1                                                                                                
Lookup Bob - result: 1                                                                                                
Lookup Ken - result: 1

Please paste your code here:

0 0
Add a comment Improve this question Transcribed image text
Answer #1

EXECUTABLE CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<math.h>
#define HASHTABLE_SIZE 10

typedef struct {

char key[4];

int value;

} KeyValuePair;

void printHashtable(KeyValuePair* table[]) {


int i;

for (i=0;i<HASHTABLE_SIZE;i++) {

if (table[i] == NULL) {

printf("%2d: -\n",i);

} else {

printf("%2d: <%s,%d>\n",i,table[i]->key,table[i]->value);

}

}

}

int hashFunc(char key[]) {

int hash= key[0]*pow(31,2)+key[1]*pow(31,1)+key[2]*pow(31,0);


hash=hash%HASHTABLE_SIZE;


return hash;

}

int hashFunc2(char key[]) {

int hash= key[0]*pow(37,2)+key[1]*pow(37,1)+key[2]*pow(37,0);


hash=(hash%7)+1;


return hash;

}

void insert(KeyValuePair* table[], char key[]) {

printf("inserting %s to the set...\n",key);

int hash = hashFunc(key);
int index = hash;

if (table[index] != NULL) {

printf("collision! we should use double hashing this time\n");

int index2=hashFunc2(key);
int i=1;
while(1)
{

int newIndex=(index+ i*index2)%HASHTABLE_SIZE;
if (table[newIndex] ==NULL)
{
printf("Entry inserted at position %d\n",newIndex);

KeyValuePair* newEntry = (KeyValuePair*) malloc(sizeof(KeyValuePair));

strcpy(newEntry->key,key);

newEntry->value = 1;

table[newIndex] = newEntry;
break;
}
i++;
}

  

return;

} else {

printf("Entry inserted at position %d\n",index);

KeyValuePair* newEntry = (KeyValuePair*) malloc(sizeof(KeyValuePair));

strcpy(newEntry->key,key);

newEntry->value = 1;

table[index] = newEntry;

}

}

int lookup(KeyValuePair *table[], int key) {


int hash = hashFunc(key);

int index = hash;

if (table[index] != NULL) {

if (strcmp(table[index]->key,key) == 0)

return 1;

else
{

int index2=hashFunc2(key);
int i=1;
while(1)
{

int newIndex=(index+ i*index2)%HASHTABLE_SIZE;
if (strcmp(table[newIndex]->key,key) == 0)
{
return 1;
}
i++;
}

  

return 0;
}   
} else {

return 0;

}

}

int main()

{

KeyValuePair* hashtable[HASHTABLE_SIZE] = {NULL};

insert(hashtable,"Ted");

insert(hashtable,"Joe");

insert(hashtable,"May");

insert(hashtable,"Ken");

insert(hashtable,"Bob");

printHashtable(hashtable);

printf("Lookup %s - result: %d\n", "Ted", lookup(hashtable,"Ted"));

printf("Lookup %s - result: %d\n", "Joe", lookup(hashtable,"Joe"));

printf("Lookup %s - result: %d\n", "Bob", lookup(hashtable,"Bob"));

printf("Lookup %s - result: %d\n", "Ken", lookup(hashtable,"Ken"));

return 0;

}

Add a comment
Know the answer?
Add Answer to:
C programming Problem 3 [Set via Hashing] As mentioned in the lecture, a hash table can...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C programming Let's try to use the template below to implement a Set with double hashing....

    C programming Let's try to use the template below to implement a Set with double hashing. Here we assume the Set contains names with 3 characters long. Since it is a Set, we do not need to have an explicit value for each key. We will use a token value of 1 if a name belongs to the Set. Let's reuse the exact hash functions we have seen in example in Part 7 of the lecture notes, page 3. As...

  • Please answer this problem in C++, Thank you! Read and study the sample program: "hashing with chaining using singly...

    Please answer this problem in C++, Thank you! Read and study the sample program: "hashing with chaining using singly linked lists", as well as "hashing with chaining using doubly linked lists". Notice this program is complete except it doesn't include the remove function. Write the remove function and test it with the rest of the program including the given main program. Upload your C++ source file. ---Here is the referenced program: "hashing with chaining using singly linked lists". Below this...

  • Follow the TODOs and complete the insertItem(), searchItem() and printTable() functions in hash.cpp. The hash function...

    Follow the TODOs and complete the insertItem(), searchItem() and printTable() functions in hash.cpp. The hash function has already been implemented for you. // hash.CPP program to implement hashing with chaining #include<iostream> #include "hash.hpp" using namespace std; node* HashTable::createNode(int key, node* next) { node* nw = new node; nw->key = key; nw->next = next; return nw; } HashTable::HashTable(int bsize) { this->tableSize= bsize; table = new node*[tableSize]; for(int i=0;i<bsize;i++) table[i] = nullptr; } //function to calculate hash function unsigned int HashTable::hashFunction(int key)...

  • Type up and get the Hash table on pages 19 - 22 to work. Show your...

    Type up and get the Hash table on pages 19 - 22 to work. Show your sample test run at the bottom of your code using a multiline comment I typed everything but the code is not working please help me fix the mistakes. These are pages 19-22. The code I have: #include <iostream> #inlcude <iomanip> #include <stack> #include <vector> #include <cstdlib> #include <ctime> using namespace std; //////////////////////////////HASH TABLE/////////////////////////////////////////////// //hash.cpp //demonstrate hash table with linear probing /////////////////////////////////////////////////////////////////////////////////////// class DataItem {...

  • Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into...

    Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into hash table we insert at an index calculated by the key modulo the array size, what would happen if we instead did key mod (array_size*2), or key mod (array_size/2)? (Describe both cases). Theory answer Here Change your hashtable from the labs/assignments to be an array of linkedlists – so now insertion is done into a linkedlist at that index. Implement insertion and search. This...

  • Name: Hash Tables CS 2020 Hw 14 edefine MAX CAPACITY 11 #define R struct HashTable f...

    Name: Hash Tables CS 2020 Hw 14 edefine MAX CAPACITY 11 #define R struct HashTable f int hashtable[MAX CAPACITY]: 1/ table to store values int countj // count of values currently stored int hash1(int value) ( return (value % MAX CAPACITY); int hash2(int value) ( return (R- (value % R)); 1) Use hash1 function and linear probing as a collision resolution strategy, insert the following elements into the correct index of the hash table: 1, 5, 4, 11, 21, 15,...

  • C++: Create a class called "HashTable" This class will implement hashing on an array of integers...

    C++: Create a class called "HashTable" This class will implement hashing on an array of integers Make the table size 11 Implement with linear probing. The hash function should be: h(x) = x % 11 Create search(), insert() and delete() member functions. Search should return the index of where the target is located, insert should allow the user to insert a value, and delete removes the desired value from the table. In main perform the following: 1. Insert: 17 11...

  • please use Java!! We are storing the inventory for our fruit stand in a hash table....

    please use Java!! We are storing the inventory for our fruit stand in a hash table. The attached file shows all the possible key/fruit combinations that can be inserted into your hash table. These are the real price lookup values for the corresponding fruit. Problem Description In this programming assignment, you will implement a hash table class fruitHash. Your hash table must include the following methods: 1) hashFunction(key) This method takes a key as an argument and returns the address...

  • 5. Hashing (a) Consider a hash table with separate chaining of size M = 5 and...

    5. Hashing (a) Consider a hash table with separate chaining of size M = 5 and the hash function h(x) = x mod 5. i. (1) Pick 8 random numbers in the range of 10 to 99 and write the numbers in the picked sequence. Marks will only be given for proper random numbers (e.g., 11, 12, 13, 14 ... or 10, 20, 30, 40, .. are not acceptable random sequences). ii. (2) Draw a sketch of the hash table...

  • Insert elements into a hash table implemented using chain hashing, as an array of linked list...

    Insert elements into a hash table implemented using chain hashing, as an array of linked list in which each entry slot is as a linked list of key/value pairings that have the same hash (outcome value computed using certain hash function). You are allowed to use “Hash Function”, h(k) = k % x where, x is the value you will need to decide to use, that you find appropriate for this implementation. The main requirements are the following: 1. Input:...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT