-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash.js
More file actions
60 lines (47 loc) · 1.7 KB
/
hash.js
File metadata and controls
60 lines (47 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const fs = require("fs");
function hash(s) {
let hashValue = 0;
for (let i = 0; i < s.length; i++) {
hashValue += s.charCodeAt(i);
}
return hashValue;
}
function hashSubstringSearch(subs, text) {
let index = [];
let count = 0;
const textLength = text.length;
const subsLength = subs.length;
const subsHash = hash(subs);
let collisions = 0; // Счетчик коллизий
for (let i = 0; i <= textLength - subsLength; i++) {
const subText = text.substring(i, i + subsLength);
const subTextHash = hash(subText);
if (subTextHash === subsHash && subText !== subs) {
collisions++; // Увеличиваем счетчик коллизий при совпадении хэшей, но разных строках
}
if (subTextHash === subsHash) {
let j = 0;
while (j < subsLength && subText[j] === subs[j]) {
j++;
}
if (j === subsLength) {
index.push(i);
count++;
}
}
}
return { count, index, collisions };
}
function main() {
const subsFile = process.argv[2];
const textFile = process.argv[3];
const subs = fs.readFileSync(subsFile, "utf8");
const text = fs.readFileSync(textFile, "utf8");
console.time("Hash Substring Search");
const { count, index, collisions } = hashSubstringSearch(subs, text);
console.timeEnd("Hash Substring Search");
console.log("Total occurrences:", count);
console.log("Indexes of first 10 occurrences:", index.slice(0, 10));
console.log("Collisions:", collisions);
}
main();