documentcloud/underscore — pull request #451 by skagedal (2012-01-29 22:25:54+00:00)
Title: _.pickRandom()

Hi!

Here is a proposed addition to underscore, a function that picks a number of random elements from an array. Functionally, \_.pickRandom(array, *[n]*) is equivalent to \_.first(\_.shuffle(array), *[n]*)), but much more effective. Takes time proportional to *n* rather than the length of the array.

The implementation might seem odd. It actually mutates the input array while it is working, but restores everything back to normal before returning. Hope you see how it works. I couldn't think of a better way to ensure that elements are picked from unique indices. One alternative would be to keep an array of indices picked so far and keep trying until a unique index was found. This would work well for picking 5 elements out of 1000, but would perform badly when the number of elements to pick is close to the length of the array.

Documentation and unit tests included. [Here](https://gist.github.com/1701014) is some extra testing code: speed test (compared with shuffle/first) and "fair coin toss" test.

I'm new to git and github, hope I am doing this the right way.

Regards,
Simon Kågedal Reimer