www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Working with randomSample

reply Murilo <murilomiranda92 hotmail.com> writes:
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?
Dec 27 2018
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
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
Dec 27 2018
parent Murilo <murilomiranda92 hotmail.com> writes:
On Friday, 28 December 2018 at 03:59:52 UTC, Ali Çehreli wrote:
 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:
 Ali
Thank you very much, now it all makes sense.
Dec 28 2018