Sign in Join
Wiki copytemporary

Samples and permutations

Functions for samples and permutations deliver randomly ordered vectors of data. Random samples may be used for very diverse applications, including simulating rolls of a die, generating anonymised IDs (e.g. for clinical trials), Monte Carlo simulations and wide-range statistical applications.

The following function delivers a vector of longint values, which are randomly ordered and range from min to max:

pascal
type
  TLongintvector_data = array of longint;   

function sample(min, max: longint; replace: boolean): TLongintvector_data;
var
  i, j, num1, num2: longint;
  Vector1, Vector2: TLongintvector_data;
begin
  randomize;                        // initialise random number generator
  num1 := 1 + max - min;            // length of vector to be generated
  SetLength(Vector1, num1);         // vector for original (ordered) data
  SetLength(Vector2, num1);         // vector with permuted data
  if num1 > 0 then
  begin
    for i := 0 to num1 - 1 do
    begin                           
      Vector1[i] := min + i;        // initialise original vector
    end;
    num2 := num1;
    for i := 1 to num1 do
    begin
      j := random(num2);            // select random element of Vector1
      Vector2[i - 1] := Vector1[j]; // and assign to next element of Vector2
      if not replace then
      begin
        Delete(Vector1, j, 1);      // remove randomly selected element
        Dec(num2);                  // and adapt size
      end;
    end;
  end;
  result := Vector2;
end;

Depending on the value of the parameter replace, the random elements of the vector are provided with or without replacement. With replacement, one number may occur several times. Without replacement all elements of the vector will contain unique numbers.

See also


From the Free Pascal wiki, page "Samples and permutations", as it stood on 2021-03-06 after a change by Jwdietrich, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 1, last changed by WikiArchive .

Edited on wiki.freepascal.org by 1 person, 2020–2021

From the official wiki's backup of 26 May 2024: who edited this page there, and when. Edits made there after that date were not recorded, and the earlier versions are not shown here; the main page says why.

WhenWhoWhat changed
JwdietrichCreating first version with an algorithm taken from my open source Quantum Salis repository (BSD license).
JwdietrichCreating "See also" section
JwdietrichImproving grammar.
JwdietrichMinor optimisations (minor)
JwdietrichClarification (minor)
JwdietrichLink to Ranking vectors of data created

Talk about this page

Nobody has opened a bench for this page yet. Sign in to open one.