mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-02 03:05:24 +08:00
* feat(ko): add the complete Korean online edition * Use UTF-8 for Python CI output on Windows * Remove print-book promotion from the Korean site * fix(ko): preserve emphasis before Korean particles
67 lines
1.5 KiB
C#
67 lines
1.5 KiB
C#
/**
|
|
* File: simple_hash.cs
|
|
* Created Time: 2023-06-26
|
|
* Author: hpstory ([email protected])
|
|
*/
|
|
|
|
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;
|
|
}
|
|
|
|
/* XOR 해시 */
|
|
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("XOR 해시값: " + hash);
|
|
|
|
hash = RotHash(key);
|
|
Console.WriteLine("회전 해시값: " + hash);
|
|
}
|
|
}
|