Advertisement
CLooker

Untitled

Jul 17th, 2018
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // https://www.hackerrank.com/challenges/circular-array-rotation/problem
  2.  
  3. // mutative, works
  4. function circularArrayRotation(arr, rotations, arrOfQueries) {
  5.   let rotationsToPerform = rotations % arr.length;
  6.   const rotateArr = () => arr.unshift(arr.pop());
  7.  
  8.   while (rotationsToPerform > 0) {
  9.     rotateArr();
  10.     rotationsToPerform--;
  11.   }
  12.  
  13.   let queryVals = [];
  14.  
  15.   arrOfQueries.forEach(query => {
  16.     const val = arr[query];
  17.     queryVals.push(val);
  18.   });
  19.  
  20.   return queryVals;
  21. }
  22.  
  23. // not mutative, times out
  24. function circularArrayRotation(arr, rotations, arrOfQueries) {
  25.   let rotationsToPerform = rotations % arr.length;
  26.   const returnRotatedColl = coll => {
  27.     const newStart = coll.slice(coll.length - 1);
  28.     const newEnd = coll.slice(0, coll.length - 1);
  29.     const rotatedColl = [...newStart, ...newEnd];
  30.     return rotatedColl;
  31.   };
  32.  
  33.   while (rotationsToPerform > 0) {
  34.     arr = returnRotatedColl(arr);
  35.     rotationsToPerform--;
  36.   }
  37.  
  38.   let queryVals = [];
  39.  
  40.   arrOfQueries.forEach(query => {
  41.     const val = arr[query];
  42.     queryVals = queryVals.concat(val);
  43.   });
  44.  
  45.   return queryVals;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement