如何从一个数组唯一随机物品? [英] How to get unique random items from an array?

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

问题描述

嘿,
我的(唯一的)对象的数组,并想获得这个阵列的4个随机的对象,但相同的对象不应该获取的两倍,因此使用一个简单的随机函数将无法正常工作。

我有两个想法:
1.洗牌数组,并获得第4项。 - >开销,因为数组可以是非常大的
。 2.生成一个随机指数。如果该指数之前使用,重试,等等... - >有点靠不住......

你知道一个更好的,更有效的方法?

解决方案
  

洗牌数组,并获得第4项。 - >开销,因为数组可以是非常大的。

使用现代版 = http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle相对=nofollow>费雪耶茨洗牌。它可以进行就地,如果​​你的前四个掉期后停止它会给您所需要的结果。没有必要洗牌整个阵列

  

相比一些其他的解决方案,它也有,如果所得到的置换的一部分是必要的,它可以被中途

停止的优点

Hey there,
I have an array of (unique) objects and would like to get 4 random objects of this array, but the same object shouldn't be fetched twice, so using a simple random function won't work.

I had two ideas:
1. Shuffle the array and get the first 4 items. -> Overhead, because the array can be very large.
2. Generate a random index. If that index was used before, try again, and so on... -> Somewhat unreliable...

Do you know a better, more efficient method?

解决方案

Shuffle the array and get the first 4 items. -> Overhead, because the array can be very large.

Use the modern version of the Fisher Yates shuffle. It can be performed in-place and if you stop after the first four swaps it will give you the result you need. There is no need to shuffle the entire array.

Compared to some other solutions, it also has the advantage that, if only part of the resulting permutation is needed, it can be stopped halfway through

这篇关于如何从一个数组唯一随机物品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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