Jump to content

Recommended Posts

Hello,

 

I have this piece of code that works as intended:

$chars = array('1','2','3');
$cnt = count($chars);
$strings = array();
for ($f = 0; $f < $cnt; $f++) {
for ($s = 0; $s < $cnt; $s++) {
 for ($t= 0; $t < $cnt; $t++) {
	 $strings[] = $chars[$f] . $chars[$s] . $chars[$t];
 }
}
}
print_r($strings);

 

The problem i'm facing is that i want to transform it in a function where i pass the chars and the nr of elements in the permutation in the above code if i want more elements ill duplicate the for loop and so on.

For example i'm trying to create a function like:

function perm($chars,$nrElements){
}

 

thank you in advance

Link to comment
https://forums.phpfreaks.com/topic/269664-permutation-function-for-nk-elements/
Share on other sites

  • 2 weeks later...

For variable input lengths you need a recursive method

 

<?php
function perm(&$perms, $chars, $stub='')
{   
   $k=count($chars);
   switch ($k) {
    case 0: return;
    case 1:
	    $perms[] = $stub . $chars[0];
	    return;
    default:
	    for ($i=0; $i<$k; ++$i) {
		    $copy = $chars;
		    $c = $copy[$i];
		    unset($copy[$i]);
		    perm($perms, array_values($copy), $stub.$c);
	    }
   }
}


$perms = array();
$chars = str_split('abcd');

perm($perms, $chars);

echo '<pre>'.print_r($perms, 1).'</pre>';    //list permutations

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.