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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
//! # Random Pick
//! Pick an element from a slice randomly by given weights.
//!
//! ## Example
//!
//! ```
//! extern crate random_pick;
//!
//! enum Prize {
//!     Legendary,
//!     Rare,
//!     Enchanted,
//!     Common,
//! }
//!
//! let prize_list = [Prize::Legendary, Prize::Rare, Prize::Enchanted, Prize::Common]; // available prizes
//!
//! let slice = &prize_list;
//! let weights = [1, 5, 15, 30]; // a scale of chance of picking each kind of prize
//!
//! let n = 1000000;
//! let mut counter = [0usize; 4];
//!
//! for _ in 0..n {
//!     let picked_item = random_pick::pick_from_slice(slice, &weights).unwrap();
//!
//!     match picked_item {
//!         Prize::Legendary=>{
//!             counter[0] += 1;
//!            }
//!         Prize::Rare=>{
//!             counter[1] += 1;
//!         }
//!         Prize::Enchanted=>{
//!             counter[2] += 1;
//!         }
//!         Prize::Common=>{
//!             counter[3] += 1;
//!         }
//!     }
//! }
//!
//! println!("{}", counter[0]); // Should be close to 20000
//! println!("{}", counter[1]); // Should be close to 100000
//! println!("{}", counter[2]); // Should be close to 300000
//! println!("{}", counter[3]); // Should be close to 600000
//! ```
//!
//! The length of the slice is usually an integral multiple (larger than zero) of that of weights.

extern crate rand;

use rand::Rng;

const MAX_NUMBER: usize = usize::max_value();

/// Pick an element from a slice randomly by given weights.
pub fn pick_from_slice<'a, T>(slice: &'a [T], weights: &'a [usize]) -> Option<&'a T> {
    let weights_len = weights.len();

    let index = gen_usize_with_weights(weights_len, weights)?;

    Some(&slice[index])
}

/// Get a usize value by given weights.
pub fn gen_usize_with_weights(high: usize, weights: &[usize]) -> Option<usize> {
    let weights_len = weights.len();

    if weights_len == 0 {
        return None;
    }

    let mut weights_sum = 0f64;
    let mut max_weight = 0;

    for &w in weights {
        weights_sum += w as f64;
        if w > max_weight {
            max_weight = w;
        }
    }

    if max_weight == 0 {
        return None;
    }

    let index_scale = (high as f64) / (weights_len as f64);

    let weights_scale = (MAX_NUMBER as f64) / weights_sum;

    let rnd = random_integer(0, MAX_NUMBER) as f64;

    let mut temp = 0f64;

    for (i, &w) in weights.iter().enumerate() {
        temp += (w as f64) * weights_scale;
        if temp > rnd {
            let index = ((i as f64) * index_scale) as usize;

            return Some(random_integer(index, ((((i + 1) as f64) * index_scale) - 1f64) as usize));
        }
    }

    None
}

#[cfg(target_pointer_width = "64")]
fn random_integer(a: usize, b: usize) -> usize {
    let rnd: u64 = rand::thread_rng().gen();

    let rnd = rnd as u128;
    let a = a as u128;
    let b = b as u128;

    (if b >= a {
        (rnd % (b - a + 1)) + a
    } else {
        (rnd % (a - b + 1)) + b
    }) as usize
}

#[cfg(target_pointer_width = "32")]
fn random_integer(a: usize, b: usize) -> usize {
    if a > b {
        let a = a as u64;
        let b = b as u64;

        rand::thread_rng().gen_range(b, a + 1) as usize
    } else if a == b {
        a
    } else {
        let a = a as u64;
        let b = b as u64;

        rand::thread_rng().gen_range(a, b + 1) as usize
    }
}

#[cfg(target_pointer_width = "16")]
fn random_integer(a: usize, b: usize) -> usize {
    if a > b {
        let a = a as u32;
        let b = b as u32;

        rand::thread_rng().gen_range(b, a + 1) as usize
    } else if a == b {
        a
    } else {
        let a = a as u32;
        let b = b as u32;

        rand::thread_rng().gen_range(a, b + 1) as usize
    }
}

