Chris
Chris

Reputation: 3445

Swap every pair of characters in string

I'd like to get all the permutations of swapped characters pairs of a string. For example:

Base string: abcd

Combinations:

  1. bacd
  2. acbd
  3. abdc

etc.

Edit

I want to swap only letters that are next to each other. Like first with second, second with third, but not third with sixth.

What's the best way to do this?

Edit

Just for fun: there are three or four solutions, could somebody post a speed test of those so we could compare which is fastest?

Speed test

I made speed test of nickf's code and mine, and results are that mine is beating the nickf's at four letters (0.08 and 0.06 for 10K times) but nickf's is beating it at 10 letters (nick's 0.24 and mine 0.37)

Upvotes: 5

Views: 4951

Answers (5)

Czimi
Czimi

Reputation: 2534

Here is a slightly faster solution as its not overusing substr().

function swapcharpairs($input = "abcd") {
  $pre = "";
  $a="";
  $b = $input[0];
  $post = substr($input, 1);
  while($post!='') {
    $pre.=$a;
    $a=$b;
    $b=$post[0];
    $post=substr($post,1);
    $swaps[] = $pre.$b.$a.$post;
  };
  return $swaps;
}

print_R(swapcharpairs());

Upvotes: 0

mweerden
mweerden

Reputation: 14051

How about just using the following:

function swap($s, $i)
{
  $t = $s[$i];
  $s[$i] = $s[$i+1];
  $s[$i+1] = $t;

  return $s;
}

$s = "abcd";
$l = strlen($s);
for ($i=0; $i<$l-1; ++$i)
{
  print swap($s,$i)."\n";
}

Upvotes: 0

Georg Sch&#246;lly
Georg Sch&#246;lly

Reputation: 126155

A fast search in google gave me that:

http://cogo.wordpress.com/2008/01/08/string-permutation-in-php/

Upvotes: 1

Chris
Chris

Reputation: 3445

nickf made beautiful solution thank you , i came up with less beautiful:

  $arr=array(0=>'a',1=>'b',2=>'c',3=>'d');
  for($i=0;$i<count($arr)-1;$i++){
  $swapped="";
  //Make normal before swapped
  for($z=0;$z<$i;$z++){
   $swapped.=$arr[$z];
  }
  //Create swapped
  $i1=$i+1;
  $swapped.=$arr[$i1].$arr[$i];

  //Make normal after swapped.     
  for($y=$z+2;$y<count($arr);$y++){
  $swapped.=$arr[$y];

  }
$arrayswapped[$i]=$swapped;
}
var_dump($arrayswapped);

Upvotes: 1

nickf
nickf

Reputation: 546303

Edit: Markdown hates me today...

$input = "abcd";
$len = strlen($input);
$output = array();

for ($i = 0; $i < $len - 1; ++$i) {
    $output[] = substr($input, 0, $i)
              . substr($input, $i + 1, 1)
              . substr($input, $i, 1)
              . substr($input, $i + 2);
}
print_r($output);

Upvotes: 3

Related Questions