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; begin 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; L99: end perm