Skip to content

Instantly share code, notes, and snippets.

@tanmay27vats
Created April 29, 2018 12:34
Show Gist options
  • Select an option

  • Save tanmay27vats/5727b3e37cda65a68e87abfdb3f8f9a7 to your computer and use it in GitHub Desktop.

Select an option

Save tanmay27vats/5727b3e37cda65a68e87abfdb3f8f9a7 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);
@uurtech

uurtech commented Jul 14, 2018

Copy link
Copy Markdown

You rock.

@nachitox

Copy link
Copy Markdown

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