在阵列中绘制六边形

问题描述 投票:2回答:1

我需要编写一个将如下所示的六边形绘制到2d数组中的函数。我只知道数组的列大小,其余的都需要计算。

enter image description here

但是,我正在努力解决其背后的数学问题。

这是我到目前为止编码的内容:

function deg2rad(degrees) {
  const pi = Math.PI;
  return degrees * (pi / 180);
}

function getCos(deg) {
  return Math.cos(deg2rad(deg));
}


function drawHexagon(cols) {
  // upper left corner
  const rows = parseInt(cols * getCos(30), 10);

  const arr = [...Array(rows)].map(() => Array(cols).fill(''));
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (j > Math.floor(cols / 4) - 1 && j < (cols - Math.round(10 / 4))) { // middle section (square)
        arr[i][j] = 1;
        continue;
      }

      if (i < Math.floor(rows / 2)) { // top half

        if (j < Math.floor(cols / 4)) { // left side (triangle)
          if (rows / 2 / (i + 1) < cols / 4 / (cols / 4 - j)) { // seems to be right
            arr[i][j] = 2;
          }
        } else { // right side (triangle)
          if (rows / (i + 1) < cols / (j / 4 + 1)) { // wrong
            arr[i][j] = 2;
          }
        }
      } else { // bottom half

        if (j < Math.floor(cols / 4)) { // Left side
          if (rows / (i + 1) > cols / 4 / (j + 1)) { // seems to be right
            arr[i][j] = 2;
          }
        } else { // bottom right 
          if (rows / 2 / (i + 1) > cols / 4 / (cols - j)) { // wrong
            arr[i][j] = 2;
          }
        }
      }
    }
  }
  console.log(arr); // console.table() not available in snippet
  return arr;
}
drawHexagon(8)

输出数组会给我这个:

enter image description here

所以左侧和中间部分似乎是正确的。

[如果有人能帮助我解决这个问题,我会感到非常高兴。

javascript arrays math trigonometry
1个回答
0
投票

有两个问题,第一个是Math.sin()Math.cos()返回的结果带有一些f 浮点误差,因此计算不稳定。

第二个是几何计算,您忘记了斜边,如图所示该三角形必须是直角三角形。

enter image description here

解决方案:

1-计算<的长度,然后得到斜边(c)并进行检查。

2-如果

a²+b²=c²

,则(a,b,c)是有效边,否则得到最接近的边成直角三角形。3-将数组内的点设置为2d网格(

如上图

)。4-

连接点

。我猜想,最是获得最短路径,如这些图和线之间的正常连接,最短路径是线本身。5-返回包含路径的数组,然后使用路径数组为网格中的每个单元格分配值

这里链接包含我的实现,但是(没有最短路径功能,我将该功能留空了)

Javascript-Code

© www.soinside.com 2019 - 2024. All rights reserved.