Revisiting the Permutation Generator in #swiftlang

It’s been a while, the language has evolved, and so I thought I’d visit my old friend the PermutationGenerator. Header docs say:

A *generator* that adapts a *collection* `C` and any *sequence* of its `Index` type to present the collection’s elements in a  permuted order.

You pass it a collection and a sequence of indices, and it returns elements based on that sequence. This code creates a scrambled index generator, which I feed to AnySequence to build the permuted output.

The permutation generator isn’t limited to random scrambles. You can use the same approach to build a strideable sequence as in this next snippet, or to any other computed walk through indices:

I had to tweak a bit with the distance check because you cannot use < to test two Self.Index operands. Update: Much improved. Thanks @oisdk.

While I don’t see myself using this a lot, I’m glad I had the chance to swing by it a second time for another look. As always, feel free to correct, tweak, or improve. Thanks!

2 Comments

  • This is the worst named method Apple has created. It’s *not* a PermutationGenerator. It’s a ObjectsAtIndexes generator. I have a bug on this, and they even acknowledged that it wasn’t named right, but now it’s probably too late for them to change it.

  • PermutationGenerator has been deprecated in Swift 2.2 and will be removed in Swift 3.