-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbf.js
More file actions
41 lines (31 loc) · 1.02 KB
/
bf.js
File metadata and controls
41 lines (31 loc) · 1.02 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
const fs = require("fs");
function bruteForceSubstringSearch(subs, text) {
let index = [];
let count = 0;
const maxIndexesToDisplay = 10;
const textLength = text.length;
const subsLength = subs.length;
for (let i = 0; i <= textLength - subsLength; i++) {
let j = 0;
while (j < subsLength && text[i + j] === subs[j]) {
j++;
}
if (j === subsLength) {
index.push(i);
count++;
}
}
return { count, index };
}
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("Brute Force Search");
const { count, index } = bruteForceSubstringSearch(subs, text);
console.timeEnd("Brute Force Search");
console.log("Total occurrences:", count);
console.log("Indexes of first 10 occurrences:", index.slice(0, 10));
}
main();