Jacob Coons
Jacob Coons

Reputation: 1

Using Recursion in JavaScript to shift Array elements to different positions

I know this question has been asked a lot, but I've yet to find a solution that is in JavaScript (a lot of Java and C++) using recursion, and not new/old index splicing. This is merely an exercise and I'm not great at recursion, so any assistance and a thorough explanation would be greatly appreciated.

//given an array, shift all elements within the array forward 2 positions.
// [1, 2, 3, 4, 5] --> [4, 5, 1, 2, 3]

My first line of thought was to use a placeholder of some sort but I'm not sure what to do with it exactly. This is what I have so far

let array = [1, 2, 3, 4, 5];

function shiftTwo (arr) {
  for (i=0; i<arr.length; i++) {
    let curr = arr[0];
  }
}

Thanks in advance!

Upvotes: 0

Views: 541

Answers (2)

Eriks Klotins
Eriks Klotins

Reputation: 4180

Here is a solution using recursion:

function shiftArr(arr, n) { 
   if (n<=0) {        // If the array is to be shifted by <=0 positions
       return arr;    // return array
   } 
   else{  
       arr.unshift(arr.pop());  // take the last element of the arr (.pop()), and insert it at the beginning of the array (.unshift())
       return shiftArr(arr,n-1) // repeat recursively until n==0
   }
}

//test:
console.log(shiftArr([1, 2, 3, 4, 5],2));   // [4, 5, 1, 2, 3]

Upvotes: 2

Scott Sauyet
Scott Sauyet

Reputation: 50807

One possibility is to recur on the number of spaces to move. If it's 0, return the array intact (or possibly clone it with arr.slice(0)); otherwise, shift the last entry to the front and recur with one less. The code might look like this:

const shiftRight = (n, arr) =>
  n <= 0
    ? arr
    : shiftRight (n - 1, [...arr.slice(-1), ...arr.slice(0, -1)])
      

console .log (shiftRight (2, [1, 2, 3, 4, 5]))

Upvotes: 2

Related Questions