【问题标题】:Function to sample N elements from array从数组中采样 N 个元素的函数
【发布时间】:2022-01-28 14:23:12
【问题描述】:

假设我们有一个数组:

let arr: [u8; 10] = [1,2,3,4,5,6,7,8,9,10];

Rust 中是否有一个函数可以从中选择 N 随机元素而不重复?相当于python的random.sample函数。

【问题讨论】:

标签: random rust std


【解决方案1】:

你可以使用choose_multiple:

use rand::prelude::*;

fn main() {
    let mut rng = rand::thread_rng();
    let arr: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    let sample: Vec<_> = arr.choose_multiple (&mut rng, 3).collect();
    println!("{:?}", sample);
}

Playground

【讨论】:

    【解决方案2】:

    您可以使用sample 获取索引样本,然后只需迭代并从原始数组中获取这些样本:

    use rand::prelude::*;
    use rand::seq::index::sample;
    
    fn main() {
        let mut rng = rand::thread_rng();
        let arr: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        let sample: Vec<u8> = sample(&mut rng, arr.len(), 3)
            .iter()
            .map(|i| arr[i])
            .collect();
    }
    
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 2012-08-03
      相关资源
      最近更新 更多