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

rand: add pub fn shuffle<T>(mut a []T) { function + tests (#13811)

This commit is contained in:
Nick Treleaven
2022-03-23 13:31:26 +00:00
committed by GitHub
parent 35cd8112a5
commit 2e963e36ac
2 changed files with 69 additions and 0 deletions

View File

@ -467,3 +467,20 @@ pub fn hex(len int) string {
pub fn ascii(len int) string {
return string_from_set(rand.ascii_chars, len)
}
// shuffle randomly permutates the elements in `a`.
pub fn shuffle<T>(mut a []T) {
len := a.len
for i in 0 .. len {
si := i + intn(len - i) or { len }
a[si], a[i] = a[i], a[si]
}
}
// shuffle_clone returns a random permutation of the elements in `a`.
// The permutation is done on a fresh clone of `a`, so `a` remains unchanged.
pub fn shuffle_clone<T>(a []T) []T {
mut res := a.clone()
shuffle(mut res)
return res
}