2023-06-26 23:08:55 +08:00
|
|
|
|
/**
|
|
|
|
|
* File: simple_hash.cs
|
|
|
|
|
* Created Time: 2023-06-26
|
|
|
|
|
* Author: hpstory (hpstory1024@163.com)
|
|
|
|
|
*/
|
|
|
|
|
|
2023-09-02 23:54:38 +08:00
|
|
|
|
namespace hello_algo.chapter_hashing;
|
2023-06-26 23:08:55 +08:00
|
|
|
|
|
|
|
|
|
public class simple_hash {
|
|
|
|
|
/* 加法哈希 */
|
2023-10-08 01:33:46 +08:00
|
|
|
|
public static int AddHash(string key) {
|
2023-06-26 23:08:55 +08:00
|
|
|
|
long hash = 0;
|
|
|
|
|
const int MODULUS = 1000000007;
|
|
|
|
|
foreach (char c in key) {
|
|
|
|
|
hash = (hash + c) % MODULUS;
|
|
|
|
|
}
|
|
|
|
|
return (int)hash;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* 乘法哈希 */
|
2023-10-08 01:33:46 +08:00
|
|
|
|
public static int MulHash(string key) {
|
2023-06-26 23:08:55 +08:00
|
|
|
|
long hash = 0;
|
|
|
|
|
const int MODULUS = 1000000007;
|
|
|
|
|
foreach (char c in key) {
|
|
|
|
|
hash = (31 * hash + c) % MODULUS;
|
|
|
|
|
}
|
|
|
|
|
return (int)hash;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* 异或哈希 */
|
2023-10-08 01:33:46 +08:00
|
|
|
|
public static int XorHash(string key) {
|
2023-06-26 23:08:55 +08:00
|
|
|
|
int hash = 0;
|
|
|
|
|
const int MODULUS = 1000000007;
|
|
|
|
|
foreach (char c in key) {
|
|
|
|
|
hash ^= c;
|
|
|
|
|
}
|
|
|
|
|
return hash & MODULUS;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* 旋转哈希 */
|
2023-10-08 01:33:46 +08:00
|
|
|
|
public static int RotHash(string key) {
|
2023-06-26 23:08:55 +08:00
|
|
|
|
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 算法";
|
|
|
|
|
|
2023-10-08 01:33:46 +08:00
|
|
|
|
int hash = AddHash(key);
|
2023-06-26 23:08:55 +08:00
|
|
|
|
Console.WriteLine("加法哈希值为 " + hash);
|
|
|
|
|
|
2023-10-08 01:33:46 +08:00
|
|
|
|
hash = MulHash(key);
|
2023-06-26 23:08:55 +08:00
|
|
|
|
Console.WriteLine("乘法哈希值为 " + hash);
|
|
|
|
|
|
2023-10-08 01:33:46 +08:00
|
|
|
|
hash = XorHash(key);
|
2023-06-26 23:08:55 +08:00
|
|
|
|
Console.WriteLine("异或哈希值为 " + hash);
|
|
|
|
|
|
2023-10-08 01:33:46 +08:00
|
|
|
|
hash = RotHash(key);
|
2023-06-26 23:08:55 +08:00
|
|
|
|
Console.WriteLine("旋转哈希值为 " + hash);
|
|
|
|
|
}
|
|
|
|
|
}
|