diff --git a/src/strings/StringAlgo.jl b/src/strings/StringAlgo.jl index 71dcf70f..7e86eb95 100644 --- a/src/strings/StringAlgo.jl +++ b/src/strings/StringAlgo.jl @@ -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") @@ -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 diff --git a/src/strings/naive_pattern_search.jl b/src/strings/naive_pattern_search.jl new file mode 100644 index 00000000..58fba4c1 --- /dev/null +++ b/src/strings/naive_pattern_search.jl @@ -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 diff --git a/test/strings.jl b/test/strings.jl index b7d6e178..7c93262b 100644 --- a/test/strings.jl +++ b/test/strings.jl @@ -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