0

I need to create a hash function that is supposed to return the sum of the ASCII values mod by 100(which is HASH_TABLE_SIZE) in a given char, but I don't seem to be getting the correct output. How do I correct this?

int string_set::hash_function(const char *s) { int h = 0; for (int i =0; i < *s; i++) { h = h + int(s[i]); return h % HASH_TABLE_SIZE; } return h; } 
5
  • 1
    What is the "correct" output? Commented Sep 28, 2015 at 3:30
  • 2
    What this i < *s supposed to mean? Commented Sep 28, 2015 at 3:31
  • for example hash_function("a") should return 97 , and hash_function("ab") would return 95 Commented Sep 28, 2015 at 3:33
  • i < *s is supposed to be such that i is less than the length of the char *s Commented Sep 28, 2015 at 3:35
  • 1
    What is "the length of the char *s"? Commented Sep 28, 2015 at 3:36

1 Answer 1

2

Do not return in the middle of process.

Try this:

int string_set::hash_function(const char *s) { int h = 0; for (int i =0; s[i] != '\0'; i++) // the loop condition didn't seem good { // the cast to unsigned char may be needed for system in which the type char is signed h = (h + (unsigned char)s[i]) % HASH_TABLE_SIZE; } return h; } 

This code will work well only if your system use ASCII code as character code for char.

Sign up to request clarification or add additional context in comments.

1 Comment

The int cast is redundant, integer promotions makes that same conversion anyway

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.