Skip to content

Instantly share code, notes, and snippets.

@mmloveaa
Last active April 4, 2016 17:21
Show Gist options
  • Select an option

  • Save mmloveaa/23e3602c9e4ab10482aa8e58d0427c4f to your computer and use it in GitHub Desktop.

Select an option

Save mmloveaa/23e3602c9e4ab10482aa8e58d0427c4f to your computer and use it in GitHub Desktop.
4-4 morning challenge
All Rotations
Complete the function containsAllRotations that will determine if all rotations of a given string are found in a given array of strings. That array will be unordered, and there may be extra unneeded strings in there as well.
To rotate a string, move the first character to the end of the string. You may continue this process to see all possible rotations. ex: 'dog' --> 'ogd' --> 'gdo'
Note: The original un-rotated string must also be found in the array, as it is a possible rotation.
Input Format:
The function will have two arguments:
str - a string.
arr - an array of strings.
Output Format:
The function will return a boolean. If arr includes every possible rotation of str, the function will return true.
Sample Input 1:
str: 'cat'
arr: ['atc', 'cat', 'fish', 'tca']
Sample Output 1:
true
Explanation: All rotations of the string 'cat' are in the array.
Sample Input 2:
str: 'cherry'
arr: ['rycher', 'errych', 'cherry', 'rryche', 'herryc', 'sherry']
Sample Output 2:
false
Explanation: The string 'ycherr' is missing.
Solution:
function containsAllRotations(str, arr) {
for(var i=0; i<str.length; i++) {
str = str.slice(1) + str.charAt(0);
if(arr.indexOf(str) === -1) {
return false;
}
}
return true;
}
containsAllRotations('cat', ['atc', 'cat', 'fish', 'tca'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment