Question

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 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

//Your C code

#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 pw(int m,int p){
   int k=1;
   while(p--)
   k=k*m;
return k;
}
int hashFunc(char key[]) {
    // we assume key is always 3 characters long and always valid characters!
    // TODO implement
    int i,l = strlen(key),h=0;
    for( i = 0 ; i < l ; i++ ){
    if(i != l-1)
   h += key[i]*pw(31,l-(i+1));
   else
   h += key[i] ;
    }
    h=h%(HASHTABLE_SIZE);
    return h;
}
int hashFunc2(char key[]) {
    // same assumption as hashFunc
    // TODO implement
    int i,l = strlen(key),h=0;
    for( i = 0 ; i < l ; i++ ){
    if(i != l-1)
   h += key[i]*pw(37,l-(i+1));
   else
   h += key[i] ;
    }
    h=h%(7);
    h = h+1;
    return h;
}
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");
            int i = 1;
            while (i < HASHTABLE_SIZE) {
                int newIndex = (index + hashFunc2(key) * i) % 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 {
        // 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[], char 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{
        int i = 1;
            while (i < HASHTABLE_SIZE) {
                int newIndex = (index + hashFunc2(key) * i) % HASHTABLE_SIZE;
                if (table[newIndex] !=NULL) {
                    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;
}

//screenshot of my editor

//My output terminal

//If you have any doubt.Please feel free to ask.Thanks

Add a comment
Know the answer?
Add Answer to:
C programming Let's try to use the template below to implement a Set with double hashing....
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 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....

  • 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)...

  • Title: Implementation of chained hashing in Java or Python Description: Implement a double linked list with...

    Title: Implementation of chained hashing in Java or Python Description: Implement a double linked list with a procedure for adding list elements. Implement a hash table using chaining and the linked list discussed above. Use Array size m = 7 A hash function of: h = k mod 7 Insert 100 random key values into the table. Key values should be between 0 and 99. Implement a Search procedure that tells whether a particular key value is in the hash...

  • 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...

  • Identify the letters and anything associated with it. It is a hash map so please feel...

    Identify the letters and anything associated with it. It is a hash map so please feel free to point out the other important parts beside the arrows. I apologize for the order of the pictures class HashMap private: HashEntry table ; public: HashMap() table-new HashEntry * [TABLE_SIZE]; for (int 1-0; 1< TABLE SIZE: i++) table [i] = NULL; Hash Function int HashFunc(int key) return key % TABLE-SIZE; Insert Element at a key void Insert(int key, int value) int hashHashFunc(key); while...

  • 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...

  • Implement a software program in C++ t stores and searches the Student records using double-hashing algorithm.  Double...

    Implement a software program in C++ t stores and searches the Student records using double-hashing algorithm.  Double hashing uses the idea of applying a second hash function to key when a collision occurs.   The software program will be based on the following requirements: Development Environment: If the software program is written in C++, its project must be created using Microsoft Visual Studio 2017. If the software program is written in Java, its project must be created using NetBeans v8.2. Algorithm: If...

  • Your task is to go through and implement the methods getBucketIndex, add, get, and remove. Follow...

    Your task is to go through and implement the methods getBucketIndex, add, get, and remove. Follow the comments inside respective methods. import java.util.ArrayList; import java.util.Scanner; public class HashtableChaining<K, V> {    // Hashtable bucket    private ArrayList<HashNode<K, V>> bucket;    // Current capacity of the array list    private int numBuckets;    // current size of the array list    private int size;       public HashtableChaining(int buckets){        bucket = new ArrayList<>();        numBuckets = buckets;   ...

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