#random #search #const

no-std weight_matchers

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

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

Download history 5/week @ 2025-01-15 124/week @ 2025-01-29 10/week @ 2025-02-05 7/week @ 2025-02-12 121/week @ 2025-03-05 12/week @ 2025-03-12 241/week @ 2025-04-23 141/week @ 2025-04-30

382 downloads per month

MIT/Apache

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.

No runtime deps