Shuffle list with some conditions

后端 未结 4 1244
余生分开走
余生分开走 2021-01-04 22:51

I have a list of elements which can be easily compared using Equals(). I have to shuffle the list, but the shuffle must satisfy one condition:

The i\'th

4条回答
  •  情书的邮戳
    2021-01-04 23:40

    It can be accomplished with a simple, two-step process. First use a Fisher-Yates (Knuth) shuffle in place. Then iterate over the list once, copying its elements to a new list. As you encounter an element, insert it into the first legal position in your new list. (This will be much more efficient with a linked list than with an array as your destination.) If there are no legal position to insert to, the instance of the problem is unsolvable. If you manage to fill your destination list, problem solved. This will take O(n) in the best case and O(n^2) in the worst.

提交回复
热议问题