Logo

Programming-Idioms

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

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.

const idx = x.map((item, i) => i);
while (y.length < k) {
  const i = parseInt(Math.random() * idx.length, 10);
  y.push(x[[idx[i]]]);
  idx.splice(i, 1);
}

Note: lodash has a sample function.

Without native sampling in JS, create an array of unchosen indices of x and randomly pick them until y's length equals k.
(def y (->> x shuffle (take k)))

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