std.random
Category | Functions |
---|---|
Uniform sampling | uniform uniform01 uniformDistribution |
Element sampling | choice dice |
Range sampling | randomCover randomSample |
Default Random Engines | rndGen Random unpredictableSeed |
Linear Congruential Engines | MinstdRand MinstdRand0 LinearCongruentialEngine |
Mersenne Twister Engines | Mt19937 Mt19937_64 MersenneTwisterEngine |
Xorshift Engines | Xorshift XorshiftEngine Xorshift32 Xorshift64 Xorshift96 Xorshift128 Xorshift160 Xorshift192 |
Shuffle | partialShuffle randomShuffle |
Traits | isSeedable isUniformRNG |
Source std/random.d
Credits The entire random number library architecture is derived from the excellent C++0X random number facility proposed by Jens Maurer and contributed to by researchers at the Fermi laboratory (excluding Xorshift).
import std.algorithm.comparison : among, equal; import std.range : iota; // seed a random generator with a constant auto rnd = Random(42); // Generate a uniformly-distributed integer in the range [0, 14] // If no random generator is passed, the global `rndGen` would be used auto i = uniform(0, 15, rnd); assert(i >= 0 && i < 15); // Generate a uniformly-distributed real in the range [0, 100) auto r = uniform(0.0L, 100.0L, rnd); assert(r >= 0 && r < 100); // Sample from a custom type enum Fruit { apple, mango, pear } auto f = rnd.uniform!Fruit; with(Fruit) assert(f.among(apple, mango, pear)); // Generate a 32-bit random number auto u = uniform!uint(rnd); static assert(is(typeof(u) == uint)); // Generate a random number in the range in the range [0, 1) auto u2 = uniform01(rnd); assert(u2 >= 0 && u2 < 1); // Select an element randomly auto el = 10.iota.choice(rnd); assert(0 <= el && el < 10); // Throw a dice with custom proportions // 0: 20%, 1: 10%, 2: 60% auto val = rnd.dice(0.2, 0.1, 0.6); assert(0 <= val && val <= 2); auto rnd2 = MinstdRand0(42); // Select a random subsample from a range assert(10.iota.randomSample(3, rnd2).equal([7, 8, 9])); // Cover all elements in an array in random order version (D_LP64) // https://issues.dlang.org/show_bug.cgi?id=15147 assert(10.iota.randomCover(rnd2).equal([7, 4, 2, 0, 1, 6, 8, 3, 9, 5])); else assert(10.iota.randomCover(rnd2).equal([4, 8, 7, 3, 5, 9, 2, 6, 0, 1])); // Shuffle an array version (D_LP64) // https://issues.dlang.org/show_bug.cgi?id=15147 assert([0, 1, 2, 4, 5].randomShuffle(rnd2).equal([2, 0, 4, 5, 1])); else assert([0, 1, 2, 4, 5].randomShuffle(rnd2).equal([4, 2, 5, 0, 1]));
- enum bool
isUniformRNG
(Rng, ElementType);
enum boolisUniformRNG
(Rng); - Test if Rng is a random-number generator. The overload taking a ElementType also makes sure that the Rng generates values of that type.A random-number generator has at least the following features:
- it's an InputRange
- it has a 'bool isUniformRandom' field readable in CTFE
Examples:struct NoRng { @property uint front() {return 0;} @property bool empty() {return false;} void popFront() {} } static assert(!isUniformRNG!(NoRng)); struct validRng { @property uint front() {return 0;} @property bool empty() {return false;} void popFront() {} enum isUniformRandom = true; } static assert(isUniformRNG!(validRng, uint)); static assert(isUniformRNG!(validRng));
- enum bool
isSeedable
(Rng, SeedType);
enum boolisSeedable
(Rng); - Test if Rng is seedable. The overload taking a SeedType also makes sure that the Rng can be seeded with SeedType.A seedable random-number generator has the following additional features:
- it has a 'seed(ElementType)' function
Examples:struct validRng { @property uint front() {return 0;} @property bool empty() {return false;} void popFront() {} enum isUniformRandom = true; } static assert(!isSeedable!(validRng, uint)); static assert(!isSeedable!(validRng)); struct seedRng { @property uint front() {return 0;} @property bool empty() {return false;} void popFront() {} void seed(uint val){} enum isUniformRandom = true; } static assert(isSeedable!(seedRng, uint)); static assert(!isSeedable!(seedRng, ulong)); static assert(isSeedable!(seedRng));
- struct
LinearCongruentialEngine
(UIntType, UIntType a, UIntType c, UIntType m) if (isUnsigned!UIntType); - Linear Congruential generator. When m = 0, no modulus is used.Examples:Declare your own linear congruential engine
alias CPP11LCG = LinearCongruentialEngine!(uint, 48271, 0, 2_147_483_647); // seed with a constant auto rnd = CPP11LCG(42); auto n = rnd.front; // same for each run writeln(n); // 2027382
Examples:Declare your own linear congruential engine// glibc's LCG alias GLibcLCG = LinearCongruentialEngine!(uint, 1103515245, 12345, 2_147_483_648); // Seed with an unpredictable value auto rnd = GLibcLCG(unpredictableSeed); auto n = rnd.front; // different across runs
Examples:Declare your own linear congruential engine// Visual C++'s LCG alias MSVCLCG = LinearCongruentialEngine!(uint, 214013, 2531011, 0); // seed with a constant auto rnd = MSVCLCG(1); auto n = rnd.front; // same for each run writeln(n); // 2745024
- enum bool
isUniformRandom
; - Mark this as a Rng
- enum bool
hasFixedRange
; - Does this generator have a fixed range? (true).
- enum UIntType
min
; - Lowest generated value (1 if c == 0, 0 otherwise).
- enum UIntType
max
; - Highest generated value (modulus - 1).
- enum UIntType
multiplier
;
enum UIntTypeincrement
;
enum UIntTypemodulus
; - The parameters of this distribution. The random number is x = (x * multipler + increment) % modulus.
- pure nothrow @nogc @safe this(UIntType
x0
); - Constructs a LinearCongruentialEngine generator seeded with
x0
. - pure nothrow @nogc @safe void
seed
(UIntTypex0
= 1); - (Re)seeds the generator.
- pure nothrow @nogc @safe void
popFront
(); - Advances the random sequence.
- const pure nothrow @nogc @property @safe UIntType
front
(); - Returns the current number in the random sequence.
- const pure nothrow @nogc @property @safe typeof(this)
save
(); - enum bool
empty
; - Always false (random generators are infinite ranges).
- alias
MinstdRand0
= LinearCongruentialEngine!(uint, 16807u, 0u, 2147483647u).LinearCongruentialEngine;
aliasMinstdRand
= LinearCongruentialEngine!(uint, 48271u, 0u, 2147483647u).LinearCongruentialEngine; - Define LinearCongruentialEngine generators with well-chosen parameters.
MinstdRand0
implements Park and Miller's "minimal standard" generator that uses 16807 for the multiplier.MinstdRand
implements a variant that has slightly better spectral behavior by using the multiplier 48271. Both generators are rather simplistic.Examples:// seed with a constant auto rnd0 = MinstdRand0(1); auto n = rnd0.front; // same for each run writeln(n); // 16807 // Seed with an unpredictable value rnd0.seed(unpredictableSeed); n = rnd0.front; // different across runs
- struct
MersenneTwisterEngine
(UIntType, size_t w, size_t n, size_t m, size_t r, UIntType a, size_t u, UIntType d, size_t s, UIntType b, size_t t, UIntType c, size_t l, UIntType f) if (isUnsigned!UIntType); - The Mersenne Twister generator.Examples:
// seed with a constant Mt19937 gen; auto n = gen.front; // same for each run writeln(n); // 3499211612 // Seed with an unpredictable value gen.seed(unpredictableSeed); n = gen.front; // different across runs
- enum bool
isUniformRandom
; - Mark this as a Rng
- enum size_t
wordSize
;
enum size_tstateSize
;
enum size_tshiftSize
;
enum size_tmaskBits
;
enum UIntTypexorMask
;
enum size_ttemperingU
;
enum UIntTypetemperingD
;
enum size_ttemperingS
;
enum UIntTypetemperingB
;
enum size_ttemperingT
;
enum UIntTypetemperingC
;
enum size_ttemperingL
;
enum UIntTypeinitializationMultiplier
; - Parameters for the generator.
- enum UIntType
min
; - Smallest generated value (0).
- enum UIntType
max
; - Largest generated value.
- enum UIntType
defaultSeed
; - The default seed value.
- pure nothrow @nogc @safe this(UIntType
value
); - Constructs a MersenneTwisterEngine object.
- pure nothrow @nogc @safe void
seed
()(UIntTypevalue
= defaultSeed); - Seeds a MersenneTwisterEngine object.
Note This seed function gives 2^w starting points (the lowest w bits of the value provided will be used). To allow the RNG to be started in any one of its internal states use the seed overload taking an InputRange.
- void
seed
(T)(Trange
)
if (isInputRange!T && is(immutable(ElementType!T) == immutable(UIntType))); - Seeds a MersenneTwisterEngine object using an InputRange.Throws:Exception if the InputRange didn't provide enough elements to seed the generator. The number of elements required is the 'n' template parameter of the MersenneTwisterEngine struct.
- pure nothrow @nogc @safe void
popFront
(); - Advances the generator.
- const pure nothrow @nogc @property @safe UIntType
front
(); - Returns the current random value.
- const pure nothrow @nogc @property @safe typeof(this)
save
(); - enum bool
empty
; - Always false.
- alias
Mt19937
= MersenneTwisterEngine!(uint, 32LU, 624LU, 397LU, 31LU, 2567483615u, 11LU, 4294967295u, 7LU, 2636928640u, 15LU, 4022730752u, 18LU, 1812433253u).MersenneTwisterEngine; - A MersenneTwisterEngine instantiated with the parameters of the original engine MT19937, generating uniformly-distributed 32-bit numbers with a period of 2 to the power of 19937. Recommended for random number generation unless memory is severely restricted, in which case a LinearCongruentialEngine would be the generator of choice.Examples:
// seed with a constant Mt19937 gen; auto n = gen.front; // same for each run writeln(n); // 3499211612 // Seed with an unpredictable value gen.seed(unpredictableSeed); n = gen.front; // different across runs
- alias
Mt19937_64
= MersenneTwisterEngine!(ulong, 64LU, 312LU, 156LU, 31LU, 13043109905998158313LU, 29LU, 6148914691236517205LU, 17LU, 8202884508482404352LU, 37LU, 18444473444759240704LU, 43LU, 6364136223846793005LU).MersenneTwisterEngine; - A MersenneTwisterEngine instantiated with the parameters of the original engine MT19937-64, generating uniformly-distributed 64-bit numbers with a period of 2 to the power of 19937.Examples:
// Seed with a constant auto gen = Mt19937_64(12345); auto n = gen.front; // same for each run writeln(n); // 6597103971274460346 // Seed with an unpredictable value gen.seed(unpredictableSeed!ulong); n = gen.front; // different across runs
- struct
XorshiftEngine
(UIntType, uint nbits, int sa, int sb, int sc) if (isUnsigned!UIntType && !(sa > 0 && (sb > 0) && (sc > 0)));
templateXorshiftEngine
(UIntType, int bits, int a, int b, int c) if (isUnsigned!UIntType && (a > 0) && (b > 0) && (c > 0)) - Xorshift generator. Implemented according to Xorshift RNGs (Marsaglia, 2003) when the size is small. For larger sizes the generator uses Sebastino Vigna's optimization of using an index to avoid needing to rotate the internal array.Period is 2 ^^ nbits - 1 except for a legacy 192-bit uint version (see note below).Parameters:
UIntType Word size of this xorshift generator and the return type of opCall. nbits The number of bits of state of this generator. This must be a positive multiple of the size in bits of UIntType. If nbits is large this struct may occupy slightly more memory than this so it can use a circular counter instead of shifting the entire array. sa The direction and magnitude of the 1st shift. Positive means left, negative means right. sb The direction and magnitude of the 2nd shift. Positive means left, negative means right. sc The direction and magnitude of the 3rd shift. Positive means left, negative means right. Note For historical compatibility when nbits == 192 and UIntType is uint a legacy hybrid PRNG is used consisting of a 160-bit xorshift combined with a 32-bit counter. This combined generator has period equal to the least common multiple of 2^^160 - 1 and 2^^32.
Previous versions ofXorshiftEngine
did not provide any mechanism to specify the directions of the shifts, taking each shift as an unsigned magnitude. For backwards compatibility, because three shifts in the same direction cannot result in a full-period XorshiftEngine, when all three of sa, sb, sc, are positive XorshiftEngine` treats them as unsigned magnitudes and uses shift directions to match the old behavior ofXorshiftEngine
. Not every set of shifts results in a full-period xorshift generator. The template does not currently at compile-time perform a full check for maximum period but in a future version might reject parameters resulting in shorter periods.Examples:alias Xorshift96 = XorshiftEngine!(uint, 96, 10, 5, 26); auto rnd = Xorshift96(42); auto num = rnd.front; // same for each run writeln(num); // 2704588748
- enum bool
isUniformRandom
; - Mark this as a Rng
- enum auto
empty
; - Always false (random generators are infinite ranges).
- enum UIntType
min
; - Smallest generated value.
- enum UIntType
max
; - Largest generated value.
- pure nothrow @nogc @safe this()(UIntType
x0
); - Constructs a XorshiftEngine generator seeded with x0.Parameters:
UIntType x0
value used to deterministically initialize internal state - pure nothrow @nogc @safe void
seed
()(UIntTypex0
); - (Re)seeds the generator.Parameters:
UIntType x0
value used to deterministically initialize internal state - const pure nothrow @nogc @property @safe UIntType
front
(); - Returns the current number in the random sequence.
- pure nothrow @nogc @safe void
popFront
(); - Advances the random sequence.
- const pure nothrow @nogc @property @safe typeof(this)
save
(); - Captures a range state.
- alias
Xorshift32
= XorshiftEngine!(uint, 32u, 13, -17, 15).XorshiftEngine;
aliasXorshift64
= XorshiftEngine!(uint, 64u, 10, -13, -10).XorshiftEngine;
aliasXorshift96
= XorshiftEngine!(uint, 96u, 10, -5, -26).XorshiftEngine;
aliasXorshift128
= XorshiftEngine!(uint, 128u, 11, -8, -19).XorshiftEngine;
aliasXorshift160
= XorshiftEngine!(uint, 160u, 2, -1, -4).XorshiftEngine;
aliasXorshift192
= XorshiftEngine!(uint, 192u, -2, 1, 4).XorshiftEngine;
aliasXorshift
= XorshiftEngine!(uint, 128u, 11, -8, -19).XorshiftEngine; - Define XorshiftEngine generators with well-chosen parameters. See each bits examples of "Xorshift RNGs".
Xorshift
is a Xorshift128's alias because 128bits implementation is mostly used.Examples:// Seed with a constant auto rnd = Xorshift(1); auto num = rnd.front; // same for each run writeln(num); // 1405313047 // Seed with an unpredictable value rnd.seed(unpredictableSeed); num = rnd.front; // different across rnd
- nothrow @nogc @property @trusted uint
unpredictableSeed
();
templateunpredictableSeed
(UIntType) if (isUnsigned!UIntType) - A "good" seed for initializing random number engines. Initializing with unpredictableSeed makes engines generate different random number sequences every run.Returns:A single unsigned integer seed value, different on each successive call
Note In general periodically 'reseeding' a PRNG does not improve its quality and in some cases may harm it. For an extreme example the Mersenne Twister has 2 ^^ 19937 - 1 distinct states but after seed(uint) is called it can only be in one of 2 ^^ 32 distinct states regardless of how excellent the source of entropy is.
Examples:auto rnd = Random(unpredictableSeed); auto n = rnd.front; static assert(is(typeof(n) == uint));
- alias
Random
= MersenneTwisterEngine!(uint, 32LU, 624LU, 397LU, 31LU, 2567483615u, 11LU, 4294967295u, 7LU, 2636928640u, 15LU, 4022730752u, 18LU, 1812433253u).MersenneTwisterEngine; - The "default", "favorite", "suggested" random number generator type on the current platform. It is an alias for one of the previously-defined generators. You may want to use it if (1) you need to generate some nice random numbers, and (2) you don't care for the minutiae of the method being used.
- nothrow @nogc @property ref @safe Random
rndGen
(); - Global random number generator used by various functions in this module whenever no generator is specified. It is allocated per-thread and initialized to an unpredictable value for each thread.Returns:A singleton instance of the default random number generatorExamples:
import std.algorithm.iteration : sum; import std.range : take; auto rnd = rndGen; assert(rnd.take(3).sum > 0);
- auto
uniform
(string boundaries = "[)", T1, T2)(T1a
, T2b
)
if (!is(CommonType!(T1, T2) == void));
autouniform
(string boundaries = "[)", T1, T2, UniformRandomNumberGenerator)(T1a
, T2b
, ref UniformRandomNumberGeneratorurng
)
if (isFloatingPoint!(CommonType!(T1, T2)) && isUniformRNG!UniformRandomNumberGenerator); - Generates a number between
a
andb
. The boundaries parameter controls the shape of the interval (open vs. closed on either side). Valid values for boundaries are "[]", "(]", "[)", and "()". The default interval is closed to the left and open to the right. The version that does not takeurng
uses the default generator rndGen.Parameters:T1 a
lower bound of the uniform distribution T2 b
upper bound of the uniform distribution UniformRandomNumberGenerator urng
(optional) random number generator to use; if not specified, defaults to rndGen Returns:A single random variate drawn from the uniform distribution betweena
andb
, whose type is the common type of these parametersExamples:auto rnd = Random(unpredictableSeed); // Generate an integer in [0, 1023] auto a = uniform(0, 1024, rnd); assert(0 <= a && a < 1024); // Generate a float in [0, 1) auto b = uniform(0.0f, 1.0f, rnd); assert(0 <= b && b < 1); // Generate a float in [0, 1] b = uniform!"[]"(0.0f, 1.0f, rnd); assert(0 <= b && b <= 1); // Generate a float in (0, 1) b = uniform!"()"(0.0f, 1.0f, rnd); assert(0 < b && b < 1);
Examples:Create an array of random numbers using range functions and UFCSimport std.array : array; import std.range : generate, takeExactly; int[] arr = generate!(() => uniform(0, 100)).takeExactly(10).array; writeln(arr.length); // 10 assert(arr[0] >= 0 && arr[0] < 100);
- auto
uniform
(T, UniformRandomNumberGenerator)(ref UniformRandomNumberGeneratorurng
)
if (!is(T == enum) && (isIntegral!T || isSomeChar!T) && isUniformRNG!UniformRandomNumberGenerator);
autouniform
(T)()
if (!is(T == enum) && (isIntegral!T || isSomeChar!T));
autouniform
(E, UniformRandomNumberGenerator)(ref UniformRandomNumberGeneratorurng
)
if (is(E == enum) && isUniformRNG!UniformRandomNumberGenerator);
autouniform
(E)()
if (is(E == enum)); - Generates a uniformly-distributed number in the range [T.min, T.max] for any integral or character type T. If no random number generator is passed, uses the default rndGen.If an enum is used as type, the random variate is drawn with equal probability from any of the possible values of the enum E.Parameters:
UniformRandomNumberGenerator urng
(optional) random number generator to use; if not specified, defaults to rndGen Returns:Random variate drawn from the uniform distribution across all possible values of the integral, character or enum type T.Examples:auto rnd = MinstdRand0(42); writeln(rnd.uniform!ubyte); // 102 writeln(rnd.uniform!ulong); // 4838462006927449017 enum Fruit { apple, mango, pear } version (D_LP64) // https://issues.dlang.org/show_bug.cgi?id=15147 writeln(rnd.uniform!Fruit); // Fruit.mango
- T
uniform01
(T = double)()
if (isFloatingPoint!T);
Tuniform01
(T = double, UniformRNG)(ref UniformRNGrng
)
if (isFloatingPoint!T && isUniformRNG!UniformRNG); - Generates a uniformly-distributed floating point number of type T in the range [0, 1). If no random number generator is specified, the default RNG rndGen will be used as the source of randomness.
uniform01
offers a faster generation of random variates than the equivalent uniform!"[)"(0.0, 1.0) and so may be preferred for some applications.Parameters:UniformRNG rng
(optional) random number generator to use; if not specified, defaults to rndGen Returns:Floating-point random variate of type T drawn from the uniform distribution across the half-open interval [0, 1).Examples:import std.math.operations : feqrel; auto rnd = MinstdRand0(42); // Generate random numbers in the range in the range [0, 1) auto u1 = uniform01(rnd); assert(u1 >= 0 && u1 < 1); auto u2 = rnd.uniform01!float; assert(u2 >= 0 && u2 < 1); // Confirm that the random values with the initial seed 42 are 0.000328707 and 0.524587 assert(u1.feqrel(0.000328707) > 20); assert(u2.feqrel(0.524587) > 20);
- F[]
uniformDistribution
(F = double)(size_tn
, F[]useThis
= null)
if (isFloatingPoint!F); - Generates a uniform probability distribution of size
n
, i.e., an array of sizen
of positive numbers of type F that sum to 1. IfuseThis
is provided, it is used as storage.Examples:import std.algorithm.iteration : reduce; import std.math.operations : isClose; auto a = uniformDistribution(5); writeln(a.length); // 5 assert(isClose(reduce!"a + b"(a), 1)); a = uniformDistribution(10, a); writeln(a.length); // 10 assert(isClose(reduce!"a + b"(a), 1));
- ref auto
choice
(Range, RandomGen = Random)(Rangerange
, ref RandomGenurng
)
if (isRandomAccessRange!Range && hasLength!Range && isUniformRNG!RandomGen);
ref autochoice
(Range)(Rangerange
);
ref autochoice
(Range, RandomGen = Random)(ref Rangerange
, ref RandomGenurng
)
if (isRandomAccessRange!Range && hasLength!Range && isUniformRNG!RandomGen);
ref autochoice
(Range)(ref Rangerange
); - Returns a random, uniformly chosen, element e from the supplied Range range. If no random number generator is passed, the default rndGen is used.Parameters:
Range range
a random access range that has the length property defined RandomGen urng
(optional) random number generator to use; if not specified, defaults to rndGen Returns:A single random element drawn from therange
. If it can, it will return a ref to the range element, otherwise it will return a copy.Examples:auto rnd = MinstdRand0(42); auto elem = [1, 2, 3, 4, 5].choice(rnd); version (D_LP64) // https://issues.dlang.org/show_bug.cgi?id=15147 writeln(elem); // 3
- Range
randomShuffle
(Range, RandomGen)(Ranger
, ref RandomGengen
)
if (isRandomAccessRange!Range && isUniformRNG!RandomGen);
RangerandomShuffle
(Range)(Ranger
)
if (isRandomAccessRange!Range); - Shuffles elements of
r
usinggen
as a shuffler.r
must be a random-access range with length. If no RNG is specified, rndGen will be used.Parameters:Range r
random-access range whose elements are to be shuffled RandomGen gen
(optional) random number generator to use; if not specified, defaults to rndGen Returns:The shuffled random-access range.Examples:auto rnd = MinstdRand0(42); auto arr = [1, 2, 3, 4, 5].randomShuffle(rnd); version (D_LP64) // https://issues.dlang.org/show_bug.cgi?id=15147 writeln(arr); // [3, 5, 2, 4, 1]
- Range
partialShuffle
(Range, RandomGen)(Ranger
, in size_tn
, ref RandomGengen
)
if (isRandomAccessRange!Range && isUniformRNG!RandomGen);
RangepartialShuffle
(Range)(Ranger
, in size_tn
)
if (isRandomAccessRange!Range); - Partially shuffles the elements of
r
such that upon returning r[0 .. n] is a random subset ofr
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 afterpartialShuffle
returns will not be independent of their order beforepartialShuffle
was called.r
must be a random-access range with length.n
must be less than or equal tor
.length. If no RNG is specified, rndGen will be used.Parameters:Range r
random-access range whose elements are to be shuffled size_t n
number of elements of r
to shuffle (counting from the beginning); must be less thanr
.lengthRandomGen gen
(optional) random number generator to use; if not specified, defaults to rndGen Returns:The shuffled random-access range.Examples: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
- size_t
dice
(Rng, Num)(ref Rngrnd
, Num[]proportions
...)
if (isNumeric!Num && isForwardRange!Rng);
size_tdice
(R, Range)(ref Rrnd
, Rangeproportions
)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range);
size_tdice
(Range)(Rangeproportions
)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range);
size_tdice
(Num)(Num[]proportions
...)
if (isNumeric!Num); - Get a random index into a list of weights corresponding to each indexSimilar to rolling a die with relative probabilities stored in
proportions
. Returns the index inproportions
that was chosen.Note Usually, dice are 'fair', meaning that each side has equal probability to come up, in which case 1 + uniform(0, 6) can simply be used. In future Phobos versions, this function might get renamed to something like weightedChoice to avoid confusion.
Parameters:Rng rnd
(optional) random number generator to use; if not specified, defaults to rndGen Num[] proportions
forward range or list of individual values whose elements correspond to the probabilities with which to choose the corresponding index value Returns:Random variate drawn from the index values [0, ...proportions
.length - 1], with the probability of getting an individual index value i being proportional toproportions
[i].Examples:auto d6 = 1 + dice(1, 1, 1, 1, 1, 1); // fair dice roll auto d6b = 1 + dice(2, 1, 1, 1, 1, 1); // double the chance to roll '1' auto x = dice(0.5, 0.5); // x is 0 or 1 in equal proportions auto y = dice(50, 50); // y is 0 or 1 in equal proportions auto z = dice(70, 20, 10); // z is 0 70% of the time, 1 20% of the time, // and 2 10% of the time
Examples:auto rnd = MinstdRand0(42); auto z = rnd.dice(70, 20, 10); writeln(z); // 0 z = rnd.dice(30, 20, 40, 10); writeln(z); // 2
- struct
RandomCover
(Range, UniformRNG = void) if (isRandomAccessRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void)));
autorandomCover
(Range, UniformRNG)(Ranger
, auto ref UniformRNGrng
)
if (isRandomAccessRange!Range && isUniformRNG!UniformRNG);
autorandomCover
(Range)(Ranger
)
if (isRandomAccessRange!Range); - Covers a given range
r
in a random manner, i.e. goes through each element ofr
once and only once, just in a random order.r
must be a random-access range with length.If no random number generator is passed torandomCover
, the thread-global RNG rndGen will be used internally.Parameters:Range r
random-access range to cover UniformRNG rng
(optional) random number generator to use; if not specified, defaults to rndGen Returns:Range whose elements consist of the elements ofr
, in random order. Will be a forward range if bothr
andrng
are forward ranges, an input range otherwise.Examples:import std.algorithm.comparison : equal; import std.range : iota; auto rnd = MinstdRand0(42); version (D_LP64) // https://issues.dlang.org/show_bug.cgi?id=15147 assert(10.iota.randomCover(rnd).equal([7, 4, 2, 0, 1, 6, 8, 3, 9, 5]));
- struct
RandomSample
(Range, UniformRNG = void) if (isInputRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void)));
autorandomSample
(Range)(Ranger
, size_tn
, size_ttotal
)
if (isInputRange!Range);
autorandomSample
(Range)(Ranger
, size_tn
)
if (isInputRange!Range && hasLength!Range);
autorandomSample
(Range, UniformRNG)(Ranger
, size_tn
, size_ttotal
, auto ref UniformRNGrng
)
if (isInputRange!Range && isUniformRNG!UniformRNG);
autorandomSample
(Range, UniformRNG)(Ranger
, size_tn
, auto ref UniformRNGrng
)
if (isInputRange!Range && hasLength!Range && isUniformRNG!UniformRNG); - Selects a random subsample out of
r
, containing exactlyn
elements. The order of elements is the same as in the original range. The total length ofr
must be known. Iftotal
is passed in, the total number of sample is considered to be total. Otherwise,RandomSample
usesr
.length.Parameters:Range r
range to sample from size_t n
number of elements to include in the sample; must be less than or equal to the total number of elements in r
and/or the parametertotal
(if provided)size_t total
(semi-optional) number of elements of r
from which to select the sample (counting from the beginning); must be less than or equal to the total number of elements inr
itself. May be omitted ifr
has the .length property and the sample is to be drawn from all elements ofr
.UniformRNG rng
(optional) random number generator to use; if not specified, defaults to rndGen Returns:Range whose elements consist of a randomly selected subset of the elements ofr
, in the same order as these elements appear inr
itself. Will be a forward range if bothr
andrng
are forward ranges, an input range otherwise.RandomSample
implements Jeffrey Scott Vitter's Algorithm D (see Vitter 1984, 1987), which selects a sample of sizen
in O(n) steps and requiring O(n) random variates, regardless of the size of the data being sampled. The exception to this is if traversing k elements on the input range is itself an O(k) operation (e.g. when sampling lines from an input file), in which case the sampling calculation will inevitably be of O(total). RandomSample will throw an exception iftotal
is verifiably less than the total number of elements available in the input, or if n > total. If no random number generator is passed torandomSample
, the thread-global RNG rndGen will be used internally.Examples:import std.algorithm.comparison : equal; import std.range : iota; auto rnd = MinstdRand0(42); assert(10.iota.randomSample(3, rnd).equal([7, 8, 9]));
- const @property bool
empty
();
@property ref autofront
();
voidpopFront
();
const @property typeof(this)save
();
const @property size_tlength
(); - Range primitives.
- @property size_t
index
(); - Returns the index of the visited record.