add a rand.shuffle_clone/1 version + test for it
parent
caf1b690b7
commit
d2846b2f3c
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue