I thought of a simple way to hash a string. By taking the ASCII decimal value of each character, multiplying it by 10, and adding all of the values computed together for each character in a string. Is there a name for this algorithm? I highly doubt I was the first one to think of this.
Compiled with gcc -Wall -Wextra -Werror -std=c99 string.c -o string
#include <stdio.h>
#include <stddef.h>
size_t stringLength(const char* source)
{
if(source == NULL) { return 0; }
size_t length = 0;
while(*source != '\0') {
length++;
source++;
}
return length;
}
static size_t getHash(const char* source)
{
size_t length = stringLength(source);
size_t hash = 0;
for(size_t i = 0; i < length; i++) {
char c = source[i];
int a = c - '0';
hash = (hash * 10) + a;
}
return hash;
}
static const char *const testCases[] = {
"this",
"is",
"a",
"test",
"but",
"i",
"should",
"use",
"real",
"dictonary"
};
#define TABLE_SIZE (16)
int main()
{
size_t name = getHash("Ryan McCullagh");
printf("%zu\n", name);
for(size_t i = 0; i < (sizeof(testCases) / sizeof(testCases[0])); i++) {
const char* source = testCases[i];
size_t hash = getHash(source);
printf("%s <==> %zu\n", source, (hash % TABLE_SIZE));
}
return 0;
}