Working with randomSample
Ali Çehreli
acehreli at yahoo.com
Fri Dec 28 03:59:52 UTC 2018
On 12/27/2018 06:06 PM, Murilo wrote:
> Why is it that when I type "auto choice = randomSample(array);" and
> later when I try to index choice as in choice[1] it gives an error
message?
It's because randomSample returns either an input range or a forward
range depending both on the kind of range that it gets and the random
number generator used. Documented here:
https://dlang.org/library/std/random/random_sample.html
Because it never returns a random access range, it does not provide
indexing with operator []. If you definitely want random access, the
normal thing to do is to copy the elements into an array with e.g.
std.array.array (imported publicly by std.random):
import std.stdio;
import std.random;
import std.range;
void main() {
auto array = 100.iota;
// .array at the end returns an array:
auto choice = randomSample(array, 10).array;
writeln(choice[1]);
}
Ali
More information about the Digitalmars-d-learn
mailing list