Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://www.hackerrank.com/challenges/circular-array-rotation/problem
- // mutative, works
- function circularArrayRotation(arr, rotations, arrOfQueries) {
- let rotationsToPerform = rotations % arr.length;
- const rotateArr = () => arr.unshift(arr.pop());
- while (rotationsToPerform > 0) {
- rotateArr();
- rotationsToPerform--;
- }
- let queryVals = [];
- arrOfQueries.forEach(query => {
- const val = arr[query];
- queryVals.push(val);
- });
- return queryVals;
- }
- // not mutative, times out
- function circularArrayRotation(arr, rotations, arrOfQueries) {
- let rotationsToPerform = rotations % arr.length;
- const returnRotatedColl = coll => {
- const newStart = coll.slice(coll.length - 1);
- const newEnd = coll.slice(0, coll.length - 1);
- const rotatedColl = [...newStart, ...newEnd];
- return rotatedColl;
- };
- while (rotationsToPerform > 0) {
- arr = returnRotatedColl(arr);
- rotationsToPerform--;
- }
- let queryVals = [];
- arrOfQueries.forEach(query => {
- const val = arr[query];
- queryVals = queryVals.concat(val);
- });
- return queryVals;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement