【问题标题】:Adding values from HashSet to 2D Matrix将 HashSet 中的值添加到 2D 矩阵
【发布时间】:2017-04-22 12:29:26
【问题描述】:

我有一个 Map 结构,其中包含一个 Integer 作为键和一组 Objects 作为值。但是,我已经重写了 toString 方法来获取值的整数值。因此,例如,地图看起来像

Key: 1 Values: [1, 2, 4]

我在用这个地图结构构建一个 2D 矩阵时遇到了一些麻烦。当我循环时,我正在检查我的迭代器值是否是 Map 中的一个键,但我无法检查第二个迭代器是否等于设定值。这是有问题的代码部分

for (int i = 1; i < this.adjacencyMatrix[0].length; i++) {
    System.out.print(i + " ");
}
System.out.println();
for (int i = 1; i < this.adjacencyMatrix.length; i++) {
    System.out.print(i + " ");
    for (int j = 1; j < this.adjacencyMatrix[i].length; j++) {
        if (this.nodes.containsKey(i)) {
            // Handle the set
            this.adjacencyMatrix[i][j] = 1;
        } else {
            this.adjacencyMatrix[i][j] = 0;
        }
        System.out.print(this.adjacencyMatrix[i][j] + " ");
    }
    System.out.println();
}

我的矩阵现在将为整行映射键打印 1。

例如,如果 4 是一个键,则整个 10 行都将打印 1。但是,假设我有一个像 4 这样的映射-- [1, 2, 4] 只有 1, 2, 4 在给定行,其余的都应该是 0。

【问题讨论】:

    标签: java arrays matrix set


    【解决方案1】:

    对于内部循环的每个步骤,if-condition (containsKey) 为真(或假)。

    内部循环应该替换为两个循环:首先循环索引j并将所有值初始化为0。然后迭代节点集中的元素,取每个值并将其用作索引:

    adjacencyMatrix[i][value] = 1
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多