Files
Yudong Jin 8e38c61455 Bug fixes and improvements (#1732)
* Bug fixes

* Sync zh and zh-hant versions.

* "入列列" -> "入佇列"

* Fix hello_algo_mindmap.png
2025-04-10 19:21:52 +08:00

61 lines
1.2 KiB
JavaScript

/**
* File: simple_hash.js
* Created Time: 2023-08-06
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 加法雜湊 */
function addHash(key) {
let hash = 0;
const MODULUS = 1000000007;
for (const c of key) {
hash = (hash + c.charCodeAt(0)) % MODULUS;
}
return hash;
}
/* 乘法雜湊 */
function mulHash(key) {
let hash = 0;
const MODULUS = 1000000007;
for (const c of key) {
hash = (31 * hash + c.charCodeAt(0)) % MODULUS;
}
return hash;
}
/* 互斥或雜湊 */
function xorHash(key) {
let hash = 0;
const MODULUS = 1000000007;
for (const c of key) {
hash ^= c.charCodeAt(0);
}
return hash % MODULUS;
}
/* 旋轉雜湊 */
function rotHash(key) {
let hash = 0;
const MODULUS = 1000000007;
for (const c of key) {
hash = ((hash << 4) ^ (hash >> 28) ^ c.charCodeAt(0)) % MODULUS;
}
return hash;
}
/* Driver Code */
const key = 'Hello 演算法';
let hash = addHash(key);
console.log('加法雜湊值為 ' + hash);
hash = mulHash(key);
console.log('乘法雜湊值為 ' + hash);
hash = xorHash(key);
console.log('互斥或雜湊值為 ' + hash);
hash = rotHash(key);
console.log('旋轉雜湊值為 ' + hash);