【问题标题】:Reduce multiple matrixes to single matrix and perform value addition将多个矩阵减少为单个矩阵并执行值加法
【发布时间】:2019-02-20 01:10:30
【问题描述】:

我在数据结构中有一个矩阵列表(数组),如下所示:

const data = [
  {
    matrix: {
      rows: {
        ROW1: {
          cols: {
            COL1: "4",
            COL2: "2"
          }
        },
        ROW2: {
          cols: {
            COL1: "1",
            COL2: "4"
          }
        },
        ROW3: {
          cols: {
            COL1: "2",
            COL2: "1"
          }
        }
      }
    },
  },
  {
    matrix: {
      rows: {
        ROW1: {
          cols: {
            COL1: "1",
            COL2: "6"
          }
        },
        ROW2: {
          cols: {
            COL1: "2",
            COL2: "3"
          }
        },
        ROW3: {
          cols: {
            COL1: "5",
            COL2: "2"
          }
        }
      }
    }
  }
];

我想总结在相同 ROW:COL 对中定义的值,并最终得到一个矩阵,如下所示:

const newMatrix = {
  rows: {
    ROW1: {
      cols: {
        COL1: "5",
        COL2: "8"
      }
    },
    ROW2: {
      cols: {
        COL1: "3",
        COL2: "7"
      }
    },
    ROW3: {
      cols: {
        COL1: "7",
        COL2: "3"
      }
    }
  }
};

我事先不知道我可能在数据数组中收到多少个矩阵。我也不知道我收到了多少行和列。

我一开始对数据调用 reduce(),但由于我想不出一种方法来查找并总结 ROW:COL 同名对中的数据。

const newMatrix = data.reduce(( accumulator, current ) => {
  let newMatrix;
  // ...???
  // find? forEach? Object.entries? for loops? maps inside maps? 
  // Everything I tried failed
  return newMatrix;
});

我还搞砸了 forEach()、Object.values()、find() 和其他循环中的各种 for 循环,但我自己总是陷入某种大脑循环。

我意识到这可能还不够,但我是编程新手,不知道下一步该去哪里。

我在这个问题上已经被困了 2.5 天,所以即使没有提供直接的解决方案,我也会感谢任何正确方向的提示或指导。

很遗憾,我没有可以寻求帮助的同龄人。

谢谢。

【问题讨论】:

  • 它是否适用于 ROW3 与 ROW1 和 ROW2 具有不同结构(不被 {} 包围)?
  • @samabcde 不,我的错。结构应该一致。现已更正。
  • 还是发现你提供的脚本有语法错误,请检查结构是否正确。
  • @samabcde 它出现在我使用}而不是]关闭它的数据数组中,现在也更正了。
  • rows 只包含 ROW1,对吗?行:{ ROW1:{ cols:{ COL1:“5”,COL2:“8”}}},{ ROW2:{ cols:{ COL1:“3”,COL2:“7”}}},

标签: javascript dictionary matrix reduce


【解决方案1】:

您可以尝试遍历对象的键,并在执行过程中添加值来构建最终结果。

const data = [
    {
        matrix: {
            rows: {
                ROW1: {
                    cols: {
                        COL1: "4",
                        COL2: "2"
                    }
                },
                ROW2: {
                    cols: {
                        COL1: "1",
                        COL2: "4"
                    }
                },
                ROW3: {
                    cols: {
                        COL1: "2",
                        COL2: "1"
                    }
                }
            }
        },
    },
    {
        matrix: {
            rows: {
                ROW1: {
                    cols: {
                        COL1: "1",
                        COL2: "6"
                    }
                },
                ROW2: {
                    cols: {
                        COL1: "2",
                        COL2: "3"
                    }
                },
                ROW3: {
                    cols: {
                        COL1: "5",
                        COL2: "2"
                    }
                }
            }
        }
    }
];

const sumMatrices = (array) => {

    const summed = { matrix: { rows: {} }};

    array.forEach((item) => {

        Object.keys(item.matrix.rows).forEach((row) => {

           if (!summed.matrix.rows[row]) summed.matrix.rows[row] = { cols: {} };

           Object.keys(item.matrix.rows[row].cols).forEach((col) => {

               if (!summed.matrix.rows[row].cols[col]) summed.matrix.rows[row].cols[col] = 0;

               summed.matrix.rows[row].cols[col] += +item.matrix.rows[row].cols[col];
           });
       });
    });

    return summed;
};  

