Permutation without repetition

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Permutation without repetition

Post 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?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post 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;
}
Post Reply