3 unstable releases
0.2.0 | Jan 29, 2025 |
---|---|
0.1.1 | Jan 10, 2025 |
0.1.0 | Jan 8, 2025 |
#1703 in Algorithms
138 downloads per month
37KB
365 lines
Efficiently find items by matching weight. If your data is static, you can build the lookup structure (a complete binary tree) at compile time, by making it const
.
You can use any numeric type for the weights, by default f32
. You can have any range for the lookup, by default 0.0 .. 1.0
for floats, and their respective whole spectrum 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::*;
# fn rand_f32() -> f32 { 0.0 }
let colours = const {
weights! {
0.70 => "red",
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()))
There’s a blog about the design choices behind this.