Exchange each pair of characters in a string

I would like to get all permutations of the replaced pairs of string characters. For instance:

Base line: abcd

Combinations:

  • bacd
  • acbd
  • abdc

and etc.

Edit

I want to change only the letters that are next to each other. Like the first with the second, the second with the third, but not the third with a pole.

What is the best way to do this?

Edit

Just for fun: there are three or four solutions, could anyone post a speed test for those so we can compare which is faster?

Speed ​​test

I did a speed test on nickf and mine, and the results are that mine beats nick with four letters (0.08 and 0.06 for 10K times), but nickf beats it with 10 letters (nick 0.24 and mine 0.37)

+3
source share
5 answers

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

nickf , :

  $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);
+1

How to use only 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";
}
0
source

Here is a slightly faster solution, since substr () should not be used.

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

Source: https://habr.com/ru/post/1698180/


All Articles