If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Permutations!
A couple of generators: pass one an array and it have it successively crank out different permutations of the array's elements. ("Different", that is, if all of the input array's elements are distinct.)

One yields the permutations in lexicographic ("dictionary") order. Think of the array as a word written in some weird alphabet (its elements being the letters), and taking the order of letters in that word to be "alphabetical" (an English example of such a word would be "begins").

Code:

a b c
a c b
b a c
b c a
c a b
c b a

The other is a "minimum change" order. The permutations in each adjacent pair in the generated list differ by a single pair of swapped elements. Obviously, the swap has to yield a permutation that has not yet been seen, with the added proviso that the process doesn't get itself wedged into a corner where no swap can generate a new permutation. If there is a choice of swaps that could be made, the leftmost is picked.

Code:

a b c
b a c
c a b
a c b
b c a
c b a

So, here's the code. Note that minimum_change_permutations uses an auxiliary factorial function. Feel free to pick something more robust if you want to be generating such a sequence of permutations with more than 20 elements (which has given me something to think about...).

This is more of a sketch of an idea. That idea is that "It would be nice to be able to call a method on an array of objects and have that method call mapped over all of the objects in the array." Like I have an array $clients and I want to call $client->getMessages('INFO', $channel) on each one.