首页 > 解决方案 > 用于噪声生成的散列函数

问题描述

我正在制作价值噪声生成器,我发现我当前的哈希在图像中产生了一种模式:

在此处输入图像描述

所以我正在寻找一个更好的哈希函数,不可预测/可重复。

我使用哈希而不是随机数,因为我希望它是确定性的。给定一个 (x, y) 坐标,它应该总是产生相同的结果。

如果可以扩展散列函数以轻松接受更多参数,例如 (x, y, z) 或 (x, y, z, t),而不仅仅是两个,这也很好,但不是强制性的。

我当前的哈希是:

public static class Hash
{
    public static float GetHash(int x)
    {
        x = x ^ 61 ^ (x >> 16);
        x += x << 3;
        x ^= x >> 4;
        x *= 0x27d4eb2d;
        x ^= x >> 15;
        return x / (float)int.MaxValue;
    }

    public static float GetHash(int x, int y) => GetHash((y << 8) + x);
}

我添加了这一行x / (float)int.MaxValue,因为我想要一个从 0 到 1 的浮点结果。

但我必须承认我只是从某个地方复制粘贴它。按位运算(和哈希)不是我的强项。

标签: c#hashhashcode

解决方案


原始答案:我会使用像https://github.com/Auburns/FastNoise_CSharp这样的库 也许您可以从该 FastNoise.cs 文件中的源代码中学习

修改后的答案,包括来自参考来源“Copyright(c) 2017 Jordan Peck”的代码、散列函数

private const int X_PRIME = 1619;
private const int Y_PRIME = 31337;
private const int Z_PRIME = 6971;
private const int W_PRIME = 1013;

private static int Hash2D(int seed, int x, int y)
{
    int hash = seed;
    hash ^= X_PRIME * x;
    hash ^= Y_PRIME * y;

    hash = hash * hash * hash * 60493;
    hash = (hash >> 13) ^ hash;

    return hash;
}

private static int Hash3D(int seed, int x, int y, int z)
{
    int hash = seed;
    hash ^= X_PRIME * x;
    hash ^= Y_PRIME * y;
    hash ^= Z_PRIME * z;

    hash = hash * hash * hash * 60493;
    hash = (hash >> 13) ^ hash;

    return hash;
}

private static int Hash4D(int seed, int x, int y, int z, int w)
{
    int hash = seed;
    hash ^= X_PRIME * x;
    hash ^= Y_PRIME * y;
    hash ^= Z_PRIME * z;
    hash ^= W_PRIME * w;

    hash = hash * hash * hash * 60493;
    hash = (hash >> 13) ^ hash;

    return hash;
}

推荐阅读