Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
@uurtech

This comment has been minimized.

Copy link

uurtech commented Jul 14, 2018

You rock.

@nachitox

This comment has been minimized.

Copy link

nachitox commented Nov 11, 2018

papota
papoto

it doesn't work... just checking indexes won't do it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.