Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #158 Random sublist

Create a new list y from randomly picking exactly k elements from list x.

It is assumed that x has at least k elements.
Each element must have same probability to be picked.
Each element from x must be picked at most once.
Explain if the original ordering is preserved or not.

import "math/rand"
y := make([]T, k)
perm := rand.Perm(len(x))
for i, v := range perm[:k] {
	y[i] = x[v]
}

Allocate a slice of T of size exactly k.
perm is a slice of int of size len(x).
This is O(len(x)) in space and runtime.

The original ordering is not preserved.
(def y (->> x shuffle (take k)))

New implementation...
< >
programming-idioms.org