Crates.io | choose-rand |
lib.rs | choose-rand |
version | 0.2.0 |
source | src |
created_at | 2023-03-29 02:10:45.034904 |
updated_at | 2023-09-13 17:14:01.831 |
description | A small crate for choosing random items from a set of weighted items. |
homepage | https://github.com/HyperCodec/choose-rand |
repository | https://github.com/HyperCodec/choose-rand |
max_upload_size | |
id | 823603 |
size | 13,286 |
A small crate for choosing random items from a set of weighed items.
To import the crate into your project, simply run cargo add choose-rand
In any file that you want to use the crate, add use choose_rand::prelude::*;
.
use choose_rand::prelude::*;
#[derive(Debug, Clone)]
struct Foo {
prob: f32,
}
impl Probable for Foo {
fn probability(&self) -> f32 {
self.prob
}
}
fn main() -> Result<()> {
let v: Vec<_> = choose_rand::helper::refcellify(
vec![Foo { prob: 0.25 }, Foo { prob: 0.5 }, Foo { prob: 0.1 }, Foo { prob: 0.05 }]
).collect();
let mut rng = rand::thread_rng();
dbg!(v.choose_rand(&mut rng));
Ok(())
}
with features = ["eq_float"]
for sets:
use choose_rand::prelude::*;
use eq_float::F32;
use std::collections::HashSet;
#[derive(Clone, Debug, Hash)]
struct Foo {
prob: F32,
}
impl Foo {
fn new(prob: f32) -> Self {
Self { prob: F32(prob) }
}
}
impl Probable for Foo {
fn probablity(&self) -> F32 {
self.prob
}
}
fn main() -> Result<()> {
let v: HashSet<_> = choose_rand::helper::refcellify(
vec![Foo::new(0.25), Foo::new(0.5), Foo::new(0.1), Foo::new(0.05)]
).collect();
let mut rng = rand::thread_rng();
dbg!(v.choose_rand(&mut rng));
Ok(())
}
This library is licensed under the MIT
license.