dsp77 Posted October 19, 2012 Share Posted October 19, 2012 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 More sharing options...
Scott_S Posted October 27, 2012 Share Posted October 27, 2012 Wouldn't count($chars) be your n? Link to comment https://forums.phpfreaks.com/topic/269664-permutation-function-for-nk-elements/#findComment-1388097 Share on other sites More sharing options...
Barand Posted October 28, 2012 Share Posted October 28, 2012 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 ?> Link to comment https://forums.phpfreaks.com/topic/269664-permutation-function-for-nk-elements/#findComment-1388300 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.