2021-01-18 13:20:06 +01:00
// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved.
2020-06-01 21:13:56 +02:00
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
2020-06-09 15:06:07 +02:00
module util
2020-06-01 21:13:56 +02:00
2021-02-04 13:56:53 +01:00
import rand
2021-01-29 10:57:30 +01:00
2021-02-04 13:56:53 +01:00
// sample_nr returns a sample of the array without replacement. This means the indices cannot repeat and it restricts the sample size to be less than or equal to the size of the given array. Note that if the array has repeating elements, then the sample may have repeats as well.
pub fn sample_nr < T > ( array [ ] T , k int ) [ ] T {
n := array . len
if k > n {
panic ( ' C a n n o t s a m p l e $ k e l e m e n t s w i t h o u t r e p l a c e m e n t f r o m a $ n - e l e m e n t a r r a y . ' )
}
mut results := [ ] T { len : k }
mut indices := [ ] int { len : n }
// Initialize with all indices
for i , mut v in indices {
v = i
}
2021-02-05 19:24:38 +01:00
shuffle ( mut indices , k )
2021-02-04 13:56:53 +01:00
for i in 0 .. k {
results [ i ] = array [ indices [ i ] ]
}
return results
}
// sample_r returns a sample of the array with replacement. This means the elements can repeat and the size of the sample may exceed the size of the array
pub fn sample_r < T > ( array [ ] T , k int ) [ ] T {
n := array . len
mut results := [ ] T { len : k }
for i in 0 .. k {
results [ i ] = array [ rand . intn ( n ) ]
}
return results
}
2021-02-05 19:24:38 +01:00
// shuffle randomizes the first `n` items of an array in place (all if `n` is 0)
[ direct_array_access ]
pub fn shuffle < T > ( mut a [ ] T , n int ) {
if n < 0 || n > a . len {
panic ( " a r g u m e n t ' n ' m u s t b e i n r a n g e [ 0 , a . l e n ] " )
}
cnt := if n == 0 { a . len - 1 } else { n }
for i in 0 .. cnt {
x := rand . int_in_range ( i , a . len )
// swap
a_i := a [ i ]
a [ i ] = a [ x ]
a [ x ] = a_i
}
}