[kw-pm] picking a random list element, the hard way
Cees Hek
ceeshek at gmail.com
Sun Feb 27 18:23:31 PST 2011
I hate it when people dangle exercises like this in front of my face
because i always get sucked into trying them out when i should be
doing more productive work ;)
Here is a (very ugly) golfed solution which is most likely of no use
to you in your intro class :)
seq 1 10 | perl -pe '$v=$_ if rand()<1/$.}{$_=$v'
I agree with you though, the algorithm is interesting and yet it is
still trivial enough to implement, which makes it a great example for
a beginner class.
Cheers,
Cees Hek
On Sat, Feb 26, 2011 at 5:52 AM, Robert P. J. Day <rpjday at crashcourse.ca> wrote:
>
> for your entertainment value, here's an optional exercise i'm going
> to give out in next week's perl class. it's not so much a perl
> question as it is an algorithmic analysis question that's actually
> quite simple to code once you figure it out.
>
> JOB: pick a random element from a list, such that each element in
> the list is equally likely to be selected.
>
> sounds trivial, yes? except here's the extra condition. you're
> given the list elements only *one at a time*. you're not allowed to
> store them, and you have no idea how many are coming. and yet, you
> still need to pick a random element out of that list.
>
> thoughts?
>
> rday
> _______________________________________________
> kw-pm mailing list
> kw-pm at pm.org
> http://mail.pm.org/mailman/listinfo/kw-pm
>
More information about the kw-pm
mailing list