import std.random;
import std.array;

/**
 * Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.
 *
 * @param array The input array.
 * @param num Specifies how many entries should be picked.
 * @return When picking only one entry, array_rand() returns the key for a random entry.
 *         Otherwise, an array of keys for the random entries is returned.
 *         This is done so that random keys can be picked from the array as well as random values.
 *         If multiple keys are returned, they will be returned in the order they were present in the original array.
 *         Trying to pick more elements than there are in the array will result in an E_WARNING level error, and NULL will be returned.
 */
auto array_rand(T)(T[] array, int num = 1)
{
    if (num > array.length) return null;

    auto indexes = array.length.iota.array;
    return indexes[randomShuffle(indexes).take(num)];
}
``
dlang语言实现php的array_rand函数该函数描述如下Description ¶array_randarray $array int $num = 1 intstringarrayPicks one or more random entries out of an array and returns the key or keys of the random entriesCaution

原文地址: https://www.cveoy.top/t/topic/fyT6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录