rand: add `shuffle` function for array

pull/13811/head
Nick Treleaven 2022-03-23 09:32:47 +00:00 committed by Delyan Angelov
parent 35cd8112a5
commit bedcc44f34
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
2 changed files with 16 additions and 0 deletions

View File

@ -467,3 +467,12 @@ 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]
}
}

View File

@ -317,3 +317,10 @@ fn test_new_global_rng() {
rand.set_rng(old)
}
fn test_shuffle() {
mut a := get_n_random_ints(seeds[0], 10)
rand.shuffle(mut a)
assert a == [4, 0, 8, 0, 1, 2, 1, 1, 0, 9]
}