有效地挑个随机元素从PHP数组(不含洗牌) [英] Efficiently pick n random elements from PHP array (without shuffle)

查看:115
本文介绍了有效地挑个随机元素从PHP数组(不含洗牌)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code接 $ N 从PHP中的数组 $阵列元素:

 洗牌($数组);
$结果= array_splice($数组,0,$ N);

给定一个大阵,但只有少数几个元素(例如 5 出的 10000 ),这是比较慢,所以我想优化它,使得并不是所有的元素都被打乱。该值必须是唯一的。

我在寻找FO最高效的替代品。我们可以假设, $阵列有没有重复,是 0 -indexed。


解决方案

  $ randomArray = [];
而(计数($ randomArray)小于5)){
  $ randomKey = mt_rand(0,计数($数组)-1);
  $ randomArray [$ randomKey] = $阵列[$ randomKey];
}

这将提供没有重复并很快正好5个元素。钥匙将是preserved。

注:你必须确保$阵列有5个或更多的元素,或添加某种检查,以prevent无限循环

I have the following code to pick $n elements from an array $array in PHP:

shuffle($array);
$result = array_splice($array, 0, $n);

Given a large array but only a few elements (for example 5 out of 10000), this is relatively slow, so I would like to optimize it such that not all elements have to be shuffled. The values must be unique.

I'm looking fo the most performant alternative. We can assume that $array has no duplicates and is 0-indexed.

解决方案

$randomArray = [];
while (count($randomArray) < 5)) {
  $randomKey = mt_rand(0, count($array)-1);
  $randomArray[$randomKey] = $array[$randomKey];
}

This will provide exactly 5 elements with no duplicates and very quickly. The keys will be preserved.

Note: You'd have to make sure $array had 5 or more elements or add some sort of check to prevent an endless loop.

这篇关于有效地挑个随机元素从PHP数组(不含洗牌)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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