Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two strings are rotationally equal to each other

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!

like image 539
s_tyagi Avatar asked Jan 27 '23 04:01

s_tyagi


1 Answers

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")
);
like image 96
user3297291 Avatar answered Feb 01 '23 12:02

user3297291