You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从数组中随机不重复选取元素?优雅实现方案探讨

问题:如何优雅地从数组中选取2或3个无重复元素?

我想从数组里选出2个或者3个完全不重复的元素,目前知道可以用Base.rand配合循环判断来实现,但总觉得这种写法不够优雅,想问问有没有更简洁清爽的实现方式。


2020/01/21 更新

感谢@Gwang-Jin Kim和@phipsgabler的建议!我按照你们的思路做了个小测试,对比了几种方案的速度和优雅性:

从测试结果来看,速度层面Base.rand加循环去重的方案确实是最快的,单次操作耗时在1.3e-7到1.4e-7之间浮动;但如果看代码的优雅程度,Random.shuffle和StatsBase.sample这两种写法明显更简洁直观。想确认下我这个结论是不是正确的?

using Base
using Random
using StatsBase

function _sampling1(M::Int64, N::Int64)
    for i in 1:M
        for j in 1:N
            r1, r2, r3 = Base.rand(1:N, 3)
            while (r1 == r2) | (r2 == r3) | (r1 == r3)
                r2, r3 = Base.rand(1:N, 2)
            end
        end
    end
end

function _sampling2(M::Int64, N::Int64)
    for i in 1:M
        for j in 1:N
            r1, r2, r3 = Random.shuffle(1:N)[1:3]
        end
    end
end

function _sampling3(M::Int64, N::Int64)
    for i in 1:M
        for j in 1:N
            r1, r2, r3 = StatsBase.sample(1:N, 3, replace=false)
        end
    end
end

M = 500
N = 100
time_cost1 = @elapsed _sampling1(M, N)
time_cost2 = @elapsed _sampling2(M, N)
time_cost3 = @elapsed _sampling3(M, N)

println(" rand: $(time_cost1 / (M * N))")
println("shuffle: $(time_cost2 / (M * N))")
println(" sample: $(time_cost3 / (M * N))")

#>>> rand: 1.3713026e-7
#>>> shuffle: 1.57786382e-6
#>>> sample: 5.6382496e-7

内容的提问来源于stack exchange,提问作者YuChan Tai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:39:14