繁体   English   中英

遍历数组 n 次旋转项目

[英]Iterate through an array n number of times rotating items

我有一个像[1,2,3,4,5]这样的数组,我有像3这样旋转数组的总数。 因此,第一次旋转后,数组应该是[2,3,4,5,1] 这样,数组应该保持旋转 n 次,这是给定的。 我有一个旋转数组的解决方案,如下所示,但我不能这样做 n 次。 这是我所做的:

 function rotateLeft(arr, n) { var newArr = []; for( let i=1; i< arr.length; i++){ newArr.push(arr[i]); } newArr.push(arr[0]); console.log(newArr); } rotateLeft([1,2,3,4,5], 3);

在 while 循环内将数组的第一个元素推到末尾

 const original = [1,2,3,4,5]; console.log(`original: [${ original}], rotated: [${ rotateLeft(original, 3)}]`); function rotateLeft(arr, n) { // if you want to mutate the original arr // omit cloning const clone = [...arr]; while (n--) { clone.push(clone.shift()); }; return clone; }

由于您没有将数组旋转到位,而是创建一个新数组,因此您可以更简单地执行此操作:

 function rotateLeft(arr, n) { n %= arr.length; return [...arr.slice(n), ...arr.slice(0, n)]; } // generate an array with numbers const arr = [...Array(20).keys()]; console.log(...arr); // rotateLeft by 8 console.log(...rotateLeft(arr, 8)); // rotateLeft by -22 (rotateRight by 22) // since arr.length === 20 // same as rotateLeft by -2 // same as rotateLeft by 18 console.log(...rotateLeft(arr, -22));

暂无
暂无

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

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