#[cfg(target_pointer_width = "8")]
fn random_integer(a: usize, b: usize) -> usize {
    if a > b {
        let a = a as u16;
        let b = b as u16;

        rand::thread_rng().gen_range(b, a + 1) as usize
    } else if a == b {
        a
    } else {
        let a = a as u16;
        let b = b as u16;

        rand::thread_rng().gen_range(a, b + 1) as usize
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_random_integer() {
        let mut result = Vec::new();

        let n = 1000000;

        let nn = n / 10;

        for _ in 0..n {
            result.push(random_integer(0, 9));
        }

        let mut counter = [0usize; 10];

        for i in result {
            counter[i as usize] += 1;
        }

        let mut errs = [0f64; 10];

        for (i, &c) in counter.iter().enumerate() {
            errs[i] = (((nn as isize) - (c as isize)) as f64).abs() / (nn as f64);
        }

        for &err in errs.iter() {
            assert!(err < 0.02);
        }
    }

    #[test]
    fn test_gen_index_with_weights_1() {
        let mut result = Vec::new();

        let n = 1000000;
        let weights = [5, 10];

        for _ in 0..n {
            result.push(gen_usize_with_weights(2, &weights).unwrap());
        }

        let mut counter = [0usize; 2];

        for i in result {
            counter[i] += 1;
        }

        let a = (counter[0] as f64) * (weights[1] as f64) / (weights[0] as f64);

        let b = counter[1] as f64;

        let err = (b - a).abs() / b;

        assert!(err < 0.02);
    }

    #[test]
    fn test_gen_index_with_weights_2() {
        let mut result = Vec::new();

        let n = 1000000;
        let weights = [5, 10, 15, 20, 25];

        for _ in 0..n {
            result.push(gen_usize_with_weights(5, &weights).unwrap());
        }

        let mut counter = [0usize; 5];

        for i in result {
            counter[i] += 1;
        }

        for i in 0..5 {
            for j in i..5 {
                let a = (counter[i] as f64) * (weights[j] as f64) / (weights[i] as f64);

                let b = counter[j] as f64;

                let err = (b - a).abs() / b;

                assert!(err < 0.02);
            }
        }
    }

    #[test]
    fn test_gen_index_with_weights_3() {
        let mut result = Vec::new();

        let n = 1000000;
        let weights = [5, 10];

        for _ in 0..n {
            result.push(gen_usize_with_weights(10, &weights).unwrap());
        }

        let mut counter = [0usize; 2];

        for i in result {
            if i < 5 {
                counter[0] += 1;
            } else {
                counter[1] += 1;
            }
        }

        let a = (counter[0] as f64) * (weights[1] as f64) / (weights[0] as f64);

        let b = counter[1] as f64;

        let err = (b - a).abs() / b;

        assert!(err < 0.02);
    }

    #[test]
    fn test_gen_index_with_weights_4() {
        let mut result = Vec::new();

        let n = 1000000;
        let weights = [5, 10, 15, 20, 25];

        for _ in 0..n {
            result.push(gen_usize_with_weights(10, &weights).unwrap());
        }

        let mut counter = [0usize; 5];

        for i in result {
            if i < 2 {
                counter[0] += 1;
            } else if i < 4 {
                counter[1] += 1;
            } else if i < 6 {
                counter[2] += 1;
            } else if i < 8 {
                counter[3] += 1;
            } else {
                counter[4] += 1;
            }
        }

        for i in 0..5 {
            for j in i..5 {
                let a = (counter[i] as f64) * (weights[j] as f64) / (weights[i] as f64);

                let b = counter[j] as f64;

                let err = (b - a).abs() / b;

                assert!(err < 0.02);
            }
        }
    }

    #[test]
    fn test_pick_from_slice() {
        enum Prize {
            Legendary,
            Rare,
            Enchanted,
            Common,
        }

        let prize_list = [Prize::Legendary, Prize::Rare, Prize::Enchanted, Prize::Common];

        let weights = [1, 5, 15, 30];


        let n = 1000000;
        let mut result = Vec::new();

        for _ in 0..n {
            let picked_item = pick_from_slice(&prize_list, &weights).unwrap();

            result.push(picked_item);
        }

        let mut counter = [0usize; 4];

        for ref picked_item in result {
            match picked_item {
                Prize::Legendary => {
                    counter[0] += 1;
                }
                Prize::Rare => {
                    counter[1] += 1;
                }
                Prize::Enchanted => {
                    counter[2] += 1;
                }
                Prize::Common => {
                    counter[3] += 1;
                }
            }
        }

        for i in 0..4 {
            for j in i..4 {
                let a = (counter[i] as f64) * (weights[j] as f64) / (weights[i] as f64);

                let b = counter[j] as f64;

                let err = (b - a).abs() / b;

                assert!(err < 0.02);
            }
        }
    }
}