Created
July 24, 2018 20:56
-
-
Save tuzz/61adbeb3b3945941fde066aa30c0a9ee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A simple implementation of a Markov Model in Rust | |
#[derive(Debug, PartialEq)] | |
struct State { | |
name: &'static str, | |
} | |
struct Transition<'a> { | |
from: &'a State, | |
to: &'a State, | |
probability: f64, | |
} | |
struct MarkovModel<'a> { | |
transitions: Vec<Transition<'a>>, | |
} | |
fn main() { | |
let sunny = State { name: "sunny" }; | |
let rainy = State { name: "rainy" }; | |
let cloudy = State { name: "cloudy" }; | |
let markov_model = MarkovModel { | |
transitions: vec![ | |
Transition { from: &sunny, to: &sunny, probability: 0.6 }, | |
Transition { from: &sunny, to: &rainy, probability: 0.1 }, | |
Transition { from: &sunny, to: &cloudy, probability: 0.3 }, | |
Transition { from: &rainy, to: &rainy, probability: 0.4 }, | |
Transition { from: &rainy, to: &cloudy, probability: 0.5 }, | |
Transition { from: &cloudy, to: &cloudy, probability: 0.8 }, | |
Transition { from: &cloudy, to: &sunny, probability: 0.1 }, | |
Transition { from: &cloudy, to: &rainy, probability: 0.1 }, | |
], | |
}; | |
let events = &[&sunny, &sunny, &cloudy]; | |
let p = calculate_probability(events, &markov_model); | |
println!("sunny then sunny then cloudy: {}", p); | |
let events = &[&rainy, &sunny]; | |
let p = calculate_probability(events, &markov_model); | |
println!("rainy then sunny: {}", p); | |
} | |
fn calculate_probability(states: &[&State], model: &MarkovModel) -> f64 { | |
let mut probability = 1.0; | |
for (index, &to) in states.iter().skip(1).enumerate() { | |
let from = states[index]; | |
let transition = model.transitions.iter().find(|t| t.from == from && t.to == to); | |
probability *= transition.map_or(0.0, |t| t.probability); | |
} | |
probability | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment