简体   繁体   English

在 JavaScript 中使用递归将数组元素移动到不同的位置

[英]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.我知道这个问题已经被问了很多,但我还没有找到一个在 JavaScript(很多 Java 和 C++)中使用递归而不是新/旧索引拼接的解决方案。 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) );如果它是 0,则完整地返回数组(或者可能用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]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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