Java 添加两个sparsematrix树映射
我试图把两个不同的稀疏矩阵加在一起,得到一个大矩阵,其中包含来自另一个矩阵的所有值。但是,如果它们在特定键上都有一个值,则应将这些值相加。我不知道如何引用正在创建的新矩阵,以便将新值放入其中,然后返回。我建议这样做-注意,这是未经测试的代码Java 添加两个sparsematrix树映射,java,treemaps,Java,Treemaps,我试图把两个不同的稀疏矩阵加在一起,得到一个大矩阵,其中包含来自另一个矩阵的所有值。但是,如果它们在特定键上都有一个值,则应将这些值相加。我不知道如何引用正在创建的新矩阵,以便将新值放入其中,然后返回。我建议这样做-注意,这是未经测试的代码 public static SparseMatrix add(SparseMatrix a, SparseMatrix b) { if (a.rows != b.rows || a.cols != b.cols) { // They must b
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;
}
publicstaticsparsematrix添加(SparseMatrix a,SparseMatrix b){
如果(a.rows!=b.rows | | a.cols!=b.cols){
//它们的尺寸必须相同。
返回null;
}
返回新的SparseMatrix(a.rows,a.cols);
}
专用SparseMatrix添加(SparseMatrix a){
//走他所有的路。
对于(整数i:a.matrix.keySet()){
//我有这个吗?
if(矩阵式容器(i)){
//是的!把它们加在一起。
TreeMap mine=matrix.get(i);
树映射his=a.matrix.get(i);
//把所有的价值观都放进去
for(整数j:his.keySet()){
//我有这个吗?
if(矿山集装箱(j)){
//我们都有一个-添加它们。
我的。放(j,我的。得到(j)+他的。得到(j));
}否则{
//我没有这个。
我的放(j,他的)得(j);;
}
}
}否则{
//我没有这些,都抄进去。
matrix.put(i,新树映射(a.matrix.get(i));
}
}
归还这个;
}