如何获得垂直和对角线排列的数组元素?

问题描述

因此,我在这里有这个数组数组,我想做的是创建一个名为car的新数组,并从'array'中保存垂直对齐([0,4,8,12],[1,5,9,13] ...)以及对角线{{1} } 我该怎么办?

([0,10,15],6,11],[2,7],[3],[4,14] and so...)

解决方法

实际上,对于您期望的解决方案,我根本不会使用数组。

要查看游戏板上的一系列插针(例如井字棋或四连棋)是水平,垂直还是对角线连接,只需使用简单的代数即可:

在您的脑海中,请按照将每一行放在上一行旁边的方式来翻译木板,例如:

| 0 | 1 | 2 | 3 |
| 4 | 5 | 6 | 7 |   =>   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | ...
...

您会注意到,董事会的职位将简单地变成简单的指标。

在此示例中,索引1和索引5是垂直连接的,因为板的宽度为4。因此,垂直连接的引脚之间的距离始终是板子的宽度(即,如果板子的宽度是4,则1 + 4 = 5)。

因此,确定引脚是垂直,水平还是对角线连接的函数可能非常简单(我在这里使用了非常简单而冗长的实现作为演示目的。如果您的数学知识较高,请随时进行优化*) :

const _boardWidth = 4;

function isHorizontallyConnected(indexA,indexB)
{
  const rowA = Math.Floor(indexA / _boardWidth);
  const rowB = Math.Floor(indexB / _boardWidth);

  if (rowA === rowB && Math.Abs(indexB - indexA) === 1) return true;

  return false;
}

function isVerticallyConnected(indexA,indexB)
{
  const rowA = Math.Floor(indexA / _boardWidth);
  const rowB = Math.Floor(indexB / _boardWidth);
  const columnA = indexA % _boardWidth;
  const columnB = indexB % _boardWidth;

  if (columnA === columnB && Math.Abs(rowB - rowA) === 1) return true;

  return false;
}

function isDiagonallyConnected(indexA,indexB)
{
  ...
}

我将isDiagonallyConnected函数的实现留给您进行实验。


*例如,isVerticallyConnected函数的优化版本可以简单地为:return Math.Abs(indexB - indexA) === _boardWidth;