Skip to content

Instantly share code, notes, and snippets.

@prasadpamidi
Last active November 5, 2015 19:15
Show Gist options
  • Save prasadpamidi/f5b9c5c6d39e514b0727 to your computer and use it in GitHub Desktop.
Save prasadpamidi/f5b9c5c6d39e514b0727 to your computer and use it in GitHub Desktop.
Pattern Matching algorithm implemented in Swift
//Famous pattern matching algorithm implementation in Swift
func FindMatch(text: [Character], pattern: [Character]) -> [Int] {
let t = count(text)
let p = count(pattern)
var i = 0
var j = 0
var matchedIdxs: [Int] = []
for i = 0; i <= t-p; i++ {
for j = 0; j < p; j++ {
if text[i+j] != pattern[j] {
break
}
}
if j == p {
println("Match found at \(i)")
matchedIdxs.append(i)
}
}
return matchedIdxs
}
let pattern = "Victor"
let text = "My name is Victor. Full name is Joseph Victor Jr. I can be called as jrVictor"
//Returns indexes for start postion of patterns found in the text
FindMatch(Array(text),Array(pattern))
[11, 39, 71]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment