如何从一个数组唯一随机物品?数组、物品

由网友(夢也渺渺、)分享简介:嘿,我的(唯一的)对象的数组,并想获得这个阵列的4个随机的对象,但相同的对象不应该获取的两倍,因此使用一个简单的随机函数将无法正常工作。 我有两个想法:1.洗牌数组,并获得第4项。 - >开销,因为数组可以是非常大的。2.生成一个随机指数。如果该指数之前使用,重试,等等... - >有点靠不住...... 你知...

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

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

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

解决方案   

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

使用费雪耶茨洗牌。它可以进行就地,如果​​你的前四个掉期后停止它会给您所需要的结果。没有必要洗牌整个阵列

  

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

停止的优点

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...

C语言问题,我想做一个查找数组元素的东西,返回找到元素的数量以及把元素所在的位置传给另一个数组,

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

阅读全文

相关推荐

最新文章