You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.5 KiB
67 lines
1.5 KiB
/**
|
|
* File: simple_hash.cs
|
|
* Created Time: 2023-06-26
|
|
* Author: hpstory (hpstory1024@163.com)
|
|
*/
|
|
|
|
namespace hello_algo.chapter_hashing;
|
|
|
|
public class simple_hash {
|
|
/* 加法雜湊 */
|
|
int AddHash(string key) {
|
|
long hash = 0;
|
|
const int MODULUS = 1000000007;
|
|
foreach (char c in key) {
|
|
hash = (hash + c) % MODULUS;
|
|
}
|
|
return (int)hash;
|
|
}
|
|
|
|
/* 乘法雜湊 */
|
|
int MulHash(string key) {
|
|
long hash = 0;
|
|
const int MODULUS = 1000000007;
|
|
foreach (char c in key) {
|
|
hash = (31 * hash + c) % MODULUS;
|
|
}
|
|
return (int)hash;
|
|
}
|
|
|
|
/* 互斥或雜湊 */
|
|
int XorHash(string key) {
|
|
int hash = 0;
|
|
const int MODULUS = 1000000007;
|
|
foreach (char c in key) {
|
|
hash ^= c;
|
|
}
|
|
return hash & MODULUS;
|
|
}
|
|
|
|
/* 旋轉雜湊 */
|
|
int RotHash(string key) {
|
|
long hash = 0;
|
|
const int MODULUS = 1000000007;
|
|
foreach (char c in key) {
|
|
hash = ((hash << 4) ^ (hash >> 28) ^ c) % MODULUS;
|
|
}
|
|
return (int)hash;
|
|
}
|
|
|
|
[Test]
|
|
public void Test() {
|
|
string key = "Hello 演算法";
|
|
|
|
int hash = AddHash(key);
|
|
Console.WriteLine("加法雜湊值為 " + hash);
|
|
|
|
hash = MulHash(key);
|
|
Console.WriteLine("乘法雜湊值為 " + hash);
|
|
|
|
hash = XorHash(key);
|
|
Console.WriteLine("互斥或雜湊值為 " + hash);
|
|
|
|
hash = RotHash(key);
|
|
Console.WriteLine("旋轉雜湊值為 " + hash);
|
|
}
|
|
}
|