Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hash pseudo code does not match actual code #24

Open
byarmis opened this issue Nov 3, 2017 · 2 comments
Open

Hash pseudo code does not match actual code #24

byarmis opened this issue Nov 3, 2017 · 2 comments

Comments

@byarmis
Copy link

byarmis commented Nov 3, 2017

The pseduo-code

    hash = 0
    string_len = length(string)
    for i = 0, 1, ..., string_len:
        hash += (a ** (string_len - (i+1))) * char_code(string[i])
    hash = hash % num_buckets
    return hash

takes the modulus of the hash value and the number of buckets once, immediately before returning it. The actual code

static int ht_hash(const char* s, const int a, const int m) {
    long hash = 0;
    const int len_s = strlen(s);
    for (int i = 0; i < len_s; i++) {
        hash += (long)pow(a, len_s - (i+1)) * s[i];
        hash = hash % m;
    }
    return (int)hash;
}

takes the modulus of the hash value and the number of buckets for each letter in the input string.

@SimonWang2014
Copy link

yep, the pseudocode is a little difference with the actual code, but the results are equally :)

@cyber-chris
Copy link

The results are not equal. Run this and see it outputs 21, not 5 as in the pseudo-code. Although, it's probably because of C precision vs Python precision.

#include <stdio.h>

// hash_table.c
static int ht_hash(const char* s, const int a, const int m) {
    long hash = 0;
    const int len_s = strlen(s);
    for (int i = 0; i < len_s; i++) {
        hash += (long)pow(a, len_s - (i+1)) * s[i];
        hash = hash % m;
    }
    return (int)hash;
}

int main()
{
    printf("Hello World, %d", ht_hash("cat", 163, 53));

    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants