Go: proposal: add support for random sampling from a collection

Created on 6 Feb 2018  ·  6Comments  ·  Source: golang/go

go 1.8.4

Random sampling is a very commonly used method to draw samples from a collection, like random.sample(population, k) in python.

I hope there is a plan to add it in.

FrozenDueToAge LanguageChange Proposal

Most helpful comment

This is easy enough today

idx := rand.Perm(n)
sample := make([]T, n)
for i := 0; i < k; i++ {
    sample[i] = population[idx[i]]
}

or with go1.10

sample := append([]T(nil), population...)
rand.Shuffle(n, func(i, j int) { sample[i], sample[j] = sample[j], sample[i] })
sample = sample[:k]

All 6 comments

The reason such a method is useful in python is that you can pass to it different kinds of collections, so it provides a nice unified interface.

In Go you can only draw a sample from slices and maps, but there's no overloading so you'd have to add two different functions (SampleSlice and SampleMap), losing the advantage of a nice unified interface for random sampling.

The range random map access implementation detail does invite using it to get random elements.

A built-in like this would be useful for me:

// pick returns a slice (len = n) of pseudorandom elements 
// in unspecified order from c which is an array, slice, or map.
for i, e := range pick(c, n) {

The range random map access implementation detail does invite using it to get random elements.

This is a very bad idea if you need the distribution to be uniform. It won't be. We should discourage doing that.

This is easy enough today

idx := rand.Perm(n)
sample := make([]T, n)
for i := 0; i < k; i++ {
    sample[i] = population[idx[i]]
}

or with go1.10

sample := append([]T(nil), population...)
rand.Shuffle(n, func(i, j int) { sample[i], sample[j] = sample[j], sample[i] })
sample = sample[:k]

@uluyol
LGTM

Sounds like this can be closed. Please comment if that’s not right.

Was this page helpful?
0 / 5 - 0 ratings