Closed pixelzoom closed 4 years ago
@pixelzoom is this something that could wait until mid May, might be a nice one for Brandon
Yes, could wait until mid-May.
Here's my current implementation in NaturalSelectionUtils.js. Note that it also removes the items that it samples from the array, important for my application.
/**
* Removes n items from an array.
* @param {Array} array
* @param {number} n
* @returns {Array}
*/
removeSample( array, n ) {
assert && assert( array.length >= n, 'array does not contain enough elements' );
//TODO https://github.com/phetsims/natural-selection/issues/65 replace _.sampleSize with phet.joist.random.sampleSize
const elements = _.sampleSize( array, n );
_.pullAll( array, elements );
return elements;
}
No longer needed in Natural Selection, I changed how I'm selecting newborn bunnies for mutation, see phetsims/natural-selection#65. Closing.
For Natural Selection, I need the equivalent of lodash's
_.sampleSize( array, n)
, which randomly chooses n elements from array. Playback requires that all "random" things must be done using phet.joist.random, so this needs to be added todot.Random
.We started discussing this on Slack (see below), but didn't come to any conclusions.
Slack discussion
Jonathan Olson 9:55 AM Do the equivalent of a shuffle, then grab the first N elements? Michael Kauzmann:spiral_calendar_pad: 9:56 AM Isn't that slower than it could be? Jonathan Olson 9:57 AM It's totally potentially slower, feel free to write a faster version if desired Michael Kauzmann:spiral_calendar_pad: 9:57 AM Why not just grab n random indexes and pluck out one element per random double? Chris Malley 9:57 AM How do you grab n random unique indices? Jonathan Olson 9:57 AM Well, if you are picking 999 elements out of 1000, it's way faster to shuffle then pick out. If it's 2 out of 1000, it's faster to do that other method Michael Kauzmann:spiral_calendar_pad: 9:57 AM True! I was thinking if CM needed 6/1000, I guess either is good! Chris Malley 9:58 AM My array length 2 to 4000. My n varies from 1 to 200. And if this is to be added to Random, should we be making assumptions about array.length and n? Michael Kauzmann:spiral_calendar_pad: 10:01 AM perhaps a naive split where you do either algorithm depending on what percent n is of the total size? Jonathan Olson 10:02 AM Actually, you can just run a partial fisher-yates shuffle Michael Kauzmann:spiral_calendar_pad: 10:03 AM https://www.tutorialspoint.com/what-is-fisher-yates-shuffle-in-javascript like that? Jonathan Olson 10:03 AM Hmm, thinkingAssigning to @ariel-phet to assign. This is a prerequisite for Natural Selection, see https://github.com/phetsims/natural-selection/issues/65.