在2D Javascript中移动行和列

Shifting rows and columns in 2D Javascript

本文关键字:移动 2D Javascript      更新时间:2023-09-26

我有这样一个情况:

var array = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
]

我正在尝试创建一个函数,移动无论是行或列,所以结果将是:

shiftRow(array, 1) 
[
  [3,1,2],
  [4,5,6],
  [7,8,9]
]
shiftColumn(array,1)
[
  [7,2,3],
  [1,5,6],
  [4,8,9]
]

我希望第一个数字是最后一个数字,然后在任何情况下从那里继续。我已经尝试了几个嵌套的for循环,并且我在解决这个问题上相当困难。请记住,我只写了几个月的代码。

这是我目前所知道的。它在最后给了我一个undefined错误,它正在以错误的方式移动它。

function shiftRow(arr) {
  var temp = arr
  for(var i = 0; i < temp.length; i++) {
    for(var j = 0; j < temp[i].length; j++) {
      temp[i][j] = temp[i][j+1]
    }
  }
  return temp;
}

前面的答案看起来不错,但是在处理数组索引时缺少一个主要的东西;验证检查。

你不想尝试访问不存在的数组索引。因此,我创建了一个小类来根据需要移动数组,并进行了验证。如果行或列索引无效,将抛出Error

class ArrayShifter {
    static showArray(array) {
        // console.log("Array : ", array);
        console.log('------');
        for (const [index, elem] of array.entries()) {
            console.log(''+elem);
        }
    }
    static validateRowIndex(array, rowIndex) {
        if (!isArray(array) || !isInt(rowIndex) || rowIndex <= 0 || rowIndex > array.length) {
            throw new Error('The row index is wrong');
        }
    }
    static validateColumnIndex(array, columnIndex) {
        if (!isArray(array) || !isInt(columnIndex) || columnIndex <= 0 || columnIndex > array[0].length) {
            throw new Error('The column index is wrong');
        }
    }
    static shiftRow(array, rowIndex) {
        ArrayShifter.validateRowIndex(array, rowIndex);
        array[rowIndex - 1].unshift(array[rowIndex - 1].pop());
        return array;
    }
    static shiftColumn(array, columnIndex) {
        ArrayShifter.validateColumnIndex(array, columnIndex);
        let prev = array[array.length - 1][columnIndex - 1];
        for (const elem of array) {
            let tmp = elem[columnIndex - 1];
            elem[columnIndex - 1] = prev;
            prev = tmp;
        }
        return array;
    }
}
let sourceArray1 = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
];
let sourceArray2 = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
];
let controlArrayShiftRow = [
    [3,1,2],
    [4,5,6],
    [7,8,9],
];
let controlArrayColumnRow = [
    [7,2,3],
    [1,5,6],
    [4,8,9],
];
// arrayShifter.showArray(sourceArray1);
console.log(`Shift row test is ${areArraysEqual(controlArrayShiftRow, ArrayShifter.shiftRow(sourceArray1, 1))}.`);
// arrayShifter.showArray(sourceArray2);
console.log(`Shift column test is ${areArraysEqual(controlArrayColumnRow, ArrayShifter.shiftColumn(sourceArray2, 1))}.`);


//-------------------- Unimportant js functions --------------------
function isArray(arr) {
    if (Object.prototype.toString.call([]) === '[object Array]') { //Make sure an array has a class attribute of [object Array]
        //Test passed, now check if is an Array
        return Array.isArray(arr) || (typeof arr === 'object' && Object.prototype.toString.call(arr) === '[object Array]');
    }
    else {
        throw new Exception('toString message changed for Object Array'); //Make sure the 'toString' output won't change in the futur (cf. http://stackoverflow.com/a/8365215)
    }
}
function isInt(n) {
    return typeof n === 'number' && parseFloat(n) === parseInt(n, 10) && !isNaN(n);
}
function areArraysEqual(a1, a2) {
    return JSON.stringify(a1) == JSON.stringify(a2);
}

工作代码可以在这个代码中看到。

对于行移位,可以使用Array#unshiftArray#pop方法。为了移动列,使用Array#forEach方法和一个临时变量。

var array = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ],
  array1 = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ]
function shiftRow(arr, row) {
  arr[row - 1].unshift(arr[row - 1].pop());
  return arr;
}
function shiftCol(arr, col) {
  var prev = arr[arr.length - 1][col-1];
  arr.forEach(function(v) {
    var t = v[col - 1];
    v[col - 1] = prev;
    prev = t;
  })
  return arr;
}
console.log(shiftRow(array, 1))
console.log(shiftCol(array1, 1))

首先,必须传递两个参数:数组和要移动的行/列。记住数组是从0开始的,不是1。所以在你的例子中,如果你想要过滤第一行,你需要传递0,而不是1。

第二,因为你想把最后一个元素放在前面,把其他元素推到下面,你需要循环,对于shiftRow,从后到前。这里有一个解决方案。请随意改进。

function shiftRow(arr, row) {
  var temp = arr[row];
  var j=temp.length-1;
  var x=temp[j];
  for(var i = j; i > 0; i--) {
    temp[i]=temp[i-1];
  }
  temp[0]=x;
  arr[row]=temp;
}

正如您所看到的,它只在您想要移动的行上工作,并且从末尾开始,一直工作到前面。在循环之前,我保存最后一个元素(它将被覆盖),并将其放在循环末尾的第一个槽中。

给定这个问题:

有效地转置javascript数组

如果我们想要实现shiftCol

,只实现shiftRow并在其前后调换就足够了
function shiftRow(array,n)
{
  let retVal=[[]];
  for(i=0;i<array.length;i++)
  {
    if (i==n)
      retVal[i]= array[i].slice(1,array.length).concat(array[i][0]);
    else
      retVal[i]=array[i];
  }
  return retVal;
}