WoW:USERAPI StringHash: Difference between revisions

no edit summary
(→‎Code: W/ the 2.0 changes, lua 5.1 renamed math.mod to math.fmod)
No edit summary
Line 5: Line 5:
Return a fair-quality 32-bit hash of a string
Return a fair-quality 32-bit hash of a string


  hashVal = ''<PREFIX>''_StringHash("string")
  hashVal = StringHash("string")




== Example ==
== Example ==
  > print(PREFIX_StringHash(""))
  > print(StringHash(""))
  1  
  1  
  > print(<PREFIX>_StringHash("ab"))
  > print(StringHash("ab"))
  3458343178
  3458343178
  > print(<PREFIX>_StringHash("ba"))
  > print(StringHash("ba"))
  3466747145
  3466747145
  > print(<PREFIX>_StringHash("AB"))
  > print(StringHash("AB"))
  2653593770
  2653593770
  > print(<PREFIX>_StringHash("BA"))
  > print(StringHash("BA"))
  2661997737
  2661997737
  > print(<PREFIX>_StringHash("The quick brown fox jumps over the lazy dog"))
  > print(StringHash("The quick brown fox jumps over the lazy dog"))
  3402772626
  3402772626


Line 31: Line 31:


==Code==
==Code==
  function ''&lt;PREFIX&gt;''_StringHash(text)
  local function StringHash(text)
   local counter = 1;
   local counter = 1
   local len = string.len(text);
   local len = string.len(text)
   for i = 1, len, 3 do  
   for i = 1, len, 3 do  
     counter = math.fmod(counter*8161, 4294967279) +  -- 2^32 - 17: Prime!
     counter = math.fmod(counter*8161, 4294967279) +  -- 2^32 - 17: Prime!
     (string.byte(text,i)*16776193) +
     (string.byte(text,i)*16776193) +
     ((string.byte(text,i+1) or (len-i+256))*8372226) +
     ((string.byte(text,i+1) or (len-i+256))*8372226) +
     ((string.byte(text,i+2) or (len-i+256))*3932164);
     ((string.byte(text,i+2) or (len-i+256))*3932164)
   end;
   end
   return math.fmod(counter, 4294967291); -- 2^32 - 5: Prime (and different from the prime in the loop)
   return math.fmod(counter, 4294967291) -- 2^32 - 5: Prime (and different from the prime in the loop)
  end
  end


Anonymous user