我正在尝试将两个不同的稀疏组合添加到一起来实现一个大矩阵,其中包含来自另一个矩阵的所有值。但是如果它们都具有特定键的值,则应将这些值加在一起。我无法弄清楚的是如何引用正在创建的新矩阵,以便我可以将新值放入其中然后返回。
答案 0 :(得分:0)
我建议这样的事情 - 注意这是未经测试的代码。
public static SparseMatrix add(SparseMatrix a, SparseMatrix b) {
if (a.rows != b.rows || a.cols != b.cols) {
// They must be the same dimensions.
return null;
}
return new SparseMatrix(a.rows, a.cols).add(a).add(b);
}
private SparseMatrix add(SparseMatrix a) {
// Walk all of his.
for (Integer i : a.matrix.keySet()) {
// Do I have one of these?
if (matrix.containsKey(i)) {
// Yes! Add them together.
TreeMap<Integer, Double> mine = matrix.get(i);
TreeMap<Integer, Double> his = a.matrix.get(i);
// Walk all values in there
for (Integer j : his.keySet()) {
// Do I have one of these?
if (mine.containsKey(j)) {
// We both have this one - add them.
mine.put(j, mine.get(j) + his.get(j));
} else {
// I do not have this one.
mine.put(j, his.get(j));
}
}
} else {
// I do not have any of these - copy them all in.
matrix.put(i, new TreeMap(a.matrix.get(i)));
}
}
return this;
}