Skip to content

Instantly share code, notes, and snippets.

@VirgilMing
Last active November 15, 2017 16:25
Show Gist options
  • Save VirgilMing/f0b40a41e8482d8cc8e1bfeafc7f51a4 to your computer and use it in GitHub Desktop.
Save VirgilMing/f0b40a41e8482d8cc8e1bfeafc7f51a4 to your computer and use it in GitHub Desktop.
myCircleHash
// tested on gcc version 7.2.0 (Homebrew GCC 7.2.0 --with-jit) on macOS 10.12.6
#include <string>
#include <iostream>
#include <functional> // std::hash
int NextCoprime(int (&c)[0xff], char x)
{
return c[x] = (c[x] - x) * c[x] + x;
}
int NextPair(int a, int b, int (&c)[0xff], char x, char y)
{
return a * NextCoprime(c, x) * std::hash<char>{}(x) +
b * std::hash<char>{}(y);
}
static int Hash(std::string s)
{
int H = 0;
if (s.length() > 0)
{
int a = s.length(), b = s.length() + 1;
int c[0xff] = {};
for (int i = 0; i < 0xff; i++)
{
c[i] = i + 1;
}
H = NextPair(a,b,c, s[s.length() - 1], s[0]);
for (unsigned i = 1; i < s.length(); i++)
{
H ^= NextPair(a,b,c, s[i-1], s[i]);
}
}
return H;
}
int main()
{
std::cout << Hash ("abcdef") << std::endl;
std::cout << Hash ("bcdefa") << std::endl;
std::cout << Hash ("cdefab") << std::endl;
std::cout << Hash ("cdfeab") << std::endl;
std::cout << Hash ("a0a0") << std::endl;
std::cout << Hash ("1010") << std::endl;
std::cout << Hash ("0abc0def0ghi") << std::endl;
std::cout << Hash ("0def0abc0ghi") << std::endl;
std::cout << Hash ("0def0ghi0abc") << std::endl;
// these three lines all returned 256293745 for me
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment