Jump to content

Permutation Function For N,k Elements


dsp77

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

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.