typedef struct {
int row;
int col;
int value;
} element;
typedef struct SparseMatrix {
element data[MAX_TERMS];
int rows; // 행의 개수
int cols; // 열의 개수
int terms; // 항의 개수
} SparseMatrixType;
SparseMatrixType sparse_matrix_add2(SparseMatrixType a, SparseMatrixType b)
{
SparseMatrixType c;
int ca = 0, cb = 0, cc = 0;
c.rows = a.rows;
c.cols = a.cols;
c.terms = 0;
while (ca < a.terms && cb < b.terms) {
// 각 항목의 순차적인 번호를 계산한다.
int inda = a.data[ca].row * a.cols + a.data[ca].col;
int indb = b.data[cb].row * b.cols + b.data[cb].col;
if (inda < indb) {
c.data[cc++] = a.data[ca++];
}
else if (inda == indb) {
c.data[cc].row = a.data[ca].row;
c.data[cc].col = a.data[ca].col;
c.data[cc++].value = a.data[ca++].value +
b.data[cb++].value;
}
else
c.data[cc++] = b.data[cb++];
}
for (; ca < a.terms; ca++)
c.data[cc++] = a.data[ca++];
for (; cb < b.terms; cb++)
c.data[cc++] = b.data[cb++];
c.terms = cc;
return c;
}
main(){
SparseMatrixType m1 = { { { 1,1,5 },{ 2,2,9 } }, 3,3,2 };
SparseMatrixType m2 = { { { 0,0,5 },{ 2,2,9 } }, 3,3,2 };
SparseMatrixType m3;
m3 = sparse_matrix_add2(m1, m2);
}
코드는 몇개 빼고 쓴거긴 한데 빨갛게 표시해놓은 저 부분이 이해가 안됨 특히 inda 구하는 공식이 왜 저렇게 되는건지
댓글 0