Rust 在结构中存储加权选项
我为代码转储提前道歉。我尽可能地把它修剪了 可以在不丢失我问题的上下文的情况下(在下面的粗体中) 我有一个结构Rust 在结构中存储加权选项,rust,Rust,我为代码转储提前道歉。我尽可能地把它修剪了 可以在不丢失我问题的上下文的情况下(在下面的粗体中) 我有一个结构 use std::rand; use std::rand::Rng; use std::rand::distributions::{Weighted, WeightedChoice, Sample, IndependentSample}; struct MarkovChain { state: uint, weights: Vec<Vec<uint>
use std::rand;
use std::rand::Rng;
use std::rand::distributions::{Weighted, WeightedChoice, Sample, IndependentSample};
struct MarkovChain {
state: uint,
weights: Vec<Vec<uint>>,
}
现在我实施:
以下是中的全部内容。对于任何经历过似曾相识的人来说,这个问题与我的问题不同,我的问题是关于返回加权选择。你可以很容易地在
new()
中计算你的行
,但我不知道你如何对加权选择
进行同样的计算。问题是,您无法向编译器证明它借用的引用是由MarkovChain
结构安全拥有的……不幸的是,即使将行
s移到new()
中也很棘手:WeightedChoice::new(&'a mut[Weighted])
修改其参数,因此,为同一行创建多个wc
s会扭曲概率分布。请参阅此相关问题:
impl MarkovChain {
fn new(weights: Vec<Vec<uint>>, initial_state: uint) -> MarkovChain {
let states = weights.len();
assert!(states > 0);
assert!(initial_state < states);
assert!(weights.iter().all(|row| row.len() == states));
MarkovChain {
state: initial_state,
weights: weights,
}
}
}
impl Sample<uint> for MarkovChain {
fn sample<R: Rng>(&mut self, rng: &mut R) -> uint {
// I'd like to put the following part in MarkovChain::new
// instead, but I can't figure out how to store the
// WeightedChoice inside the MarkovChain struct.
//BEGIN
let mut row = self.weights[self.state]
.iter()
.enumerate()
.map(|(i, &wt)| Weighted { item: i, weight: wt })
.collect::<Vec<Weighted<uint>>>();
let wc = WeightedChoice::new(row.as_mut_slice());
//END
self.state = wc.ind_sample(rng);
self.state
}
}
fn main() {
// Create the 3-state Markov chain illustrated at
// https://en.wikipedia.org/w/index.php?title=Markov_chain&oldid=626307401#Example
let mut mc = MarkovChain::new(vec![vec![900, 75, 25],
vec![150, 800, 50],
vec![250, 250, 500]], 0);
// Expect around 62.5% 0s, 31.25% 1s, and 6.25% 2s after many iterations.
let rng = &mut rand::task_rng();
let mut stats = vec![0u, 0, 0];
for _ in range(0u, 10000) {
*stats.get_mut(mc.sample(rng)) += 1;
}
println!("Expect approximately [6250, 3125, 625]:");
println!("{}", stats);
}