Skip to content

Commit 6db6185

Browse files
author
Your Name
committed
Bitap Algorithm in C++ added
1 parent 05a9735 commit 6db6185

1 file changed

Lines changed: 111 additions & 0 deletions

File tree

Bitap Algorithm/Bitap.cpp

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
#include <string>
2+
3+
#include <map>
4+
5+
#include <iostream>
6+
7+
8+
9+
using namespace std;
10+
11+
int bitap_search(string text, string pattern)
12+
13+
{
14+
15+
int m = pattern.length();
16+
17+
long pattern_mask[256];
18+
19+
/** Initialize the bit array R **/
20+
21+
long R = ~1;
22+
23+
if (m == 0)
24+
25+
return -1;
26+
27+
if (m > 63)
28+
29+
{
30+
31+
cout<<"Pattern is too long!";
32+
33+
return -1;
34+
35+
}
36+
37+
38+
39+
/** Initialize the pattern bitmasks **/
40+
41+
for (int i = 0; i <= 255; ++i)
42+
43+
pattern_mask[i] = ~0;
44+
45+
for (int i = 0; i < m; ++i)
46+
47+
pattern_mask[pattern[i]] &= ~(1L << i);
48+
49+
for (int i = 0; i < text.length(); ++i)
50+
51+
{
52+
53+
/** Update the bit array **/
54+
55+
R |= pattern_mask[text[i]];
56+
57+
R <<= 1;
58+
59+
if ((R & (1L << m)) == 0)
60+
61+
62+
63+
return i - m + 1;
64+
65+
}
66+
67+
return -1;
68+
69+
}
70+
71+
void findPattern(string t, string p)
72+
73+
{
74+
75+
int pos = bitap_search(t, p);
76+
77+
if (pos == -1)
78+
79+
cout << "\nNo Match\n";
80+
81+
else
82+
83+
cout << "\nPattern found at position : " << pos;
84+
85+
}
86+
87+
88+
89+
int main(int argc, char **argv)
90+
91+
{
92+
93+
94+
95+
cout << "Bitap Algorithm Test\n";
96+
97+
cout << "Enter Text\n";
98+
99+
string text;
100+
101+
cin >> text;
102+
103+
cout << "Enter Pattern\n";
104+
105+
string pattern;
106+
107+
cin >> pattern;
108+
109+
findPattern(text, pattern);
110+
111+
}

0 commit comments

Comments
 (0)