Created
October 20, 2015 15:05
-
-
Save MightyPork/59f5c2a8a6a77cbcd6da to your computer and use it in GitHub Desktop.
String Permutation Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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