Skip to content

Instantly share code, notes, and snippets.

@ashokdhaduk
Forked from tanmay27vats/twins.php
Created May 28, 2018 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashokdhaduk/ffd9d7142e6764a501b0fe9397a252b1 to your computer and use it in GitHub Desktop.
Save ashokdhaduk/ffd9d7142e6764a501b0fe9397a252b1 to your computer and use it in GitHub Desktop.
Two strings, a and b, are said to be twins only if they can be made equivalent by performing some number of operations on one or both strings. There are two possible operations: SwapEven: Swap a character at an even-numbered index with a character at another even-numbered index. SwapOdd: Swap a character at an odd-numbered index with a character…
function Twins($a, $b) {
$flag = false;
$a_len = count($a);
$b_len = count($b);
if($a_len != $b_len) {
throw new Exception('array index count mismatched!');
}
$result = [];
for($i = 0; $i<$a_len; $i++) {
$a_val = $a[$i];
$b_val = $b[$i];
$a_val_arr = str_split($a_val);
$b_val_arr = str_split($b_val);
$flag = false;
foreach($a_val_arr as $key => $val) {
$b_key = array_search($val, $b_val_arr);
if( ($key % 2 == 0 && $b_key % 2 == 0) || ($key % 2 != 0 && $b_key % 2 != 0) ) {
$flag = true;
} else if( ($key % 2 == 0 && $b_key % 2 != 0) || ($key % 2 != 0 && $b_key % 2 == 0)) {
$flag = false;
break;
}
}
if($flag) {
$result[$i] = "Yes";
} else {
$result[$i] = "No";
}
if(count($a_val_arr) != count($b_val_arr)) {
$result[$i] = "string length mismatched!";
}
}
return $result;
}
$string1 = array("cdab", "dcba");
$string2 = array("abcd", "abcd");
$result = Twins($string1, $string2);
echo implode("\n", $result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment