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);
|