我需要一个哈希函数将1000个八位十六进制数字映射到一个50*50的矩阵中。我使用的是:
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地址的数量。请帮助我!
我需要一个哈希函数将1000个八位十六进制数字映射到一个50*50的矩阵中。我使用的是:
static int[,] matrix = new int[50, 50];
int m=hex[0 to 3]%50;
int n=hex[4 to 7]%50;
matrix[m,n]++;
这个类保证没有碰撞 :-) 请注意返回的哈希值是连续的。第一个不同数字的哈希值将为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