-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
99 lines (73 loc) · 2.33 KB
/
main.cpp
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <bits/stdc++.h>
using namespace std;
int numberOfQueries,queryLength,baseStringLength;
int decimal = 256;
int primeNumber = 1117;
string baseString, query;
vector <int> hashes;
vector <string> queries;
void hashFunction(string text)
{
// generates the hashes of length 'queryLength' from the 'text'
int i;
int totalHash = 0;
int hash = 1;
for (i = 0; i < queryLength - 1; i++)
hash = (hash * decimal) % primeNumber;
for (i = 0; i < queryLength; i++)
totalHash = (decimal * totalHash + text[i]) % primeNumber;
hashes.push_back(totalHash);
for (i = 0; i <= baseStringLength - queryLength; i++) {
totalHash = (decimal * (totalHash - text[i] * hash) + text[i + queryLength]) % primeNumber;
if (totalHash < 0)
totalHash += primeNumber;
hashes.push_back(totalHash);
}
}
int doesDatasetHave(string query)
{
int i, j, localHash = 0;
// get the hash of the query
for (i = 0; i < queryLength; i++)
localHash = (decimal * localHash + query[i]) % primeNumber;
for(i = 0; i < hashes.size(); i++){
if( localHash == hashes[i] ){
// verify the match
for (j = 0; j < queryLength; j++){
if ( baseString[i+j] != query[j] )
break;
}
if (j == queryLength)
return i;
}
}
return -1;
}
int main()
{
clock_t start, end;
start = clock();
// getting the input
cin >> baseString;
cin >> numberOfQueries >> queryLength;
baseStringLength = (int)baseString.size();
for(int i = 0; i < numberOfQueries; i++){
cin >> query ;
queries.push_back(query);
}
// generate hashes for the dataset
hashFunction(baseString);
// look for a query in the dataset
for(int i=0; i<numberOfQueries; i++){
query = queries[i];
int index = doesDatasetHave(query);
if( index != -1)
cout << "The sequence: '" << query << "' found at the position: " << index+1<< "\n";
else
cout << "The sequence: '" << query << "' not found"<< "\n";
}
end = clock();
double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
cout << "Time taken by program is : " << fixed << time_taken*1000 << setprecision(0);
cout << " ms " << endl;
}