Skip to content

Commit f530f81

Browse files
Added string pattern matching algorithm (TheAlgorithms#238)
1 parent a019404 commit f530f81

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

String/PatternMatching.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
Pattern matching is case insensitive as
3+
the inputs are converted to lower case before the
4+
algorithm is run.
5+
6+
The algorithm will run through the entire text and
7+
return the starting index if the given pattern is
8+
available in the text
9+
*/
10+
const checkIfPatternExists = (text, pattern) => {
11+
const textLength = text.length // Store the length of the text in a variable
12+
const patternLength = pattern.length // Store the length of the pattern in a variable
13+
14+
// Iterate through the text until the textlength - patternlength index
15+
for (let i = 0; i <= textLength - patternLength; i++) {
16+
// For each character in the text check if the subsequent character
17+
// are matching the given pattern; if not break from the condition
18+
for (let j = 0; j < textLength; j++) {
19+
if (text[i + j] !== pattern[j]) break
20+
21+
// For each iteration of j check if the value of
22+
// j + 1 is equal to the length of the pattern
23+
if (j + 1 === patternLength) {
24+
console.log(`Given pattern is found at index ${i}`)
25+
}
26+
}
27+
}
28+
}
29+
30+
const main = () => {
31+
const text = 'AABAACAADAABAAAABAA'
32+
const pattern = 'AABA'
33+
checkIfPatternExists(text.toLowerCase(), pattern.toLowerCase())
34+
}
35+
36+
main()

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy