Logo

Programming-Idioms

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

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.

uses Types, Math;
function RandArr(Max: Integer): TIntegerDynArray;
var
  i, j, temp: Integer;
begin
  SetLength(Result, Max+1);
  for i := Low(Result) to High(Result) do Result[i] := i;
  i := Length(Result);
  while i > 0 do
  begin
    Dec(i);
    j := RandomRange(0,i);
    temp := Result[i];
    Result[i] := Result[j];
    Result[j] := temp;
  end;
end;
  
var
  Idx: TIntegerDynArray;
begin
  Idx := RandArr(High(X));
  SetLength(Y, k);
  for i := 0 to k-1 do Y[i] := X[Idx];
end.

First create an array (Idx) of random integers from 0 to number of elements in X minus 1.
It is created using the Sattolo algorithm.

Then create a list Y of k elements (all elements will be nil after creation).

Then copy k elements form X to Y using the first k elements of the Idx array to determine what element to pick from X
(def y (->> x shuffle (take k)))

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