1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
//! A small crate for choosing random items from a set of weighed items.
//!
//! ### Installation/Setup
//! To import the crate into your project, simply run `cargo add choose-rand` or open your Cargo.toml and add `choose-rand = "<latest release>"`
//!
//! In any file that you want to use the crate, add `use choose_rand::prelude::*;` and `use eq_float::F64;` (the eq_float part is for when you need to `impl Probable`)
//!
//! ### Examples
//! 1. Enum
//! ```rust
//! use choose_rand::prelude::*;
//! use eq_float::F64;
//!
//! #[derive(Hash, Eq, PartialEq, Clone, Debug)]
//! enum Test {
//! foo,
//! bar,
//! buz
//! }
//!
//! impl Probable for Test {
//! fn probability(&self) -> F64 {
//! match self {
//! Test::foo => F64(0.1),
//! Test::bar => F64(0.2),
//! Test::buz => F64(0.7)
//! }
//! }
//! }
//!
//! fn main() {
//! // all probabilities must add up to 1 or else it will (sometimes) fail.
//! // it also works with BTreeSet
//! let things = HashSet::from([
//! Test::foo,
//! Test::bar,
//! Test::buz
//! ]);
//!
//! let chosen = choose_rand(&things).unwrap();
//!
//! println!("The chosen one is: {:#?}", chosen);
//! }
//! ```
//!
//! 2. Struct
//! ```rust
//! use choose_rand::prelude::*;
//! use eq_float::F64;
//!
//! #[derive(Hash, Eq, PartialEq, Clone, Debug)]
//! struct Test(F64);
//!
//! impl Probable for Test {
//! fn probability(&self) -> F64 {
//! self.0
//! }
//! }
//!
//! fn main() {
//! // all probabilities must add up to 1 or else it will (sometimes) fail.
//! // it also works with BTreeSet
//! let things = HashSet::from([
//! Test(F64(0.1)),
//! Test(F64(0.2)),
//! Test(F64(0.7))
//! ]);
//!
//! let chosen = choose_rand(&things).unwrap();
//!
//! println!("The chosen one is: {:#?}", chosen);
//! }
//! ```
/// Contains all of the important things from this crate.
/// When using the crate, you want to do `use choose_rand::prelude::*;`
use fmt;
/// Simple Error struct that has a String value for whatever reason it errored.
;