Search code examples
c++hashmappseudocode

How do I implement this Pseudocode?


I am trying to write a function to hash strings into integers so I can use strings as keys in my hash map. I'm required to use the pseudocode written below, but I still can't get it to work without errors. The program is to enter a German word (as key) and return it's English translation (as value).

The pseudocode:

Parameters : natural numbers i, h = 0; Field s
 for i = 0 to i <length_of (s)
    h = (h * 128 + s [i]) mod M;
Result : h.

My code:

#include "pch.h"
#include <iostream>
#include <string>
#define M 661
using namespace std;

struct entry {
    string key_de, val_en;
};

int HASH(int i, int h = 0, struct entry ex_array[])
{
    for (i = 0; i < sizeof(ex_array) / sizeof(ex_array[0]); i++)
    {
        h = (h * 128) + ex_array[i] % m;
    }
    return h;
}

int main()
{

}

Solution

  • This would be a way you could implement that

    #include <string>
    #define M 661
    
    int Hash(std::string s, int h = 0){
       for(int i = 0 ; i < s.length(); i++)
          h = (h * 128 + s [i]) % M;
       return h;
    }
    

    I have one note though. In the pseudo code you provided i'm not so sure that the "parameters" provided are talking about actual function parameters because it seems a little strange to pass in 'i' since you immediately set it to to 0 (for i = 0 ...). But if you do need to pass 'i' in then you can just add it to the beginning of the argument list and remove the 'int' from inside the for loop.

    Then you can use this function to get the hash value of the German word.

    Here's an example of how to use it

    string arr[M]; //assuming M is size of array
    std::string germanWord{"german"}; //some German word
    std::string englishWord{"english"} //same word but in English
    arr[Hash(germanWord)] = englishWord //adding new English word to the array
    string s = arr[Hash(germanWord)] // accessing that word from the array
    

    there are other things you might have to think about if you are going to make an actual hash map (Like how you deal with collisions) but this is enough if you just want to implement that pseudo code.

    Good luck!