You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现代表二维网格的一维数组的翻转与旋转(附JS示例)

实现思路

一维数组存储的二维网格可以通过索引和坐标的转换实现所有变换,规则如下:

  • 已知一维索引idx,对应二维行号 r = Math.floor(idx / cols),列号 c = idx % cols
  • 已知二维坐标(r,c),对应一维索引 idx = r * cols + c

所有变换仅需做坐标映射即可,兼容奇偶行列数,也支持非正方形网格。

完整实现代码

let startingArray = 
                [true,  false, false,
                 true,  true,  true,
                 false, false, false];
let rows = 3;
let cols = 3;


function flipVertical(arrayToFlip){
  const flippedArray = new Array(arrayToFlip.length);
  for (let newIdx = 0; newIdx < flippedArray.length; newIdx++) {
    const newRow = Math.floor(newIdx / cols);
    const newCol = newIdx % cols;
    // 垂直翻转仅行号倒序,列号不变
    const originalRow = rows - 1 - newRow;
    const originalIdx = originalRow * cols + newCol;
    flippedArray[newIdx] = arrayToFlip[originalIdx];
  }
  return flippedArray;  
}

function flipHorizontal(arrayToFlip){
  const flippedArray = new Array(arrayToFlip.length);
  for (let newIdx = 0; newIdx < flippedArray.length; newIdx++) {
    const newRow = Math.floor(newIdx / cols);
    const newCol = newIdx % cols;
    // 水平翻转仅列号倒序,行号不变
    const originalCol = cols - 1 - newCol;
    const originalIdx = newRow * cols + originalCol;
    flippedArray[newIdx] = arrayToFlip[originalIdx];
  }
  return flippedArray;  
}

function rotate90Clockwise(arrayToRotate){
  const rotatedArray = new Array(arrayToRotate.length);
  // 顺时针旋转90度后行列数互换
  const newRows = cols;
  const newCols = rows;
  for (let newIdx = 0; newIdx < rotatedArray.length; newIdx++) {
    const newRow = Math.floor(newIdx / newCols);
    const newCol = newIdx % newCols;
    // 坐标映射规则
    const originalRow = rows - 1 - newCol;
    const originalCol = newRow;
    const originalIdx = originalRow * cols + originalCol;
    rotatedArray[newIdx] = arrayToRotate[originalIdx];
  }
  return rotatedArray ;  
}

上述代码运行输出和给出的预期结果完全一致。

内容的提问来源于stack exchange,提问作者Mark Taylor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 21:57:04