循环内移动阵列

Shifting array within loop

本文关键字:阵列 移动 循环      更新时间:2023-09-26

我有一个数组,我想移动它n次并返回一个新的移位数组数组。

如 [1,2,3,4] 变成

[[ 1, 2, 3, 4 ],
[ 2, 3, 4, 1 ],
[ 3, 4, 1, 2 ],
[ 4, 1, 2, 3 ],
[ 1, 2, 3, 4 ],
[ 2, 3, 4, 1 ],
...

function dataShift(len, inp){
var row = inp;
var rows = [];
for (var i=0;i<len;i++) {
    row.push(row.shift());
    rows.push(row);
    console.log(rows[i]);
}
return rows;
}
console.log(dataShift(5,[1,2,3,4]));

console.log(rows[i])将打印所需的结果,但是console.log(dataShift(5,[1,2,3,4]))仅包含原始数组的最后一次排列len次。

怎样才能达到我想要的结果?

function dataShift(len, inp){
var row = inp;
var rows = [];
for (var i=0;i<len;i++) {
    row.push(row.shift());
    var new1 = row.slice(0,len);
    rows.push(new1);
}
return rows;
}
console.log(dataShift(5,[1,2,3,4]));

var new1 = row.slice(0, len)线是魔力所在。 row.slice创建一个新的数组对象。

您之前的方法(直接推送)最终会生成一个指向同一对象的对象引用数组。因此,当您修改对象时,所有引用都会更新。

如果您不想使用slice(),另一种方法是使用 JSON.parse(JSON.stringify(row))

public static int [] leftSwap(int [] arr, int n) {
        int l = arr.length;
        int [] result = new int[l];
        int  m = 0 ;
        int criticalIndex = l - n ;
        for(int i = 0 ; i <result.length  ; i++) {
            if(i < criticalIndex) {
                result[i] = arr[n];
                n++;
            }
            else {
                result[i] = arr[m];
                        m++;
            }
        }
        return result;
    }