Programming Languages (CS302 2007S)

Algorithm 306: Permutation with Repetitions

A reformatted version of:

Bratley, P. (1967). Algorithm 306: Permutation with Repetitions [G6]. Communications of the ACM 10(7), July 1967, pp. 450-451.

procedure perm(a, n, last);
     value n;
     integer n;
     integer array a;
     Boolean last;
     integer i, p, q, r;
     own integer m;
     own integer array b[1:n];
     if (!last) then go to L12;
     last := false;
     for i := 1 step 1 until n do b[i] := a[i];
     p := b[n];
     for i := n step -1 until 1 do
       if p != b[i] then
         begin m := i; go to L99 end;
     m := 0;
     go to L99;
L12: if m = 0 then go to L10;
     p := b[m]; q := m; r := 0;
L9:  i := n;
L4:  if a[i] = p then go to L2
     if a[i] < p then r := i;
L5:  i := i-1; go to L4
L2:  a[i] := b[n] - 1;
     if r = 0 then go to L8
L1:  a[r] := p; q := q+1;
L3:  r := r+1;
     if r > n then go to L11
     else if a[r] > p then go to L3
L11: if b[q] = p then go to L1
     r := 0;
L6:  r := r+1; 
     if a[r] >= p then go to L6;
     a[r] := b[q];
     if q=n then go to L7;
     q := q + 1;
     go to L6;
L7:  last := false; go to L99;
L8:  q := q - 1; 
     if q = 0 then go to L10;
     if b[q] = p then go to L5;
     p := b[q]; go to L9;
L10:  last := true;
end perm

Disclaimer: I usually create these pages on the fly, which means that I rarely proofread them and they may contain bad grammar and incorrect details. It also means that I tend to update them regularly (see the history for more details). Feel free to contact me with any suggestions for changes.

This document was generated by Siteweaver on Mon Jan 29 08:26:34 2007.
The source to the document was last modified on Mon Jan 29 08:26:33 2007.
This document may be found at

You may wish to validate this document's HTML ; Valid CSS! ; Check with Bobby

Samuel A. Rebelsky,