javascript - 给定一个多维数组,返回一个包含对 Angular 线总和的数组

标签 javascript arrays algorithm math

给定一个多维数组,返回一个包含对 Angular 线之和的数组。

例如:

input:
  [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ]

output:

[ 7, 12, 15, 8, 3 ]

function addDiagonals(matrix) {
  let sum = 0;
  let j = matrix[0].length - 1;
  for (let i = 0; i < matrix.length; i++, j--) {
    sum += matrix[i][j];
    sum += matrix[i][i];
  }
  return sum;
}

console.log(addDiagonals([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]));

我能够求出对 Angular 线的总和。但我需要知道如何计算每条对 Angular 线的总和。

但我需要完成这个:

function diagonalSum(matrix) {
  let sum = 0;
  let res = [];
  for (let i = 0; i < matrix.length; i++) {
    let j = matrix.length - i - 1;

    res[i] = matrix[i][j];



    console.log(`i = ${i} and j = ${j};`)
  }
  return res;
}
console.log(diagonalSum([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]));

最佳答案

首先创建一个初始数字数组(用于对 Angular 线和),然后使用 reduce迭代,使用 x 索引和 y 索引以及数组长度来找出当前数字应添加到的正确对 Angular 线索引:

const input = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

const { length } = input;
const initial = new Array(length * 2 - 1).fill(0);
const output = input.reduce((a, subArr, y) => {
  subArr.forEach((item, x) => {
    const diagIndex = x - y + length - 1;
    a[diagIndex] += item;
  });
  return a;
}, initial);

console.log(output);

另一个 4x4 数组的例子:

const input = [
  [1, 2, 3, 9],
  [4, 5, 6, 9],
  [7, 8, 9, 9],
  [2, 2, 2, 2]
];

const { length } = input;
const initial = new Array(length * 2 - 1).fill(0);
const output = input.reduce((a, subArr, y) => {
  subArr.forEach((item, x) => {
    const diagIndex = x - y + length - 1;
    a[diagIndex] += item;
  });
  return a;
}, initial);

console.log(output);

推导

const diagIndex = x - y + length - 1;

是:作为y (列索引)增加,如果 x (行索引)保持不变,diagIndex应该减少,因为您越来越接近输出总和数组的左下角和索引 0。因此,在 const diagIndex = 的右侧, y是负的。作为x增加,如果 y保持不变,diagIndex应该增加,因为你离左下角越来越远,所以x右侧为正。

我们现在有

const diagIndex = x - y + num;

哪里num是别的东西

我们也知道在 x = 0y = <square length - 1> (左下角),对 Angular 线索引应该为0,所以:

diagIndex = x - y + num;
0 = 0 - (length - 1) + num
length - 1 = num

插入:

const diagIndex = x - y + num;
const diagIndex = x - y + (length - 1);

关于javascript - 给定一个多维数组,返回一个包含对 Angular 线总和的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54299711/

相关文章:

javascript - Polymer 1.0 中具有绑定(bind)的文本环绕元素

javascript:将 html 添加到 <span> 末尾(菜鸟)

arrays - 如何在 Snowflake SELECT 中展平一组 ARRAY_AGGS

c# - 如何在 C# 中创建相交链表?

c++ - 算法中令人费解的行为应该根据列表的项目创建 4 个列表

javascript - 如何在dojo中模拟无模式窗口对话框,以便我们可以打开多个窗口 Pane

Javascript:图像不会立即更新

php - Array Merge PHP不断创建子/维数组

c - 双重释放错误释放二维数组

algorithm - EM算法的贝叶斯信息准则计算