argmin/core/math/random_vec.rs
1// Copyright 2018-2020 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use crate::core::math::ArgminRandom;
9use rand::distributions::uniform::SampleUniform;
10use rand::Rng;
11
12impl<T> ArgminRandom for Vec<T>
13where
14 T: SampleUniform + std::cmp::PartialOrd + Clone,
15{
16 fn rand_from_range(min: &Self, max: &Self) -> Vec<T> {
17 assert!(!min.is_empty());
18 assert_eq!(min.len(), max.len());
19
20 let mut rng = rand::thread_rng();
21
22 min.iter()
23 .zip(max.iter())
24 .map(|(a, b)| {
25 // Do not require a < b:
26
27 if a == b {
28 a.clone()
29 } else if a < b {
30 rng.gen_range(a, b)
31 } else {
32 rng.gen_range(b, a)
33 }
34 })
35 .collect()
36 }
37}