7 releases (breaking)
new 0.6.0 | May 4, 2025 |
---|---|
0.5.0 | Apr 26, 2025 |
0.4.0 | Apr 23, 2025 |
0.3.0 | Mar 8, 2025 |
0.1.1 | Jan 10, 2025 |
#451 in Algorithms
382 downloads per month
100KB
1.5K
SLoC
Efficiently find items by matching weight. If your data is static, you can build the lookup structure (a complete binary tree) at compile time.
You can use any inferred numeric type for the weights. You can have any range for the lookup, by default 0.0 .. 1.0
for floats, and their respective whole spectrum MIN ..= MAX
for integers.
As a small example, let’s make red more than twice as likely as green, and that in turn five times as likely as blue.
# extern crate weight_matchers;
# use weight_matchers::{dyn_weights, weights};
# fn rand_f32() -> f32 { 0.0 }
let colours = weights! {
0.70 => "red",
0.25 => "green",
0.05 => "blue",
};
// If you have dynamic values, use this macro instead:
let frequent = 0.70;
let most = "red";
let dyn_colours = dyn_weights! {
frequent => most,
0.25 => "green",
0.05 => "blue",
};
// Any random source of the same type and range as your weights will do.
println!("I got {}", colours.get(rand_f32()));
println!("I got {}", dyn_colours.get(rand_f32()));
There’s a blog about the design choices behind this.