PHP function to generate all permutations

To generate all permutations of a given set means to find all possible ways the elements of the set can be arranged. For example, if the given set is {1, 2, 3} the permutations are:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

The number of permutations of a set of n distinct object is n×(n − 1)×(n − 2)×…×2×1; this number is called “n factorial”.

In real life permutations are used for solving a lot of problems: allotting phone numbers, generating car plate numbers, generating IP address, password hackings etc.

So, for those in need, here you have a PHP implementation of an algorithm to generate all permutations. The function has one parameter – the array of elements – and it returns an array of all permutations minus the original one. As a bonus, it’s an iterative method because I, for one, am not a big fan of recursivity in PHP.

function permutations($set)
	{
	$solutions=array();
	$n=count($set);
	$p=array_keys($set);
	$i=1;
 
	while ($i<$n)
		{
		if ($p[$i]>0)
			{
			$p[$i]--;
			$j=0;
			if ($i%2==1)
				$j=$p[$i];
			//swap
			$tmp=$set[$j];
			$set[$j]=$set[$i];
			$set[$i]=$tmp;
			$i=1;
			$solutions[]=$set;
			}
		elseif ($p[$i]==0)
			{
			$p[$i]=$i;
			$i++;
			}
		}
	return $solutions;
	}

Example to call this function:

$set=array(1, 2, 3, 4);
print_r(permutations($set));

1 comment to PHP function to generate all permutations

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Categories

Archives

Calendar

February 2012
M T W T F S S
« May    
 12345
6789101112
13141516171819
20212223242526
272829