Function std.random.partialShuffle
Partially shuffles the elements of r
such that upon returning r[0 .. n]
is a random subset of r
and is randomly ordered. r[n .. r
will contain the elements not in r[0 .. n]
. These will be in an undefined
order, but will not be random in the sense that their order after
partialShuffle
returns will not be independent of their order before
partialShuffle
was called.
Range partialShuffle(Range, RandomGen)
(
Range r,
in size_t n,
ref RandomGen gen
)
if (isRandomAccessRange!Range && isUniformRNG!RandomGen);
Range partialShuffle(Range)
(
Range r,
in size_t n
)
if (isRandomAccessRange!Range);
r
must be a random-access range with length. n
must be less than
or equal to r
. If no RNG is specified, rndGen
will be used.
Parameters
Name | Description |
---|---|
r | random-access range whose elements are to be shuffled |
n | number of elements of r to shuffle (counting from the beginning);
must be less than r |
gen | (optional) random number generator to use; if not
specified, defaults to rndGen |
Returns
The shuffled random-access range.
Example
auto rnd = MinstdRand0(42);
auto arr = [1, 2, 3, 4, 5, 6];
arr = arr .dup .partialShuffle(1, rnd);
version(X86_64) // Issue 15147
assert(arr == [2, 1, 3, 4, 5, 6]); // 1<->2
arr = arr .dup .partialShuffle(2, rnd);
version(X86_64) // Issue 15147
assert(arr == [1, 4, 3, 2, 5, 6]); // 1<->2, 2<->4
arr = arr .dup .partialShuffle(3, rnd);
version(X86_64) // Issue 15147
assert(arr == [5, 4, 6, 2, 1, 3]); // 1<->5, 2<->4, 3<->6
Authors
Andrei Alexandrescu Masahiro Nakagawa (Xorshift random generator) Joseph Rushton Wakeling (Algorithm D for random sampling) Ilya Yaroshenko (Mersenne Twister implementation, adapted from mir-random)