Created
February 20, 2018 06:29
-
-
Save SergeyNarozhny/72c211188eace09ada6fa0f2cc2f3fe6 to your computer and use it in GitHub Desktop.
Twin Strings. 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...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Twins(a, b) { | |
var result = Array(a.length), | |
swap = function(arr, index) { | |
var tmp = arr[index]; | |
arr[index] = arr[index + 2]; | |
arr[index + 2] = tmp; | |
return arr; | |
}, | |
swapBack = function(str, index) { | |
var arr = str.split(''); | |
return swap(arr, index).join(''); | |
}; | |
for (var i = 0; i < a.length; i++) { | |
// No need to compare | |
if (!b[i]) { | |
break; | |
} | |
// Already equal | |
else if (a[i] === b[i]) { | |
result[i] = "Yes"; | |
continue; | |
} | |
var verification = []; | |
verification.push(a[i]); | |
for (var z = 0; z < verification.length; z++) { | |
var str = verification[z], | |
txtArr = str.split(''); | |
console.log('iter', str); | |
for (var j = 0; j < txtArr.length; j++) { | |
// No pair | |
if (!txtArr[j+2]) { | |
break; | |
} | |
// Swap | |
console.log('inside iter', txtArr[j], txtArr[j+2]); | |
swap(txtArr, j); | |
// Compare each time | |
var check = txtArr.join(''); | |
if (check === b[i]) { | |
result[i] = "Yes"; | |
console.log('YES'); | |
break; | |
} | |
else { | |
var checkBack = swapBack(check, j); | |
if (verification.indexOf(check) === -1) { | |
verification.push(check); | |
} | |
if (verification.indexOf(checkBack) === -1) { | |
verification.push(checkBack); | |
} | |
} | |
}; | |
if (result[i] === "Yes") { | |
break; | |
} | |
}; | |
console.log('verification', verification); | |
!result[i] && (result[i] = "No"); | |
} | |
return result; | |
} | |
console.log(Twins(["ddccdab", "dcba"], ["ddcabcd", "abcd"])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @SergeyNarozhnyy,
I have built a logic in PHP language, that can accept n number of indexes in the passed array. I am handling validations i.e. If both arrays have the different number of indexes. And if any index in the array has different length string/data.
https://gist.github.com/tanmay27vats/5727b3e37cda65a68e87abfdb3f8f9a7