Friday, May 27, 2016

Generate all possible permutation of string using PHP.


(Date : 28-May 12:05 IST)

I tried to solve it by recursion but at the end come to this solution i.e.

1)Run a loop so that each char come to first position one by one

2)Remove the char(i.e. now in first position) from that position so that remaining string is still in sequence

3)And rotate the whole remaining string like
cat
i)'c' remains constant(Prefix)
ii)rotate 'at'

4)Rotating 'at' is also tricky.So come to this solution that
i)Run a for loop divide it into two parts(I not look into php function for doing so)
First part start from the counter from where this loop working
Second part start from 0 upto the counter

5)And form an array.(Array dimension is (string length)*(String length-1))


Here is the code.

Updated solution( Aug-2017 )
(Can rotate any length of string)

<?php
$string="abc";
$array=array();
for($i=0;$i<strlen($string);$i++)
{
$array[]=$string[$i];
}
$rotate=rotate($array);

$rotate=array_unique($rotate);
print_r($rotate);
function rotate($array)
{
if(count($array)==2)
{
$data0=array_pop($array);
$data1=array_pop($array);
return array($data0.$data1,$data1.$data0);
}
else
{
$finalArray=array();
for($i=0;$i<count($array);$i++)
{
$tempArray=array();
for($k=0;$k<count($array);$k++)
{
if($k==$i)
{
continue;
}
$tempArray[]=$array[$k];
}
if(count($tempArray)>=2)
{
$tempData=rotate($tempArray);
}
for($j=0;$j<count($tempData);$j++)
{
$finalArray[]=$array[$i].$tempData[$j];
}
}
return $finalArray;
}
}
?>

Past solution( May-2017 )
(Can rotate 3 character string)

function generatePermutation($string)
{
  #----------------
  #---act
  #---atc
  #---cat
  #---cta
  #---tac
  #---tca
  #--------------
    for($i=0;$i<strlen($string);$i++)
    {  
$j=0;
 $tempString="";
 #--------------------------
 #---Get later portion of string
 #--------------------------------
 for($k=0;$k<strlen($string);$k++)
 {
if($i==$k)
{
continue;
}
else
{
$tempString.=$string[$k];
}
 }
 #---------------------------------------
 #----Generate all permutation
          #------------------------------------------
 for($l=0;$l<strlen($tempString);$l++)
 {
$tempTempString="";
for($m=$l;$m<strlen($tempString);$m++)
{
$tempTempString.=$tempString[$m];
}
for($m=0;$m<$l;$m++)
{
$tempTempString.=$tempString[$m];
}
$array[$i][$j++]=$string[$i].$tempTempString;
 }
    }
    return $array;
}

No comments: