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:
@ -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
|
||||
}
|
||||
|
Reference in New Issue
Block a user