On a related note, if you want to iterate through all permutations lexicographically, see the algorithm of
Narayana Pandita, which efficiently handles duplicate items. There are various other permutation ranking & unranking algorithms which are a little more efficient, although they generally aren't lexicographic.