Print all permutations of a string in php

Php program for Print all permutations of a string. Here problem description and explanation.

<?php
// Php program for
// Print all permutations of a string
class Permutation
{
	// Swapping two string elements by index
	public
	function swap($text, $size, $a, $b)
	{
		// Check valid location of swap element
		if (($a >= 0 && $a < $size) && ($b >= 0 && $b < $size))
		{
			//Get first character
			$first = $text[$a];
			//Get second character
			$second = $text[$b];
			//Put character
			$text = substr($text, 0, $b - strlen($text)).$first.
            substr($text, $b + 1);
			$text = substr($text, 0, $a - strlen($text)).$second.
            substr($text, $a + 1);
		}
		return $text;
	}
	// Method which is print all permutations of given string
	public
	function findPermutation($text, $n, $size)
	{
		if ($n > $size)
		{
			return;
		}
		if ($n == $size)
		{
			echo $text, "\n";
			return;
		}
		for ($i = $n; $i < $size; ++$i)
		{
			// Swap the element
			$text = $this->swap($text, $size, $i, $n);
			$this->findPermutation($text, $n + 1, $size);
			// Swap the element
			$text = $this->swap($text, $size, $i, $n);
		}
	}
	public static

	function main($args)
	{
		$task = new Permutation();
		$text = "ABC";
		$size = strlen($text);
		$task->findPermutation($text, 0, $size);
		print("\n");
		$text = "abcd";
		$size = strlen($text);
		$task->findPermutation($text, 0, $size);
	}
}
Permutation::main(array());

Output

ABC
ACB
BAC
BCA
CBA
CAB

abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved