View source code
Display the source code in std/random.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

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.length] 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.length. If no RNG is specified, rndGen will be used.

Parameters

NameDescription
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.length
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 (D_LP64) // https://issues.dlang.org/show_bug.cgi?id=15147
assert(arr == [2, 1, 3, 4, 5, 6]); // 1<->2

arr = arr.dup.partialShuffle(2, rnd);
version (D_LP64) // https://issues.dlang.org/show_bug.cgi?id=15147
assert(arr == [1, 4, 3, 2, 5, 6]); // 1<->2, 2<->4

arr = arr.dup.partialShuffle(3, rnd);
version (D_LP64) // https://issues.dlang.org/show_bug.cgi?id=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)

License

Boost License 1.0.