Skip to content

Instantly share code, notes, and snippets.

@direvus
Created October 10, 2018 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save direvus/29dc135a22cb06706932185a2c3ea179 to your computer and use it in GitHub Desktop.
Save direvus/29dc135a22cb06706932185a2c3ea179 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
unsigned int hash(char *k) {
unsigned int result = 0;
size_t len = strlen(k);
if (len == 0) {
return 0;
} else if (len == 1) {
return k[0];
}
for (unsigned int i = 0; i < len - 1; i++) {
result <<= 1;
result += k[i+1] * (k[i] - 1);
}
return result;
}
int main(int argc, char **argv) {
if (argc < 2) {
const int SIZE = 1024;
char buf[SIZE];
while(fgets(buf, SIZE, stdin) != NULL) {
size_t pos = strlen(buf) - 1;
if (buf[pos] == '\n') {
buf[pos] = 0;
}
printf("%u\n", hash(buf));
}
return 0;
}
printf("%u\n", hash(argv[1]));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment