Skip to content

feat: Implement Raita Algorithm for string matching #651

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
feat: Implement Raita Algorithm for string matching
- Added `_raita` function to `pydatastructs/strings/algorithms.py`.
- Updated `find` function to support the `raita` algorithm.
- Added test cases for the Raita algorithm in `tests/test_strings.py`.
- Ensured compatibility with existing string matching algorithms.
  • Loading branch information
asmit27rai committed Mar 17, 2025
commit c390b29d2948ad64e10afa6dc9f6ef5646fce69a
45 changes: 45 additions & 0 deletions pydatastructs/strings/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,48 @@ def _z_function(text, query):
positions.append(pos)

return positions

def _raita(text, query):
"""
Implements the Raita algorithm for string matching.

Parameters
==========
text: str
The text in which the pattern is to be searched.
query: str
The pattern to be searched in the text.

Returns
=======
DynamicOneDimensionalArray
An array of starting positions of the pattern in the text.
"""
positions = DynamicOneDimensionalArray(int, 0)
n, m = len(text), len(query)

if m == 0 or n == 0 or m > n:
return positions

bad_char = {}
for i in range(m):
bad_char[query[i]] = i

middle_char = query[m // 2]

i = 0
while i <= n - m:
if query[0] == text[i] and query[-1] == text[i + m - 1] and middle_char == text[i + m // 2]:
j = 1
while j < m - 1 and query[j] == text[i + j]:
j += 1
if j == m - 1:
positions.append(i)

if i + m < n:
shift = bad_char.get(text[i + m], -1)
i += max(1, m - 1 - shift)
else:
break

return positions
3 changes: 3 additions & 0 deletions pydatastructs/strings/tests/test_algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ def test_bm():
def test_zf():
_test_common_string_matching('z_function')

def test_raita():
_test_common_string_matching('raita')

def _test_common_string_matching(algorithm):
true_text_pattern_dictionary = {
"Knuth-Morris-Pratt": "-Morris-",
Expand Down
Loading