1 unstable release
new 0.1.0 | Jan 8, 2025 |
---|
#2021 in Algorithms
36KB
354 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.