如何为数组元素删除F#生成特定数量的随机索引 [英] How to Generate A Specific Number of Random Indices for Array Element Removal F#

查看:93
本文介绍了如何为数组元素删除F#生成特定数量的随机索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以sCount是源数组中的元素数,iCount是我要删除的元素数.

So sCount is the number of elements in the source array, iCount is the number of elements I want to remove.

let indices = Array.init iCount (fun _ -> rng.Next sCount) |> Seq.distinct |> Seq.toArray |> Array.sort

上述方法的问题在于,我需要专门删除iCount索引,但这不能保证这一点.

The problem with the method above is that I need to specifically remove iCount indices, and this doesn't guarantee that.

我尝试过类似的东西

while indices.Count < iCount do
    let x = rng.Next sCount
    if not (indices.Contains x) then
        indices <- indices.Add x

还有其他一些类似的东西...

And a few other similar things...

不过,我尝试过的每一种方法都非常慢-我正在处理的大小不超过2000万个元素的源数组.

Every way I've tried has been extremely slow though - I'm dealing with source arrays of sizes up to 20 million elements.

推荐答案

如果您需要一组与数组相比大小可忽略的索引,那么您正在做的事情就可以了.否则,请考虑对 Knuth-Fisher-Yates随机播放进行修改,以获取第一个i元素以1 .. n随机排列的元素:

What you're doing should be fine if you need a set of indices of negligible size compared to the array. Otherwise, consider doing a variation of a Knuth-Fisher-Yates shuffle to get the first i elements in a random permutation of 1 .. n:

let rndSubset i n =
    let arr = Array.zeroCreate i
    arr.[0] <- 0
    for j in 1 .. n-1 do
        let ind = rnd.Next(j+1)
        if j < i then arr.[j] <- arr.[ind]
        if ind < i then arr.[ind] <- j
    arr

这篇关于如何为数组元素删除F#生成特定数量的随机索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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