Trying to understand RandomSample struct in std.random
Ali Çehreli
acehreli at yahoo.com
Thu Apr 12 11:39:16 PDT 2012
On 04/12/2012 11:30 AM, Joseph Rushton Wakeling wrote:
> What gets output at the end is clearly an array containing a subset of
> the original input.
That's misleading. RandomSample is a lazy range. The output seems to be
elements of an array only as you pull data out of this range.
> The constructor sets various initial values and then calls a function
> prime() [looks like an implementation of Knuth's Algorithm S] which
> returns when the current _index value is selected. Otherwise, it moves
> along to the next index value.
>
> What I don't understand is where the selected values are stored or how
> they come to be available.
The actual values are produced by the range that is passed to
RandomSample. RandomSample merely skips over some of those values.
> I also don't understand the corresponding randomSample functions where a
> specified random number generator is passed; how it can work to set
> ret.gen = gen _after_ the RandomSample struct has been initialized.
It is ok because the returned RandomSample range is not used yet. It
will be used only after having been returned from the randomSample()
convenience function.
> Can anyone help me to understand how this struct works?
I shamelessly provide a link to a chapter that I have written, which I
think covers all of these topics:
http://ddili.org/ders/d.en/ranges.html
> Thanks & best wishes,
>
> -- Joe
Ali
More information about the Digitalmars-d-learn
mailing list