javascript - 移动二维数组中的行和列 - Javascript

标签 javascript arrays matrix 2d

我遇到这样的情况:

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 循环,但我很难弄清楚这一点。请记住,我只编码了几个月。

这就是我到目前为止所拥有的。它最后给了我一个未定义错误,并且它以错误的方式移动它。

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;
}

最佳答案

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

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

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);
}

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

关于javascript - 移动二维数组中的行和列 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40435302/

相关文章:

c# - 浏览器尝试连接和 Socket.Accept() 之间的长时间延迟 [~1s]

php - 拉维尔 5.4 : how to iterate through request array?

Python 数字递增矩阵

javascript - knockoutjs - 渲染模板或 foreach 到自身

javascript - Jquery 自动完成 - 当选择一个项目时光标移动到开头

javascript - 带标签的谷歌地图视网膜标记

arrays - 遍历二维数组

python - 在 python 中,如何删除 numpy 3d 数组中每第 n 个元素的一系列列?

arrays - 将数组与矩阵中的每一行进行比较(列数可能不同)

java - 从相机坐标计算世界坐标