mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 12:16:29 +08:00
f62256bee1
* Modify method name to PascalCase(array and linked list) * Modify method name to PascalCase(backtracking) * Modify method name to PascalCase(computational complexity) * Modify method name to PascalCase(divide and conquer) * Modify method name to PascalCase(dynamic programming) * Modify method name to PascalCase(graph) * Modify method name to PascalCase(greedy) * Modify method name to PascalCase(hashing) * Modify method name to PascalCase(heap) * Modify method name to PascalCase(searching) * Modify method name to PascalCase(sorting) * Modify method name to PascalCase(stack and queue) * Modify method name to PascalCase(tree) * local check
66 lines
1.6 KiB
C#
66 lines
1.6 KiB
C#
/**
|
|
* File: simple_hash.cs
|
|
* Created Time: 2023-06-26
|
|
* Author: hpstory (hpstory1024@163.com)
|
|
*/
|
|
|
|
namespace hello_algo.chapter_hashing;
|
|
|
|
public class simple_hash {
|
|
/* 加法哈希 */
|
|
public static int AddHash(string key) {
|
|
long hash = 0;
|
|
const int MODULUS = 1000000007;
|
|
foreach (char c in key) {
|
|
hash = (hash + c) % MODULUS;
|
|
}
|
|
return (int)hash;
|
|
}
|
|
|
|
/* 乘法哈希 */
|
|
public static int MulHash(string key) {
|
|
long hash = 0;
|
|
const int MODULUS = 1000000007;
|
|
foreach (char c in key) {
|
|
hash = (31 * hash + c) % MODULUS;
|
|
}
|
|
return (int)hash;
|
|
}
|
|
|
|
/* 异或哈希 */
|
|
public static int XorHash(string key) {
|
|
int hash = 0;
|
|
const int MODULUS = 1000000007;
|
|
foreach (char c in key) {
|
|
hash ^= c;
|
|
}
|
|
return hash & MODULUS;
|
|
}
|
|
|
|
/* 旋转哈希 */
|
|
public static 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);
|
|
}
|
|
}
|