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

rand: move functions from rand.util to the main module (#13840)

This commit is contained in:
Subhomoy Haldar
2022-03-27 20:08:59 +05:30
committed by GitHub
parent 875ad1f6ea
commit f75ce9dd82
5 changed files with 142 additions and 131 deletions

View File

@ -326,7 +326,6 @@ fn test_shuffle() {
a := get_n_random_ints(seed, 10)
arrays << a
}
//
mut digits := []map[int]int{len: 10}
for digit in 0 .. 10 {
digits[digit] = {}
@ -337,7 +336,7 @@ fn test_shuffle() {
for mut a in arrays {
o := a.clone()
for _ in 0 .. 100 {
rand.shuffle(mut a)
rand.shuffle(mut a) or { panic('shuffle failed') }
assert *a != o
for idx in 0 .. 10 {
digits[idx][a[idx]]++
@ -355,12 +354,25 @@ fn test_shuffle() {
}
}
fn test_shuffle_partial() ? {
mut a := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
mut b := a.clone()
rand.shuffle(mut a, start: 4) ?
assert a[..4] == b[..4]
a = b.clone()
rand.shuffle(mut a, start: 3, end: 7) ?
assert a[..3] == b[..3]
assert a[7..] == b[7..]
}
fn test_shuffle_clone() {
original := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
mut a := original.clone()
mut results := [][]int{}
for _ in 0 .. 10 {
results << rand.shuffle_clone(a)
results << rand.shuffle_clone(a) or { panic('shuffle failed') }
}
assert original == a
for idx in 1 .. 10 {
@ -369,3 +381,33 @@ fn test_shuffle_clone() {
assert results[idx] != original
}
}
fn test_choose() ? {
lengths := [1, 3, 4, 5, 6, 7]
a := ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
for length in lengths {
b := rand.choose(a, length) ?
assert b.len == length
for element in b {
assert element in a
// make sure every element occurs once
mut count := 0
for e in b {
if e == element {
count++
}
}
assert count == 1
}
}
}
fn test_sample() {
k := 20
a := ['heads', 'tails']
b := rand.sample(a, k)
assert b.len == k
for element in b {
assert element in a
}
}