Gets n random elements from an array.
If n is greater than the array length, returns all elements in random order. If n is 0 or negative, returns an empty array.
从数组中获取 n 个随机元素。
如果 n 大于数组长度,则以随机顺序返回所有元素。 如果 n 为 0 或负数,则返回空数组。
The array to sample from. 要取样的数组
The number of elements to sample. 要取样的元素数量
An array of random elements from the array. 数组中的随机元素数组
O(n) time complexity where n is the size parameter. Uses Fisher-Yates partial shuffle for unbiased sampling
O(n) 时间复杂度,其中 n 为 size 参数。使用 Fisher-Yates 部分洗牌算法实现无偏取样
sampleSize([1, 2, 3, 4, 5], 2)// => [3, 1] (random 2 elements from the array) Copy
sampleSize([1, 2, 3, 4, 5], 2)// => [3, 1] (random 2 elements from the array)
sampleSize([1, 2, 3], 5)// => [2, 1, 3] (all elements in random order) Copy
sampleSize([1, 2, 3], 5)// => [2, 1, 3] (all elements in random order)
Gets n random elements from an array.
If n is greater than the array length, returns all elements in random order. If n is 0 or negative, returns an empty array.
从数组中获取 n 个随机元素。
如果 n 大于数组长度,则以随机顺序返回所有元素。 如果 n 为 0 或负数,则返回空数组。