I am using someones permutation solution in PHP that was given off stack and was wondering if there was a way for me to limit the character count in the string to be a fixed amount? Lets say I want to limit the string length to only 4 characters. To be honest, I'm not sure really whats going on in this formula and was hoping I could modify it, but I would also be interested in a new formula approach as well especially if its faster from another individual. Thanks
ini_set('memory_limit', '1024M');
function permutations(array $elements)
{
if (count($elements) <= 1) {
yield $elements;
} else {
foreach (permutations(array_slice($elements, 1)) as $permutation) {
foreach (range(0, count($elements) - 1) as $i) {
yield array_merge(
array_slice($permutation, 0, $i),
[$elements[0]],
array_slice($permutation, $i)
);
}
}
}
}
$list = ['a', 'b', 'c', 'd', 'e', 'f'];
$newlist = array();
foreach (permutations($list) as $permutation) {
//echo implode(',', $permutation) . PHP_EOL;
array_push($newlist, implode(',', $permutation));
}
echo sizeof($newlist);
1 Answer 1
Here is an adaptation of the function that allows you to put a limit on the number of characters as second argument.
You need to add an extra parameter to know how many remaining characters are allowed and decrement it on the recursive call :
function permutations(array $elements, $limit)
{
if( $limit == 1 )
{
// No need to go deeper, return a list of all remaining letters
foreach($elements as $element)
yield array($element);
}
foreach($elements as $i => $element)
{
// compute all the permutions, without the elements at index i
$sub_perms = permutations( array_merge(array_slice($elements, 0, $i), array_slice($elements, $i+1)), $limit-1);
// list all the permutations with the currently selected element + all the possible combinations of $limit-1 letters of the others elements
foreach($sub_perms as $sub_perm)
{
yield array_merge(array($element), $sub_perm);
}
}
}
You can then call permutations($list, 2) or permutations($list, 4) to have all the permutations of 2 or 4 characters.
echo sizeof($newlist);to print the size which is probably 6! for['a', 'b', 'c', 'd', 'e', 'f'].Lets say I want to limit the string length to only 4 characters? Can you give an example?