pub struct Chain<T>{ /* private fields */ }
Expand description
A struct representing a markov chain.
A markov chain has an order, which determines how many items per node are held. The chain itself is a map of vectors, which point to a map of single elements pointing at a weight.
use markov_chain::Chain;
let mut chain = Chain::new(1); // 1 is the order of the chain
// Train the chain on some vectors
chain.train(vec![1, 2, 3, 2, 1, 2, 3, 4, 3, 2, 1])
.train(vec![5, 4, 3, 2, 1]);
// Generate a sequence and print it out
let sequence = chain.generate();
println!("{:?} ", sequence);
Implementations§
Source§impl<T> Chain<T>
impl<T> Chain<T>
Sourcepub fn new(order: usize) -> Self
pub fn new(order: usize) -> Self
Initializes a new markov chain with a given order.
§Examples
use markov_chain::Chain;
let chain: Chain<u32> = Chain::new(1);
Sourcepub fn order(&self) -> usize
pub fn order(&self) -> usize
Gets the order of the markov chain. This is static from chain to chain.
Sourcepub fn train(&mut self, string: Vec<T>) -> &mut Self
pub fn train(&mut self, string: Vec<T>) -> &mut Self
Trains a sentence on a string of items.
§Examples
use markov_chain::Chain;
let mut chain = Chain::new(1);
let data = vec![10, 15, 20];
chain.train(data)
.train(vec![]);
Sourcepub fn merge(&mut self, other: &Self) -> &mut Self
pub fn merge(&mut self, other: &Self) -> &mut Self
Merges this markov chain with another.
§Examples
use markov_chain::Chain;
let mut chain1 = Chain::new(1);
let mut chain2 = chain1.clone();
chain1.train(vec![1, 2, 3]);
chain2.train(vec![2, 3, 4, 5, 6])
.merge(&chain1);
Sourcepub fn generate(&self) -> Vec<T>
pub fn generate(&self) -> Vec<T>
Generates a string of items with no maximum limit.
This is equivalent to generate_limit(-1)
.
Sourcepub fn generate_limit(&self, max: isize) -> Vec<T>
pub fn generate_limit(&self, max: isize) -> Vec<T>
Generates a string of items, based on the training, of up to N items. Specifying a maximum of -1 allows any arbitrary size of list.
Source§impl Chain<String>
String-specific implementation of the chain. Contains some special string-
specific functions.
impl Chain<String>
String-specific implementation of the chain. Contains some special string- specific functions.
Sourcepub fn train_string(&mut self, sentence: &str) -> &mut Self
pub fn train_string(&mut self, sentence: &str) -> &mut Self
Trains this chain on a single string. Strings are broken into words, which are split by whitespace and punctuation.
Sourcepub fn generate_sentence(&self) -> String
pub fn generate_sentence(&self) -> String
Generates a sentence, which are ended by “break” strings or null links.
“Break” strings are:
.
, ?
, !
, ."
, !"
, ?"
, ,"
Sourcepub fn generate_paragraph(&self, sentences: usize) -> String
pub fn generate_paragraph(&self, sentences: usize) -> String
Generates a paragraph of N sentences. Each sentence is broken off by N spaces.