console.log(sumMatrices(data));

【讨论】:

    【解决方案2】:

    你必须反过来做,这意味着循环列,然后是行,然后是矩阵。以下代码有详细的解决方案。

        function sumMatrices(data)
        {
            // if data empty or has missing fileds, return null
            if(
                !data || 
                !data[0].matrix.rows ||
                !data[0].matrix.rows.ROW1.cols ||
                data.length == 0 || 
                Object.keys(data[0].matrix.rows).length == 0 ||
                Object.keys(data[0].matrix.rows.ROW1.cols).length == 0)
            {
                return null; 
            }
        
            // else sum and return the result matrix
            else
            {
                // Get matrix, row, and column counts
                let numOfMatrices =  data.length;
                let numOfRows = Object.keys(data[0].matrix.rows).length;
                let numOfCols = Object.keys(data[0].matrix.rows.ROW1.cols).length;
        
                // Copy matrix structure 
                let result = JSON.parse(JSON.stringify(data[0]));
        
                // Fields base names to be addressed
                let rowWord = 'ROW';
                let colWord = 'COL';
        
                // Loop in reverse: columns -> rows -> matrices 
                for (colNum = 1; colNum < numOfCols+1; colNum++){
                    let currentCol = colWord + colNum;
    
                    for (rowNum=1; rowNum<numOfRows+1; rowNum++){
                        let currentRow = rowWord + rowNum;
                        let sum = 0;
    
                        for (matrixNum = 0; matrixNum < numOfMatrices; matrixNum++) {
                            sum += parseInt(data[matrixNum].matrix.rows[currentRow].cols[currentCol]);
                        }
                        result.matrix.rows[currentRow].cols[currentCol] = "" + sum;
                    }
                }
                console.log(result);
                return result;
            }
        }   
        
        
        const data = [
        {
          matrix: {
            rows: {
              ROW1: {
                cols: {
                  COL1: "4",
                  COL2: "2"
                }
              },
              ROW2: {
                cols: {
                  COL1: "1",
                  COL2: "4"
                }
              },
              ROW3: {
                cols: {
                  COL1: "2",
                  COL2: "1"
                }
              }
            }
          },
        },
        {
          matrix: {
            rows: {
              ROW1: {
                cols: {
                  COL1: "1",
                  COL2: "6"
                }
              },
              ROW2: {
                cols: {
                  COL1: "2",
                  COL2: "3"
                }
              },
              ROW3: {
                cols: {
                  COL1: "5",
                  COL2: "2"
                }
              }
            }
          }
        }
      ];
    
       sumMatrices(data);

    【讨论】:

      【解决方案3】:

      由于行数和列数不是静态的,因此将应用递归函数来获取总和,而无需假设列或行属性名称。

      const data = [{
          matrix: {
            rows: {
              ROW1: {
                cols: {
                  COL1: "4",
                  COL2: "2"
                }
              },
              ROW2: {
                cols: {
                  COL1: "1",
                  COL2: "4"
                }
              },
              ROW3: {
                cols: {
                  COL1: "2",
                  COL2: "1"
                }
              }
            }
          },
        },
        {
          matrix: {
            rows: {
              ROW1: {
                cols: {
                  COL1: "1",
                  COL2: "6"
                }
              },
              ROW2: {
                cols: {
                  COL1: "2",
                  COL2: "3"
                }
              },
              ROW3: {
                cols: {
                  COL1: "5",
                  COL2: "2"
                }
              }
            }
          }
        }
      ];
      
      var result = {};
      var sum = function(from, to) {
      
        var keys = Object.keys(from);
      
        for (let i = 0; i < keys.length; i++) {
          if (to[keys[i]] === undefined) {
            to[keys[i]] = from[keys[i]];
          } else {
            if (typeof from[keys[i]] === "object") {
              sum(from[keys[i]], to[keys[i]])
            } else {
              to[keys[i]] = parseInt(from[keys[i]]) + parseInt(to[keys[i]]);
            }
          }
        }
      };
      
      
      for (index in data) {
        sum(data[index], result);
      }
      
      console.log(result);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-17
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-04
        相关资源
        最近更新 更多