我需要一个哈希函数来将 1000 个数字映射到一个 50*50 矩阵。我的数字是 8 位十六进制。我使用:
static int[,] matrix = new int[50, 50];
int m=hex[0 to 3]%50;
int n=hex[4 to 7]%50;
matrix[m,n]++;
但它的功能非常糟糕并且有很大的冲突。事实上我会计算网络数据包窗口中源 IP 的数量。 请帮我!
最佳答案
此类保证没有冲突 :-) 请注意,返回的哈希值是连续的。给出的第一个不同数字的哈希值将为 0,给出的第二个不同数字的哈希值将为 1,依此类推。
public class Hasher
{
private readonly Dictionary<int, int> Hashes = new Dictionary<int, int>();
public int Hash(int value)
{
int hash;
if (!Hashes.TryGetValue(value, out hash))
{
hash = Hashes.Count;
Hashes[value] = Hashes.Count;
}
return hash;
}
}
像这样使用:
var hasher = new Hasher();
int hash1 = hasher.Hash(11); // 0
int hash2 = hasher.Hash(27); // 1
int hash3 = hasher.Hash(11); // 0
int hash4 = hasher.Hash(47); // 2
int hash5 = hasher.Hash(47); // 2
关于c# - 什么是限制范围输出的好散列函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29485701/