随机数组中的元素? [英] Randomizing elements in an array?

查看:110
本文介绍了随机数组中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个网站,我的一位画家朋友,和她想要的布局保持不变,但她也希望新的画作,她会产生混合到当前布局。所以我有12张缩略图(thumb1 - thumb12)主图库页面上18幅图像(IMG1 - img18)的地方,以及

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 as well

我想到的方法是创建所有的图像阵列,随机,然后简单地刮去第12并将其加载到拇指槽。另一种方法是将来自阵列12中选择的图像随机。在第一种情况下,我不能找到一种方法,随机数组中的元素。在后一种情况下,我不能加载超过一次,除了使用第二阵列,这似乎非常低效和可怕的总结我的周围如何保持图像的大脑。

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.

我做的这一切在Javascript,顺便说一句。

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

推荐答案

我前一段时间写了这一点,它恰巧适合你要找的内容。我相信这是费雪耶茨洗牌的ojblass指的是:

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
};

请注意,修改Array.prototype可以被认为是不好的形式。你可能想实现这个作为一个独立的方法,该方法的数组作为参数。总之,要完成它:

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);

这篇关于随机数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