Playing with hashing: Random.new() with different seeds producing the exact same result?

Hey yall, I’m playing around with hashing for the first time, and I’m trying to use it to generate psuedo-random colors for usernames. This is what I have right now:

local function bkdrHash(str)
    local seed = 131 -- 31 131 1313 13131 131313 etc..
    local hash = 1
    
    for i=1, str:len() do
        hash = (hash * seed) + str:byte(i)
    end
    
    return hash
end

local function getNameColor(name)
    local seed = bkdrHash(name)
    local rng = Random.new(seed)
    local hue = rng:NextNumber()
    
    print(name)
    print("seed", seed)
    print("hue", hue)
    
    return Color3.fromHSV(hue, 0.8, 0.8)
end

getNameColor("vocksel")
getNameColor("david lastname")
getNameColor("david vocksel")

The problem I’m running into is that when this prints, these are the results I get. Notice that the hue for david lastname and david vocksel are the exact same number. Yet their seeds are drastically different.

vocksel
seed 1.262736094302e+15
hue 0.28863467717504
david lastname
seed 7.7542835647773e+29
hue 0.20012743358005
david vocksel
seed 5.9193004311277e+27
hue 0.20012743358005

Why is that, and how can I fix it? The hashing algorithm I’m using is based off the BKDR Hash, found here.

Seeds are clamped to a 64-bit signed int, so any values above 2^63-1 are clamped and will give the same result.
Generally, it’s best to keep Lua numbers below 2^53 to fit in a double.

Very good to know. I completely blanked on how exponent notation works in Lua and thought I was within the int limit. I rewrote my hashing function to use a smaller prime to multiply the hash.

local function hash(str)
    local result = 0
    for i=1, str:len() do
        result = result + str:byte(i)
    end
    return result
end

local function getNameColor(name)
    local rng = Random.new(hash(name))
    local hue = rng:NextNumber()
    
    return Color3.fromHSV(hue, 0.5, 1)
end

Now it stays well within the 64 bit int range, and I can create some really nice pseudo random colors.

image

1 Like