Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- unit Next_perm_string;
- //
- // refer libstdc++ https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.4/a01347.html
- //
- interface
- function D_next_permutation(var s:AnsiString; const first, end_:word) : boolean;
- implementation
- procedure swapCh( var a : Ansichar; var b : Ansichar ); inline;
- var c : Ansichar;
- begin
- if a<>b then begin
- c := a; a := b; b := c;
- end;
- end;
- procedure reverse(var s:AnsiString; const a,x_:word); inline;
- var
- i,j : word;
- begin // x_ is one past the end of reverse section
- if a = x_-1 then exit;
- j := (x_ - a) shr 1; // trunc( (x_ - a)/2 );
- for i := 1 to j do
- swapCh( s[a-1+i] , s[x_-i] );
- end;
- function D_next_permutation(var s : AnsiString; const first, end_ : word) : boolean; // inline;
- var
- i, ii, j : word;
- begin
- if first = end_ then exit(false); //begin result := false; exit; end;
- i := first + 1;
- if i = end_ then exit(false); //begin result := false; exit; end;
- i := end_ - 1;
- while true do begin
- ii := i; dec(i);
- if s[i] < s[ii] then begin
- j := end_;
- repeat dec(j); until s[i] < s[j];
- swapCh( s[i] , s[j] );
- reverse(s, ii, end_);
- result := true;
- exit;
- end;
- if i = first then begin
- reverse(s, first, end_);
- result := false;
- exit;
- end;
- end;
- end;
- end.
Add Comment
Please, Sign In to add comment