add a rand.shuffle_clone/1 version + test for it

pull/13811/head
Delyan Angelov 2022-03-23 12:55:21 +02:00
parent caf1b690b7
commit d2846b2f3c
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
2 changed files with 23 additions and 0 deletions

View File

@ -476,3 +476,11 @@ pub fn shuffle<T>(mut a []T) {
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
}

View File

@ -354,3 +354,18 @@ fn test_shuffle() {
// eprintln('digits[$digit]: ${digits[digit]}')
}
}
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)
}
assert original == a
for idx in 1 .. 10 {
assert results[idx].len == 10
assert results[idx] != results[0]
assert results[idx] != original
}
}