1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

rand: add rand.element and prng.element functions with unit test (#16068)

This commit is contained in:
Subhomoy Haldar
2022-10-14 04:54:02 +01:00
committed by GitHub
parent f7f0e0b5dc
commit 09e23e3ed6
2 changed files with 33 additions and 0 deletions

View File

@ -383,6 +383,15 @@ pub fn (mut rng PRNG) choose<T>(array []T, k int) ?[]T {
return results
}
// element returns a random element from the given array.
// Note that all the positions in the array have an equal chance of being selected. This means that if the array has repeating elements, then the probability of selecting a particular element is not uniform.
pub fn (mut rng PRNG) element<T>(array []T) ?T {
if array.len == 0 {
return error('Cannot choose an element from an empty array.')
}
return array[rng.intn(array.len)!]
}
// sample samples k elements from 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 (mut rng PRNG) sample<T>(array []T, k int) []T {
@ -607,6 +616,12 @@ pub fn choose<T>(array []T, k int) ?[]T {
return default_rng.choose<T>(array, k)
}
// element returns a random element from the given array.
// Note that all the positions in the array have an equal chance of being selected. This means that if the array has repeating elements, then the probability of selecting a particular element is not uniform.
pub fn element<T>(array []T) ?T {
return default_rng.element<T>(array)
}
// sample samples k elements from 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<T>(array []T, k int) []T {