views:

258

answers:

3

I've created a site for an artist friend of mine, and she wants the layout to stay the same, but she also wants new paintings she'd produced to be mixed into the current layout. So I have 12 thumbnails (thumb1 - thumb12) on the main gallery page and 18 images (img1 - img18) to place.

The approach I thought of was to create an array of all the images, randomize it, then simply scrape off the first 12 and load them into the thumb slots. Another approach would be to select 12 images randomly from the array. In the first case, I can't find a way to randomize the elements of an array. In the latter case, I can't wrap my brain around how to keep images from loading more than once, other than using a second array, which seems very inefficient and scary.

I'm doing all of this in Javascript, by the by.

+6  A: 

You should implement the Fisher-Yates shuffle (otherwise known as the Knuth shuffle).

Look at the great answer provided here.

ojblass
+1  A: 

Your first approach would work. Just shuffle the 18 elements and take the first 12.

Bill the Lizard
+8  A: 

I wrote this a while ago and it so happens to fit what you're looking for. I believe it's the Fisher-Yates shuffle that ojblass refers to:

Array.prototype.shuffle = function() {
   var i = this.length;
   while (--i) {
      var j = Math.floor(Math.random() * (i + 1))
      var temp = this[i];
      this[i] = this[j];
      this[j] = temp;
   }

   return this; // for convenience, in case we want a reference to the array
};

Note that modifying Array.prototype may be considered bad form. You might want to implement this as a standalone method that takes the array as an argument. Anyway, to finish it off:

var randomSubset = originalArray.shuffle().slice(0,13);

Or, if you don't want to actually modify the original:

var randomSubset = originalArray.slice(0).shuffle().slice(0,13);
Jeremy Huiskamp
Note that the inner loop is the Fisher-Yates shuffle mentioned. The outer loop is doing multiple shuffles. (Not that there's anything wrong with that.)
Bill the Lizard
Just a note your 'iters' loop. The Fisher-Yates shuffle is said to be unbiased which mean that every permutation is equally likely. Mixing up the array multiple times in no way "means a better mix."
Robert Cartaino
Even if the random number has a highly uneven distribution? I may as well just edit that part out anyway, as it obfuscates the answer to the question, as Bill points out.
Jeremy Huiskamp
Thanks so much!
b. e. hollenbeck