I’m trying to program a Markov chain in Swift. This is what the model training code looks like. In spite of me not being particularly good with Swift, it seems to hold up in testing, putting the right values in the chainDict
and chainValues
arrays.
func trainModel(input: [[String]]) {
var previousWord: String? = nil
for sample in input {
for word in sample {
if JRContains(list: chainDict, query: "\(word)") { // If the word is already in the chain's data...
if previousWord != nil { // If there is a word to chain this word to...
chainValues[chainDict.firstIndex(of: previousWord!)!].append("\(word)") // Chain previous word to new word
}
} else { // Otherwise...
chainDict.append("\(word)") // Add word to dictionary
chainValues.append([]) // and add a new chain pool
if previousWord != nil { // If there is a word to chain this word to...
chainValues[chainDict.firstIndex(of: previousWord!)!].append("\(word)") // Chain previous word to new word
}
}
previousWord = "\(word)"
}
previousWord = nil
}
}