c# - 什么是限制范围输出的好散列函数

标签 c# hash

我需要一个哈希函数来将 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/

相关文章:

c# - 从字符串中提取特定文本

c# - DataGridView 单元格类型

perl - 如何维护添加到Perl哈希中的键的顺序?

cryptography - 数字签名 - 分布式环境 - 单独的哈希和签名

c# - C#中的多线程CPU使用率

c# - 正在寻找 C# TDD 框架?

mysql - 哈希索引与 Elasticsearch

hash - if 语句的 Ocaml 错误

java - Apache DigestUtils 似乎计算 MD5 部分错误

c# - 文件正在被另一个进程错误使用