mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-02 03:05:24 +08:00
* Retranslate the complete Japanese online edition from Chinese * Fit Japanese homepage labels and localize heading permalinks * Point Japanese contribution instructions to the Japanese preview * Replace locale conditionals with multilingual UI tables
67 lines
1.6 KiB
C#
67 lines
1.6 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;
|
|
}
|
|
|
|
/* 排他的論理和ハッシュ */
|
|
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);
|
|
}
|
|
}
|