MarkovUnchained is a simple, generic Swift implementation for working with Markov chains. See http://setosa.io/ev/markov-chains/ for a nice description of Markov chains (with c00l visuals). With MarkovUnchained, you can build a Markov chain with a set of states, and predict the next state for any given existing state.
To run the example project, clone the repo, and run pod install
from the Example directory first.
The project uses George Orwell's 1984 text as a corpus, and generates 100 words from a given initial word.
MarkovUnchained is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'MarkovUnchained'
The Markov chain can be built with any Hashable
type. The .build(from: _)
function and provided callback runs on a background queue.
let corpus = readSomeTextFile()
let chain = MarkovChain<String>()
chain.build(from: corpus) {
// on complete
}
Each retrieval of a predicted state can set how the selection should be made via the following enum:
public enum SelectionType {
case random // purely random as to which state is chosen
case weighted // states with higher weights are likely to be chosen
case mixed // default, either random or weighted is used to choose next state
}
let nextState = chain.nextState(for: "me", selectionType: .random)
let states = "This is a short sentence but now it's long".split(separator: " ")
let predictedStates = chain.nextStates(for: states, selectionType: .weighted)
let predictedStates = chain.nextStates(100, for: "lmao", using: .mixed)
MarkovUnchained is available under the MIT license. See the LICENSE file for more info.