#include
#include
#define MAX_TERMS 100
typedef struct {
int row;
int col;
int value;
}element;
typedef struct SparseMatrix {
element data[MAX_TERMS];
int rows;
int cols;
int terms;
}SparseMatrix;
void matrix_print(SparseMatrix a);
SparseMatrix matrix_copy(SparseMatrix a);
int main()
{
SparseMatrix m = {
{ { 0, 3, 7 },{ 1, 0, 9 },{ 1, 5, 8 },{ 3, 0, 6 },{ 3, 1, 5 },{ 4, 5, 1 },{ 5, 2, 2 } },
6,
6,
7
};
SparseMatrix result;
result = matrix_copy(m);
matrix_print(result);
return 0;
}
void matrix_print(SparseMatrix a)
{
int aindex = 0;
printf("===================\n"); // 문제는 프린트
for (int r = 0; r < a.rows; r++) {
printf("|");
for (int c = 0; c < a.cols; c++) {
if (a.data[aindex].col == c && a.data[aindex].row == r) {
printf(" %d |", a.data[aindex].value);
aindex++;
}
else {
printf(" 0 |");
}
}
printf("\n");
}
printf("===================\n");
}
SparseMatrix matrix_copy(SparseMatrix a)
{
SparseMatrix b;
int bindex = 0;
b.rows = a.rows;
b.cols = a.cols;
b.terms = a.terms;
if (a.terms > 0 ) {
for (int c = 0; c < a.cols; c++) {
for (int i = 0; i < a.terms; i++) {
if (a.data[i].col == c) {
b.data[bindex].row = a.data[i].row;
b.data[bindex].col = a.data[i].col;
b.data[bindex].value = a.data[i].value;
bindex++;
}
}
}
}
return b;
}
위에 이건 희소행렬의 (행,열,값)을 받아서 0이 포함된 원래 행렬을 출력하는 전체 코드고요
문제가 있다고 추청되는 부분은
for (int r = 0; r < a.rows; r++) {
printf("|");
for (int c = 0; c < a.cols; c++) {
if (a.data[aindex].col == c && a.data[aindex].row == r) {
printf(" %d |", a.data[aindex].value);
aindex++;
}
else {
printf(" 0 |");
}
}
printf("\n");
}
여기(프린트하는 부분)입니다
원래
0 0 0 7 0 0
9 0 0 0 0 8
0 0 0 0 0 0
6 5 0 0 0 0
0 0 0 0 0 1
0 0 2 0 0 0
이렇게 출력하고 싶은데
0 0 0 0 0 0
9 0 0 0 0 0
0 0 0 0 0 0
6 5 0 0 0 0
0 0 0 0 0 0
0 0 2 0 0 0
이렇게 자꾸 4열부터 누락이 생기네요
이렇게 오래걸릴지 모르고 지금까지 붙잡고 있었네요 살려주세요 ㅠㅠ