如何从数组中获取唯一的随机项? [英] How to get unique random items from an array?

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

问题描述

嘿,
我有一个(唯一的)对象数组,并且想要获得这个数组的 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.

我有两个想法:
1. 打乱数组,得到前 4 项.-> 开销,因为数组可能非常大.
2. 生成随机索引.如果之前使用过该索引,请重试,依此类推... -> 有点不可靠...

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?

推荐答案

打乱数组并获得前 4 项.-> 开销,因为数组可能非常大.

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

使用现代版本Fisher Yates shuffle.它可以就地执行,如果您在前四次交换后停止,它将给出你得到你需要的结果.不需要打乱整个数组.

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天全站免登陆