Skip to content

Add function that randomises the strings in a string list #64

@delphidabbler

Description

@delphidabbler

Such a function was suggested by @Thaddy in #28 (comment).

A series of overloaded functions, something like the following might do the job (written off the top of my head - not compiled or tested 🤞):

procedure RandomiseStrings(const AList: TStringList); overload;
begin
  AList.CustomSort(
    function(L: TStringList; A, B: Integer): Integer
    begin
      // becomes -1, 0 or 1
      Result := Random(3) - 1;
    end
   );
end;

and a string array version:

function RandomiseStrings(const AArray: array of string): TArray<string>; overload;
begin
  var SL := TStringList.Create;
  try
    for var S in AArray do
      SL.Add(S);
    RandomiseStrings(SL);
    Result := SL.ToStringArray;
  finally
    SL.Free;
  end;
end;

It's a shame that TStrings doesn't implement CustomSort - it would have made the routine more general.

Maybe:

procedure RandomiseStrings(const AList: TStrings); overload;
begin
  var SL := TStringList.Create;
  try
    SL.Assign(AList);
    RandomiseStrings(SL);
    AList.Assign(SL);
  finally
    SL.Free;
  end;
end;

Metadata

Metadata

Assignees

Labels

acceptedIssue will be actionedenhancementNew feature or request

Projects

Status

Accepted

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions