#random #search #const

no-std weight_matchers

Efficiently find items by matching weight. You can build the lookup structure at compile time.

5 releases (3 breaking)

new 0.4.0 Apr 23, 2025
0.3.0 Mar 8, 2025
0.2.0 Jan 29, 2025
0.1.1 Jan 10, 2025
0.1.0 Jan 8, 2025

#721 in Algorithms

41 downloads per month

MIT/Apache

42KB
468 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.

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 for unsigned 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.

No runtime deps