-
Notifications
You must be signed in to change notification settings - Fork 0
/
trace.c
83 lines (73 loc) · 1.72 KB
/
trace.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void printMatrix(int** m, int r, int c){
int i, j;
for (i = 0; i < r; i++){
for (j = 0; j < c; j++)
printf("%d ", m[i][j]);
//printf("%d ", *((m+i*c)+j));
printf("\n");
}
}
int vecMult(int* vA, int* vB, int n){
int result = 0, i;
for (i = 0; i < n; i++){
result += vA[i] * vB[i];
}
return result;
}
int** matrixMult(int* mA, int rA, int cA, int* mB, int rB, int cB){
int** result = malloc(rA * sizeof(int *)), i, j;
for (i = 0; i < rA; i++)
result[i] = malloc(cB * sizeof(int));
for (i = 0; i < rA; i++){
for (j = 0; j < cB; j++){
int vB[rA];
int k;
for (k = 0; k < rB; k++) {
vB[k] = *((mB+k*cB) + j);
}
result[i][j] = vecMult(mA+i*cA, vB, cA);
}
}
return result;
}
int trace(int** m, int n){
int total = 0, i;
for (i = 0; i < n; i++)
total += m[i][i];
return total;
}
int main(int argc, char** argv){
if (argc <= 1) {
printf("NO FILE PROVIDED\n");
return 0;
}
if (access(*(argv+1), F_OK) != 0){
printf("FILE DOES NOT EXIST\n");
return 0;
}
FILE* f = fopen(argv[1], "r");
int rowsA, colsA, rowsB, colsB, i , j;
fscanf(f, "%d %d\n", &rowsA, &colsA);
int matrixA[rowsA][colsA];
for (i = 0; i < rowsA; i++)
for (j = 0; j < colsA; j++)
fscanf(f, " %d ", &matrixA[i][j]);
fscanf(f, "%d %d\n", &rowsB, &colsB);
int matrixB[rowsB][colsB];
for (i = 0; i < rowsB; i++)
for (j = 0; j < colsB; j++)
fscanf(f, " %d ", &matrixB[i][j]);
if (colsA != rowsB){
printf("MULTIPLICATION NOT POSSIBLE\n");
return 0;
}
int tra = trace(matrixMult((int*)matrixA, rowsA, colsA, (int*)matrixB, rowsB, colsB), rowsA);
FILE* out = fopen("part2_trace.dat", "w");
fprintf(out, "%d\n", tra);
fclose(out);
fclose(f);
return 0;
}