简体   繁体   中英

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)

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);

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);

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";
}

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM