mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-14 01:38:18 +08:00
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
67 lines
1.5 KiB
C#
67 lines
1.5 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 {
|
|
/* Additive hash */
|
|
int AddHash(string key) {
|
|
long hash = 0;
|
|
const int MODULUS = 1000000007;
|
|
foreach (char c in key) {
|
|
hash = (hash + c) % MODULUS;
|
|
}
|
|
return (int)hash;
|
|
}
|
|
|
|
/* Multiplicative 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;
|
|
}
|
|
|
|
/* XOR hash */
|
|
int XorHash(string key) {
|
|
int hash = 0;
|
|
const int MODULUS = 1000000007;
|
|
foreach (char c in key) {
|
|
hash ^= c;
|
|
}
|
|
return hash & MODULUS;
|
|
}
|
|
|
|
/* Rotating hash */
|
|
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("Additive hash value: " + hash);
|
|
|
|
hash = MulHash(key);
|
|
Console.WriteLine("Multiplicative hash value: " + hash);
|
|
|
|
hash = XorHash(key);
|
|
Console.WriteLine("XOR hash value: " + hash);
|
|
|
|
hash = RotHash(key);
|
|
Console.WriteLine("Rotating hash value: " + hash);
|
|
}
|
|
}
|