Skip to content

Commit 4740a3f

Browse files
committed
Hash - linear probe
1 parent 5ef1951 commit 4740a3f

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

hash/linear_probing.ts

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
const hashTableSize = 13;
2+
3+
const hashTable: (string | number)[] = Array(hashTableSize).fill(null);
4+
5+
function hashFun(str: string) {
6+
let result = 0;
7+
for (let i = 0; i < str.length; i++) {
8+
result += str.charCodeAt(i);
9+
}
10+
11+
result %= hashTableSize;
12+
return Math.floor(result);
13+
}
14+
15+
function addToHashTable(item: { key: string; value: string | number }) {
16+
const hashAddr = hashFun(item.key);
17+
18+
let i = hashAddr;
19+
while (hashTable[i] !== null) {
20+
if (hashTable[i] === item.value) {
21+
throw new Error("Duplicated item");
22+
}
23+
24+
i = (i + 1) % hashTableSize;
25+
if (i === hashAddr) {
26+
throw new Error("Hash table full");
27+
}
28+
}
29+
30+
hashTable[i] = item.value;
31+
}
32+
33+
const a = addToHashTable({ key: "hi", value: 1 });
34+
35+
function hashSearch(item: { key: string; value: number }) {
36+
const hashAddr = hashFun(item.key);
37+
38+
let i = hashAddr;
39+
while (hashTable[i]) {
40+
if (hashTable[i] === item.value) {
41+
return hashTable[i];
42+
}
43+
44+
i = (i + 1) % hashTableSize;
45+
46+
if (hashAddr === i) {
47+
return console.log("value not exist");
48+
}
49+
}
50+
51+
return console.log("Value not exists");
52+
}
53+
54+
function printHashTable() {
55+
console.log("==================");
56+
for (let i = 0; i < hashTable.length; i++) {
57+
console.log(`[${i}] ${hashTable[i]}`);
58+
}
59+
}
60+
61+
function main() {
62+
const tokens = ["do", "for", "if", "case", "else", "return", "function"];
63+
64+
for (let i = 0; i < tokens.length; i++) {
65+
const item = { key: tokens[i], value: tokens[i] };
66+
addToHashTable(item);
67+
}
68+
69+
printHashTable();
70+
}
71+
72+
main();

0 commit comments

Comments
 (0)