Page 1 of 1
Permutation without repetition
Posted: Tue Oct 24, 2006 2:13 pm
by bokehman
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?
Posted: Tue Oct 24, 2006 3:14 pm
by John Cartwright
Posted: Tue Oct 24, 2006 5:05 pm
by bokehman
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;
}