【发布时间】:2017-01-04 20:34:20
【问题描述】:
我经常发现自己需要一个哈希表,其值在编译时已知并且永远不会改变。
我想知道是否有一种标准方法可以生成只用于特定哈希表的定制算法,这样就不需要在运行时构造它,并确保没有冲突。
这种最糟糕的算法就是执行一系列 if 语句,但这有点破坏 O(N)ness。
我想知道是否有一些现有的算法可以将固定数量的唯一字符串映射到从 0 到唯一字符串数量的索引。
例如;我可能有一个哈希表
{
"one": "1",
"two": "2",
"three": "3"
}
创建这样一个硬编码表的一个天真的尝试是用一个内部条目对表创建一个函数,并提出一些任意的区分,例如下面的一个。
#include <stdio.h>
#include <string.h>
#include <math.h>
static const char *my_hash(const char *input)
{
const struct {
const char *key;
const char *value;
} h_table[] = {
{"three", "3"},
{"one", "1"},
{"two", "2"}
};
int hash;
int len = strlen(input);
if (len != 3 && len != 5) {
return (char *)0;
}
hash = (int)ceil((((input[1] - 102) / 4) - 1) / 2.0);
return h_table[hash].value;
}
int main(int argc, char **argv)
{
puts(my_hash("one"));
puts(my_hash("two"));
puts(my_hash("three"));
return 0;
}
有没有一种已知的算法可以生成这种算法?
总结:是否存在将 N 个不同字符串映射到从 0 到 N-1 的 N 个不同整数的已知算法?
我觉得这样的东西已经存在了。
【问题讨论】: