Permutation without repetition!
I want a function. I feed it a number. For example 2 and it returns an array of strings with every permutation it is possible from the numbers between 0 and 2. i.e. 012, 021, 120, 102, 201, 210. How would I do this with logic?
Permutation without repetition
Moderator: General Moderators
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
User comment from the manual http://www.php.net/manual/en/function.shuffle.php#70370
SOLVED: This is what I came up with. I know its pretty rubbish but it does work. Anyone see a way to improve this?
Code: Select all
print_r(permutations(2));
function permutations($end, $start = 0)
{
if($start == $end)
{
return array(array($end));
}
if($start > $end)
{
list($start, $end) = array($end, $start);
}
$rtn = array(array($start));
for($i = $start + 1; $i <= $end; $i++)
{
$temp = array();
foreach($rtn as $k => $v)
{
for($j = 0; $j <= count($v); $j++)
{
$temp[] = array_insert($v, $i, $j);
}
}
$rtn = $temp;
}
return array_reverse($rtn);
}
function array_insert($array, $num, $pos)
{
foreach($array as $k => $v)
{
if($k == $pos)
{
$rtn[] = $num;
}
$rtn[] = $v;
}
if($k < $pos)
{
$rtn[] = $num;
}
return $rtn;
}