Last active
January 6, 2024 17:19
-
-
Save k0ff33/3029d30fb4ae62a72b0c54f2cb39893d to your computer and use it in GitHub Desktop.
Cyclic Rotation Exercise from Codility (JavaScript/NodeJS)
This file contains hidden or 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
/** | |
* Shift items in the array to the right by number of indexes | |
* @param {array} A | |
* @param {int} K | |
* @return {array} | |
*/ | |
function solution(A, K) { | |
// if A is meant to be shifted by its own length (K) then just return the array | |
if (A.length === K || K === 0) { | |
return A | |
} | |
// Run K number of times saving last element in the array as a temporary variable, adding it to the front of the array and removing the last element | |
for (let i = 0; i < K; i++) { | |
let lastElement = A[A.length - 1] | |
A.unshift(lastElement) | |
A.pop() | |
} | |
return A | |
} |
This is my solution for 100%
function solution(A, K) {
const size = A.length // sets length
if(K>size) K = (K - (size*(Math.floor(K/size)))) // simplifies rotation (also realized you could do k = k % size)
if(size === 0) return []; // if the string is empty return it as is
const insertLeft = A.slice(-1 * K)
const rotateRight = A.slice(0, -1 * K)
const result = insertLeft.concat(rotateRight)
return result
}
My solution
function solution(A, K) { // edge case destroyer if (A.length === 0 || A.length === K || K === 0) return A; let finalArr = A; // add characters to the start of finalArr for (let i = 0; i < K; i++) { finalArr.unshift(A[A.length - 1 - i]); } // assign sliced array to variable finalArr = finalArr.slice(0, -K); console.log(finalArr); // return sliced array return finalArr; }
Solution from elendil7 fail performance tests
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My solution