Skip to content

Instantly share code, notes, and snippets.

@lizixroy
Created July 28, 2016 03:02
Show Gist options
  • Save lizixroy/e4a36ae21c101ebb70df7be30f33186f to your computer and use it in GitHub Desktop.
Save lizixroy/e4a36ae21c101ebb70df7be30f33186f to your computer and use it in GitHub Desktop.
CKYParser
class CKYParser {
func parse(words words: [String], language: Language) -> [[[ParseTreeNode]]] {
let wordCount = words.count
var table = [[[ParseTreeNode]]]()
for _ in 0...words.count - 1 {
let array = [[ParseTreeNode]](count: wordCount, repeatedValue: [ParseTreeNode]())
table.append(array)
}
// populate lexicon. assuming all the words are in our lexicon
for index in 0...words.count - 1 {
let word = words[index]
let nonTerminals = language.recognize([word])!
for nonTerminal in nonTerminals {
table[index][index].append(ParseTreeNode(nonTerminal: nonTerminal, leftNode: nil, rightNode: nil))
}
}
for col in 0...wordCount - 1 {
for row in (0...wordCount - 1).reverse() {
var t = row
while t + 1 <= col {
let arr1 = table[row][t]
let arr2 = table[t + 1][col]
if arr1.count == 0 || arr2.count == 0 {
t += 1
continue
}
if let nonTerminals = language.recognize(arr1: arr1, arr2: arr2) {
for nonTerminal in nonTerminals {
table[row][col].append(nonTerminal)
}
}
t += 1
}
}
}
return table
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment