DS assignment02 technical report

EB·2023년 9월 29일

자료구조 과제 🤓 A+기원🤓

1. sparse matrix transposition

#include<stdio.h>

#define ROWS 6
#define COLS 6
#define MAX_TERMS 10

defining rows, cols, and max terms as constant value to efficient program operation.

typedef struct {
	int row;
	int col;
	int value;
} element;

typedef struct SparseMatrix {
	element data[MAX_TERMS];
	int rows; //row size
	int cols; //cloumn size
	int terms; // the number of elemnets
}SparseMatrix;

defining two structures: 'element' and 'SparseMatrix.'

'element' represents a single element in a sparse matrix with attributes for its row, column, and value.

'SparseMatrix' is a structure for representing a sparse matrix and includes an array of 'element' objects, as well as attributes for the total number of rows, columns, and non-zero elements in the matrix.

void printMat(element data[]) {
	int k = 0, i, j;
	for (i = 0; i < ROWS; i++) {
		for (j = 0; j < COLS; j++) {
			if (data[k].row == i && data[k].col == j) {
				printf("%d ", data[k].value);
				k++;
			}
			else {
				printf("0 ");
			}
		}
		printf("\n");
	}
} //print out Matrix

Function printMat is takes an array of ‘element’ structures as its input parameter. This function is used to print a matrix.

  • it initializes an integer variable ‘k’ to 0, which is used to iterate through the ‘data’array.
  • It uses nested-for-loop to iterate through the rows and columns of a matrix, where constant values ‘ROWS’ and ‘COLS’ likely represent the
//void main()
SparseMatrix B = { {{0,3,7},{1,0,9},{1,5,8},{3,0,6},{3,1,5}, {4,5,1}, {5,2,2}}, ROWS, COLS, 7 };
//Add B as an input

	SparseMatrix result;
	element temp;
	int i, j, k = 0;

	result.cols = B.cols;
	result.rows = B.rows;
	result.terms = B.terms; //Initialize result

Declare and initialize variables.

  • SparseMatrix B : SparseMatrix struct containg the data array values given in question. The total number of rows and colums in the matrix is both 6. The number of non-zero elements in ‘B’ is 7.
  • SparseMatrix result : SparsMatrix struct designed to save the result . The initial vaule of cols, rows, and eterms are set to those of B. because the transposition Matrix of 6x6Matrix is the same size as the original one. The same gose for the number of non-zero elements.
  • element temp : element struct that will be used to sort the data array int the ‘result’.
for (i = 0; i < B.rows; i++) {
		for (j = 0; j < B.cols; j++) {
			if (B.data[k].row == i && B.data[k].col == j) {
				result.data[k].row = j;
				result.data[k].col = i;
				result.data[k].value = B.data[k++].value;
			}
		}
	}//Perform the transpose operation
  1. nested for-loop iterate through the rows and colums of the ‘B’ matrix, visiting each element in the matrix.
  2. if statement checks if the current element at index ‘k’in the ‘B.data’ array has a row and column index matches the current values of ‘i’and ‘j’. If they match, it means that there is non-zero element at this position in the ‘B’ matrix
  3. Inside the if block, the code assigns the column index ‘j’ to the ‘row’ attribute of the ‘result.data[k]’ element. Similarly, it assigns the row index ‘i’ to the ‘col’ attribute of the ‘result.data[k]’ element. Finally, it copies the ‘value’ attribute from the B matrix to the result matrix and increases ‘k’. This operation swaps the row and column indices, performing the transpose operation on the element.
  4. this nested loop continues to iterate through all elements in the ‘B’ matrix.
    B[i][j] → B’[j][i]

This neasted ‘for’loops are used for sorting the elements in the ‘result’ matrix to ensures that its elements are oredered by row index.

for (i = 0; i < result.terms; i++) {
		for (j = i; j < result.terms - 1; j++) {
			if (result.data[j].row > result.data[j + 1].row) {
				temp = result.data[j];
				result.data[j] = result.data[j + 1];
				result.data[j + 1] = temp;
			}
		}
	}//Perform the sorting operation, completing transposed matrix
  1. The outer loop iterates over each element in the ‘result.data’arrau, and the inner loop compares adjacent elements ot determine their oerder.
  2. in side the inner loop compares adjacent elements to determine thier order
  3. insiede the inner loop, there is an if statement that checks if the row attribute of the current element ‘result.data[j]’ is greater than the ‘row’ attribute of the next element ‘result.data[j+1]’
  4. if the condition is true, it means the elements are out of order in therms of row indices. so a temporary ‘element’ structure ‘temp’is used to swap the positions of ‘result.data[i]’ and ‘result.data[j+1]’ itn the array

⇒ reoerders the elements so that they are sorted vby row index in ascending order.

  1. the loops continue to iterate and perform this comparison and swapping operation untilall elements in the ‘result.data’ array are sorted by row index.
//Print out B and B ^T
	printf("== Matrix B ==\n");
	printMat(B.data);

	printf("== Matrix B^T ==\n");
	printMat(result.data);

this lines of code print the original matrix ‘B’ and its transpose ‘b^T’ to the console, allowing visualize both matrices and verify the result of the tanspose operation and sorting


2. 3D array allocation

//Implement a function 'mem-alloc_3D_double' of allocationg 3D array of double.
//Then, use this as below
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#define HEIGHT 3
#define ROW 3
#define COL 3

defining constant for the dimensions of 3D double array.

void mem_Alloc_3D_double(double ****p) {
	(*p) = (double***)malloc(sizeof(double**) * HEIGHT);
	int i = 0, j = 0, k=0;

	//allocate memory for each dimension of the 3D array
	for (i = 0; i < HEIGHT; i++) {
		(*p)[i] = (double**)malloc(sizeof(double*) * ROW);
		for (j = 0; j < ROW; j++) {
			(*p)[i][j] = (double*)malloc(sizeof(double) * COL);
			for (k = 0; k < COL; k++){
				(*p)[i][j][k] = (i*ROW*COL)+(j*COL)+k+1;
				//initialize
				printf("%.2f ", (*p)[i][j][k]);
				//print result
			}
			printf("\n");
		}
		printf("[%d]================\n\n", i+1);
	}
	printf(">>Allocation Completed!\n\n");
}

function mem_Alloc_3D_double takes a pointer to a 3D double pointer (****p) as its parameter. this function dynamically allocates memory for a 3D array of double values with dimensions specified by the constans.

  1. it allocates memory for the first dimension of the 3D array, which is an array of pointers to double**. the number of elements in this diemension is HEIGHT.
  2. inside a for-loop, it allocates memory for the second dimension (an array of pointers to double*) for each element in the first dimension (i).
  3. inside a nested loop it alloctes memory for the third dimension for each element in the secodn dimension(j)
  4. It initializes the elements of the array with values based on their postition.
  5. It prints a complition message when the allocation is completed.
void addition_3D(double ***p1, double ***p2) {
	int i, j, k;

	//iterate each element of the matrices and print sum
	printf("\nSum of the two 3D arrays!---------------------\n");
	for (i = 0; i < HEIGHT; i++) {
		for (j = 0; j < ROW; j++) {
			for (k = 0; k < COL; k++) {
				printf("%.2f ", p1[i][j][k] + p2[i][j][k]);
			}
			printf("\n");
		}
		printf("[%d]================\n", i+1);
	}
	printf(">>Addition Completed!\n\n");
}

function addition_3D takes two 3D double arrays represented as pointers p1and p2 as its parametes. It calculates the element addition of the two arrays and prints the result.

  1. iterate through each element of the two arrays usinsg nested loops.
  2. for each element at position (i,j,k) in both arrys, it calculates the sum of teh corresponding elements from p1 and p2 and then it prints this sum.
  3. finally it prints a message indicating the addition operation is completed.
void main() {
	//Define two matrices A and B using 'mem_alloc_3D_double';
	double ***A = NULL;
	double ***B = NULL;

	mem_Alloc_3D_double(&A);
	mem_Alloc_3D_double(&B);
	
	//Perform addition of two matrices using 'addition_3D()'
	addition_3D(A, B);

	//Deallocate A and B
	for (int i = 0; i < HEIGHT; i++) {
		for (int j = 0; j < ROW; j++) {
			free(A[i][j]);
			free(B[i][j]);
		}
		free(A[i]);
		free(B[i]);
	}
	free(A);
	free(B);
	printf(">>Deallocation Completed!\n\n");
}
  1. defines two 3D arrays A and B by calling the mem_Alloc_3D_double function for each of them.
  2. calls the addition_3D function to calculate and print the result of two matrix addition.
  3. after perfoming the addition, it deallocates the memory for both A and B. this is doen by freeing the memory for eache element of the arrays in a nested loop adn then freeing the memory for the arrays themselves.
  4. finally, it print completion message when the dealloction process is completed.

포인터는 할때마다 헷갈린다. 더 많이 쓰면서 익숙해지는 수 밖에!

profile
델룰루 이스 솔룰루

0개의 댓글