You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.2 KiB
61 lines
1.2 KiB
/**
|
|
* 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);
|