pmcgee

Delphi version of std::next_permutation

Sep 7th, 2020 (edited)
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.52 KB | None | 0 0
  1. unit Next_perm_string;
  2. //
  3. //   refer libstdc++   https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.4/a01347.html
  4. //
  5. interface
  6.  
  7. function  D_next_permutation(var s:AnsiString; const first, end_:word) : boolean;
  8.  
  9.  
  10. implementation
  11.  
  12. procedure swapCh( var a : Ansichar; var b : Ansichar );   inline;
  13. var c :  Ansichar;
  14. begin
  15.     if a<>b then begin
  16.        c := a;  a := b;  b := c;
  17.     end;
  18. end;
  19.  
  20.  
  21. procedure reverse(var s:AnsiString; const a,x_:word);  inline;
  22. var
  23.     i,j : word;
  24. begin                               //  x_ is one past the end of reverse section
  25.    if  a  = x_-1    then  exit;
  26.    j     := (x_ - a) shr 1;         //  trunc( (x_ - a)/2 );
  27.    for i := 1 to j do
  28.             swapCh( s[a-1+i] , s[x_-i] );
  29. end;
  30.  
  31.  
  32. function  D_next_permutation(var s : AnsiString; const first, end_ : word) : boolean;  // inline;
  33. var
  34.     i, ii, j : word;
  35. begin
  36.     if first  =  end_        then exit(false);    //begin result := false; exit; end;
  37.         i    :=  first + 1;
  38.     if  i     =  end_        then exit(false);    //begin result := false; exit; end;
  39.         i    :=  end_  - 1;
  40.  
  41.     while true do begin
  42.             ii := i;  dec(i);
  43.  
  44.             if s[i] < s[ii] then begin
  45.  
  46.                 j := end_;
  47.                 repeat dec(j); until     s[i] < s[j];
  48.  
  49.                 swapCh( s[i] , s[j] );
  50.  
  51.                 reverse(s, ii, end_);
  52.                 result := true;
  53.                 exit;
  54.             end;
  55.  
  56.             if i = first then begin
  57.                 reverse(s, first, end_);
  58.                 result := false;
  59.                 exit;
  60.             end;
  61.     end;
  62.  
  63. end;
  64.  
  65. end.
  66.  
Add Comment
Please, Sign In to add comment