gpt4 book ai didi

java - 散列以在大范围内均匀分配值(value)

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:40:14 25 4
gpt4 key购买 nike

我想设计一种算法,它采用一组值并将其均匀分布在更大的范围内。例如。我有 1000 个值,想将它们分布在 2^16 的值范围内。此外,输入值可以连续变化,我需要通过哈希函数不断解析每个输入值,以便它在我的输出范围内均匀分布。

为此我应该使用什么哈希算法?我正在用 Java 编写代码。

最佳答案

如果您只是散列整数,这是一种方法。

public class Hasho {

private static final Long LARGE_PRIME = 948701839L;
private static final Long LARGE_PRIME2 = 6920451961L;

public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(i + " -> " + hash(i));
}
}

public static int hash(int i) {
// Spread out values
long scaled = (long) i * LARGE_PRIME;

// Fill in the lower bits
long shifted = scaled + LARGE_PRIME2;

// Add to the lower 32 bits the upper bits which would be lost in
// the conversion to an int.
long filled = shifted + ((shifted & 0xFFFFFFFF00000000L) >> 32);

// Pare it down to 31 bits in this case. Replace 7 with F if you
// want negative numbers or leave off the `& mask` part entirely.
int masked = (int) (filled & 0x7FFFFFFF);
return masked;
}
}

这只是一个展示如何完成的示例。专业质量的哈希函数中包含一些严肃的数学。

关于java - 散列以在大范围内均匀分配值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3825870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com