Talk:Samples and permutations

From Lazarus wiki
Revision as of 23:43, 19 November 2020 by Bart (talk | contribs) (Created page with "ANother example, not using 2 arrays, but only one, maybe: <syntaxhighlight lang=pascal> type TIntegerDynArray= array of Integer; { Returns an array of aSize random intege...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

ANother example, not using 2 arrays, but only one, maybe:

type
  TIntegerDynArray= array of Integer;

{
  Returns an array of aSize random integers without duplicates ranging from
  aFrom (inclusive) to aTo (exclusive).
  - aFrom and aTo must be positive integers
  - aTo must be > aFrom
  - aSize must be <= aTo - aFrom
  - if either of these conditions is not met, an empty array will be returned.
}
function RandomArray(aFrom, aTo, aSize: Integer): TIntegerDynArray; overload;
var
  i, j, temp, Range: Integer;
begin
  Range := (aTo - aFrom);
  if (aFrom < 0) or (aFrom >= aTo) or (aSize > Range) then
    Exit(nil);
  SetLength(Result, Range);
  for i := Low(Result) to High(Result) do Result[i] := aFrom + i;
  // Use te Sattolo algorithm to shuffle the array
  // https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Sattolo.27s_algorithm
  i := Length(Result);
  while i > 0 do
  begin
    Dec(i);
    j := Random(i);
    temp := Result[i];
    Result[i] := Result[j];
    Result[j] := temp;
  end;
  if (aSize <> Range) then
    SetLength(Result, aSize);
end;

function RandomArray(aFrom, aTo: Integer): TIntegerDynArray; inline; overload;
begin
  Result := RandomArray(aFrom, aTo, (aTo - aFrom));
end;

function RandomArray(Range: Integer): TIntegerDynArray; inline; overload;
begin
  Result := RandomArray(0, Range, Range);
end;