简体   繁体   中英

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!

Here is a solution using recursion:

 function shiftArr(arr, n) { if (n<=0) { return arr; } else{ arr.unshift(arr.pop()); return shiftArr(arr,n-1) } } //test: console.log(shiftArr([1, 2, 3, 4, 5],2)); // [4, 5, 1, 2, 3]

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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM