LoginSignup
4
2

More than 5 years have passed since last update.

Juliaで重複がないサンプリング

Posted at

1から$n$までのリストから、重複が無いように$k$個($n$以下でないといけない)の要素をサンプリングするという操作がそこそこの頻度で必要になる(復元抽出と非復元抽出のことだけど)。

単純にrandint的なことをやろうとすると標準で使えるrandを使うと、重複ありのサンプリングが可能。

n = 10
k = 5
rand(1:n, k)

> 5-element Array{Int64, 1}:
   2
   3
   6
   5
   5

重複が望ましくない場合、StatsBaseに入っているsampleを利用して、replaceフラグを設定すれば良い。

using StatsBase
n = 10
k = 5
sample(1:n, k, replace=false)
> 5-element Array{Int64, 1}:
   5
   7
   4
   2
  10

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2