Randomize StringList

后端 未结 3 1437
有刺的猬
有刺的猬 2020-12-06 10:41

How can I randomize the Strings in the StringList similarly how this online tool works. If anyone is familiar with it, check this: http://textmechanic.co/Randomize-List.html

3条回答
  •  旧时难觅i
    2020-12-06 11:31

    To randomize a TStrings, create a comparer from TComparer with random result value, and sort the TStrings with it.

    /// The Comparer
    TMyShuffleComparer= class(TComparer)
    public
      function Compare(const Left, Right: string): Integer; override;
    end;
    
    /// The randomizer 
    function TMyShuffleComparer.Compare(const Left, Right: TCard): Integer;
    begin
      // To sort, get a random number for compare result
      Result := Random(100) - 50;
    end;
    
    /// How to call the comparer
    procedure TMyStrings.Shuffle;
    begin
     Sort(TMyShuffleComparer.Create);
    end;
    

    or to call directly:

      /// Shuffle
      MyString.Sort(TMyShuffleComparer.Create);
    

提交回复
热议问题