USE: math.combinatorics : invert ( perm -- perm' ) >alist sort-values keys ; : factoradic>integer ( factoradic -- n ) [ factorial * ] map-index sum ; : >factoradic ( permutation -- factoradic ) dup [ unclip [ '[ _ over < [ 1 - ] when ] map ] keep ] replicate nip ; : depermutation ( seq -- n seq ) [ 2array ] map-index sort-keys unzip invert >factoradic factoradic>integer swap ; : next-permutation ( seq -- seq ) dup depermutation [ 3dup permutation <=> +lt+ = not ] [ [ 1 + ] dip ] while permutation nip ;