Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #define MAX 20
- void input(int [][MAX],int,int);
- void convert_to_triplet(int [][MAX],int,int,int [][3]);
- void display(int [][3]);
- void addsparse(int [][3],int [][3],int [][3]);
- int main()
- {
- int r1,c1,r2,c2;
- int matrix1[MAX][MAX];
- int matrix2[MAX][MAX];
- int sparse1[MAX*MAX+1][3];
- int sparse2[MAX*MAX+1][3];
- int result[MAX*MAX+1][3];
- printf("Enter no. of rows and column in first matrix:");
- scanf("%d %d",&r1,&c1);
- do{
- printf("Enter no. of rows and column in second matrix:");
- scanf("%d %d",&r2,&c2);
- }while(r1!=r2||c2!=c1);
- printf("Enter first matrix:\n");
- input(matrix1,r1,c1);
- printf("Enter second matrix:\n");
- input(matrix2,r2,c2);
- convert_to_triplet(matrix1,r1,c1,sparse1);
- convert_to_triplet(matrix2,r2,c2,sparse2);
- printf("Sparse representation of first matrix:\n");
- display(sparse1);
- printf("Sparse representation of second matrix:\n");
- display(sparse2);
- addsparse(sparse1,sparse2,result);
- printf("Resultant matrix is:\n");
- display(result);
- return 0;
- }
- void input(int a[MAX][MAX],int r,int c){
- int i,j;
- for(i=0;i<r;i++){
- for(j=0;j<c;j++){
- printf("Enter matrix[%d][%d]:",i+1,j+1);
- scanf("%d",&a[i][j]);
- }
- }
- }
- void convert_to_triplet(int a[][MAX],int r,int c,int sparse[][3]){
- int i,j,k=1,count=0;
- sparse[0][0]=r;
- sparse[0][1]=c;
- for(i=0;i<r;i++){
- for(j=0;j<c;j++){
- if(a[i][j]){
- sparse[k][0]=i;
- sparse[k][1]=j;
- sparse[k][2]=a[i][j];
- k++;
- count++;
- }
- }
- }
- sparse[0][2]=count;
- }
- void display(int sparse[][3]){
- int i;
- for(i=0;i<=sparse[0][2];i++){
- printf("%d\t%d\t%d\n",sparse[i][0],sparse[i][1],sparse[i][2]);
- }
- }
- void addsparse(int a[][3],int b[][3],int c[][3])
- {
- int t1,t2,i,j,k;
- if(a[0][0]!=b[0][0]||a[0][1]!=b[0][1]){
- printf("Addition not possible");
- }
- t1=a[0][2];
- t2=b[0][2];
- i=j=k=0;
- c[0][0]=a[0][0];
- c[0][1]=a[0][1];
- while(i<=t1&&j<=t2){
- if(a[i][0]<b[j][0]){
- c[k][0]=a[i][0];
- c[k][1]=a[i][1];
- c[k][2]=a[i][2];
- k++;
- i++;
- }
- else if(b[j][0]<a[i][0]){
- c[k][0]=b[j][0];
- c[k][1]=b[j][1];
- c[k][2]=b[j][2];
- k++;
- j++;
- }
- else if(a[i][1]<b[j][1]){
- c[k][0]=a[i][0];
- c[k][1]=a[i][1];
- c[k][2]=a[i][2];
- k++;
- i++; }
- else if(b[j][1]<a[i][1]){
- c[k][0]=b[j][0];
- c[k][1]=b[j][1];
- c[k][2]=b[j][2];
- k++;
- j++;
- }
- else {
- c[k][0]=a[i][0];
- c[k][1]=a[i][1];
- c[k][2]=a[i][2]+b[j][2];
- k++;
- i++;
- j++;
- }
- }
- while(i<=t1){
- c[k][0]=a[i][0];
- c[k][1]=a[i][1];
- c[k][2]=a[i][2];
- i++;
- k++;
- }
- while(j<=t2){
- c[k][0]=b[j][0];
- c[k][1]=a[j][1];
- c[k][2]=a[j][2];
- j++;
- k++;
- }
- c[0][2]=k-1;
- }
Add Comment
Please, Sign In to add comment