如何在JavaScript中对矩阵指定列的数值进行上下行偏移操作
原有代码问题
你现有代码的核心问题是采用了相邻元素两两交换的逻辑,遍历方向也不符合偏移需求,导致列元素移动结果和预期完全不符。
正确实现方案
我们可以分别封装向下偏移和向上偏移两个函数,逻辑如下:
列向下偏移逻辑
- 先存储指定列的最后一个元素,该元素会被挤出,作为新的
flip_value返回 - 从最后一行开始倒序遍历到第二行,将当前行指定列的取值替换为上一行同列的取值
- 将指定列的第一行取值替换为传入的
flip_value
列向上偏移逻辑
- 先存储指定列的第一个元素,该元素会被挤出,作为新的
flip_value返回 - 从第一行开始正序遍历到倒数第二行,将当前行指定列的取值替换为下一行同列的取值
- 将指定列的最后一行取值替换为传入的
flip_value
完整可运行代码
// 测试用原始矩阵 let matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]; let Yindex = 1; let flip_value = 999; const size = matrix.length; // 指定列向下偏移1位函数,返回新的flip_value function shiftColumnDown(matrix, colIndex, flipVal) { const rowCount = matrix.length; // 保存被挤出的最后一个元素 const pushedOut = matrix[rowCount - 1][colIndex]; // 倒序遍历赋值 for (let i = rowCount - 1; i >= 1; i--) { matrix[i][colIndex] = matrix[i - 1][colIndex]; } // 首位置替换为传入的flipVal matrix[0][colIndex] = flipVal; return pushedOut; } // 指定列向上偏移1位函数,返回新的flip_value function shiftColumnUp(matrix, colIndex, flipVal) { const rowCount = matrix.length; // 保存被挤出的第一个元素 const pushedOut = matrix[0][colIndex]; // 正序遍历赋值 for (let i = 0; i < rowCount - 1; i++) { matrix[i][colIndex] = matrix[i + 1][colIndex]; } // 尾位置替换为传入的flipVal matrix[rowCount - 1][colIndex] = flipVal; return pushedOut; } // 测试向下偏移 console.log("===== 测试向下偏移 ====="); flip_value = shiftColumnDown(matrix, Yindex, flip_value); console.log("新的flip_value:", flip_value); // 输出14,符合预期 console.log("偏移后矩阵:"); matrix.forEach(row => console.log(row)); // 重置矩阵测试向上偏移 matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ]; flip_value = 999; console.log("\n===== 测试向上偏移 ====="); flip_value = shiftColumnUp(matrix, Yindex, flip_value); console.log("新的flip_value:", flip_value); // 输出2,符合预期 console.log("偏移后矩阵:"); matrix.forEach(row => console.log(row));
运行结果验证
- 向下偏移后第二列值为
[999,2,6,10],被挤出值为14,完全匹配需求 - 向上偏移后第二列值为
[6,10,14,999],被挤出值为2,完全匹配需求
内容的提问来源于stack exchange,提问作者Sql4Life
相关产品推荐
相关产品推荐

