Logo

Programming-Idioms

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

Idiom #240 Sort 2 lists together

Lists a and b have the same length. Apply the same permutation to a and b to have them sorted based on the values of a.

uses classes;
type
  TPairedList = class(TStringList)
  private
    FBuddy: TStrings;
  protected
    procedure ExchangeItems(Id1, Id2: Integer); override;
  public
    procedure Sort(Buddy: TStrings); overload;
  end;

procedure TPairedList.ExchangeItems(Id1, Id2: Integer);
begin
  inherited Exchange(Id1, Id2);
  if Assigned(FBuddy) then
    FBuddy.Exchange(Id1, Id2);
end;

procedure TPairedList.Sort(Buddy: TStrings);
begin
  FBuddy := Buddy;
  Sort;
end;

begin
  ...
  a.sort(b);
end.
(->> (map vector a b)
     (sort-by first)
     (apply (partial mapv vector)))

this returns [a b]
the last line is from the 2d- transpose solution

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