Skip to content

Instantly share code, notes, and snippets.

@MightyPork
Created October 20, 2015 15:05
Show Gist options
  • Save MightyPork/59f5c2a8a6a77cbcd6da to your computer and use it in GitHub Desktop.
Save MightyPork/59f5c2a8a6a77cbcd6da to your computer and use it in GitHub Desktop.
String Permutation Generator
<?php
// Needs php 5.6!
function combinations($length = 3, $chars = "abc")
{
$p = array_fill(0, $length, 0); // counters
$opt_count = strlen($chars);
$iter_count = $opt_count ** $length;
for($i = 0; $i < $iter_count; $i++) {
// Build the code
$s = '';
for ($j = 0; $j < $length; $j++) {
$s .= $chars[$p[$j]];
}
// offer to iterator
yield $s;
// advance the counters
if ($i < $iter_count - 1) {
$x = $length - 1;
while($x >= 0) {
$p[$x]++;
if ($p[$x] == $opt_count) {
$p[$x] = 0;
$x--;
} else {
break;
}
}
}
}
}
foreach(combinations(4, "PORK") as $x) {
echo "$x\n"; // do the haxx
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment