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
/*
* Copyright (c) 2015 Ryan McCullagh
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#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;
}