rand: add `shuffle` function for array
parent
35cd8112a5
commit
bedcc44f34
|
|
@ -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]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue