Skip to content

Commit

Permalink
Naive pattern search algorithm (#175)
Browse files Browse the repository at this point in the history
* add naive pattern search algorithm

* add naive pattern search algorithm

Co-authored-by: Laptop-Salad <email.com>
  • Loading branch information
Laptop-Salad authored Jan 3, 2023
1 parent 96a0c2e commit 49e93a1
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/strings/StringAlgo.jl
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export word_count
export hamming_distance
export rabin_karp
export LCS
export naive_pattern_search

include("detect_anagrams.jl")
include("is_palindrome.jl")
Expand All @@ -25,5 +26,6 @@ include("word_count.jl")
include("hamming_distance.jl")
include("rabin_karp.jl")
include("lcs.jl")
include("naive_pattern_search.jl")

end
44 changes: 44 additions & 0 deletions src/strings/naive_pattern_search.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""
naive_pattern_search(text, pattern)
Program to find the given pattern in the given text
# Arguments:
- 'text': A string to find the pattern
- 'pattern': A string to find in the given text
# Examples/Tests
```julia
julia> naive_pattern_search("ABCDEF", "DEF")
"DEF found at index: 3"
julia> naive_pattern_search("Hello world!", "eggs")
"No matches found"
```
# References:
(https://www.geeksforgeeks.org/naive-algorithm-for-pattern-searching/)
(https://www.tutorialspoint.com/Naive-Pattern-Searching)
# Contributors:
- [Laptop-Salad](https://github.com/Laptop-Salad)
"""

function naive_pattern_search(text, pattern)
for index in 0:(length(text)-length(pattern) + 1)
matches = 0
for character in eachindex(pattern)
if pattern[character] == text[index + character]
matches += 1

if matches == length(pattern)
return string(pattern, " found at index: ", index)
end
else
break
end
end
end
return "No matches found"
end
10 changes: 10 additions & 0 deletions test/strings.jl
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,14 @@ using TheAlgorithms.StringAlgo

@test LCS("AGCDEG", "BGFDG") == "GDG"
end

@testset "Strings: naive_pattern_search" begin
@test naive_pattern_search("ABCDEF", "DEF") == "DEF found at index: 3"

@test naive_pattern_search("Hello world!", "world") == "world found at index: 6"

@test naive_pattern_search("Hello world!", "world") == "world found at index: 6"

@test naive_pattern_search("ABCDEF", "XYZ") == "No matches found"
end
end

0 comments on commit 49e93a1

Please sign in to comment.