2020/05/10

PHP code for a permutation algorithm

Since I'm currently writing yet-another-php-code-analyzer, I ended up writing a function or something to allow me to do permutation of the elements of any given array. The goal was to make a call to an anonymous function on each new iteration of the elements. Last time I did this was about 17 years ago using legacy mode, and I barely had the idea how I did it. Unfortunately that code is gone (perhaps still lying around on a CD waiting to be thrown to the trash can), so I had to start from zero.

To make this three days story short, as as TDD wanna-be practitioner, at first I tried to create an object, and as the Transformation Priority Premises states, I started using basic values at first (null, empty array, one element array and so on). But I took several wrong turns (as you can see my repository). Had to read again the TPP blog entry to see what I was doing wrong. On top of that I had a misunderstanding on how the array_splice and slice functions works so I had to write a microtest to make sure I understood them.

So my last try was to kept thing as simple as possible. Created a function to return the permuted values. Tests were up to 0, 1, 2, 3 and 4 elements, once I got it tried one with 10 elements and PHP ran out of memory.

Then I went to the anonymous function version and I got it (doing TDD but using the previous code as guide). Then tried a 10 elements version (which is on the tests but commented out) and php took about 4 seconds to do it on a Core2Duo Mac 5 Notebook (Maverick). For reference, back at the time I did it for the first time, an old Pentium II with 233 mhz clock, using Quick C the same process took about 10 seconds.

Resulting code is here