I need your help with the following: I'm trying to develop a function that is supposed to check whether two argument strings are rotationally equal to each other. Like, 'abcd' would become 'cdab' if we rotate that clockwise twice, so my function is supposed to return 'true' if the above strings are supplied as arguments. My initial idea to solve this was to check whether the constant shift between each character in both strings exists, so I tried
function areRotEq (str1, str2) {
var shift = null;
for(char of str1){
if(!shift) shift = str2.indexOf(char);
else if (shift != str2.indexOf(char)) return false
}
return true;
}
But, it fails to evaluate even the above simple strings properly and returns 'false'. If you could point me to the right direction to figure out why my code is not working or maybe suggest some more effective method to solve my problem that would be much appreciated. Thank you in advance!
Here's an alternative approach:
First, do the "quick" checks that are absolutely true or false.
Then, check for the first char of str1 in str2. Split it at this point and paste the first part behind the last. If the two are equal, they are rotational.
warning: this won’t work for strings that contain the same character multiple times.
function areRotEq (str1, str2) {
if (str1 === str2) return true;
if (str1.length !== str2.length) return false;
var start2 = str2.indexOf(str1[0]);
if (start2 === -1) return false;
return str1 === str2.slice(start2) + str2.slice(0, start2)
}
console.log(
areRotEq("abcd", "abcd"),
areRotEq("abcd", "acdb"),
areRotEq("abcd", "dabc"),
areRotEq("dcab", "abdc")
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With