Re^2: Derangements iterator (duplicates)by tye (Sage)
|on Jan 08, 2008 at 15:35 UTC||Need Help??|
Update If one needed to allow for deranging a list which contains duplicates, one could simply derange the list of its indices.
Um, not really. A derangement algorithm that "doesn't handle duplicates" is one that deranges "1 4 4" into "4 1 4" because it doesn't notice that the duplicates are the same and so doesn't realize that replacing the last 4 with the second 4 didn't actually cause the last item to be different. It also, when deranging "1 1 2 2" returns "2 2 1 1" four times instead of just once because it doesn't realize that reversing "1 1" (nor "2 2") gives the same thing.
So your first algorithm simply breaks when presented with duplicates (it always finds zero derangements, for those who didn't notice) but your work-around just prevents this breakage while not actually correctly handling the duplicates. (So I'd suggest you document how it doesn't handle duplicates rather than suggest that work-around.)
Just for fun, here is your algorithm modified to correctly handle duplicates:
Of course, if you try to look up a definition for "derangement", you won't find anything that makes much sense when considering duplicates because mathematicians define derangements in term of permutations which they define without considering duplicates either (though they usually don't use language that actually makes that clear, either).
But the extension of these two concepts to cover lists with duplicate elements is natural, even obvious, as well as useful.