-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix.c
More file actions
126 lines (114 loc) · 2.21 KB
/
matrix.c
File metadata and controls
126 lines (114 loc) · 2.21 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/*
* Matrix task processor - matrix module
* Based on Operating Systems: Three Easy Pieces by R. Arpaci-Dusseau and A. Arpaci-Dusseau
*
* Wes J. Lloyd
* University of Washington, Tacoma
* TCSS 422 - Operating Systems
* Spring 2017
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
int SumMatrix(int ** matrix, const int height, const int width);
// MATRIX ROUTINES
int ** AllocMatrix(int r, int c)
{
int ** a;
int i;
a = (int**) malloc(sizeof(int *) * r);
assert(a != 0);
for (i = 0; i < r; i++)
{
a[i] = (int *) malloc(c * sizeof(int));
assert(a[i] != 0);
}
return a;
}
void FreeMatrix(int ** a, int r, int c)
{
int i;
for (i=0; i<r; i++)
{
free(a[i]);
}
free(a);
}
void GenMatrixType(int ** matrix, const int height, const int width, int type)
{
int i, j;
if (type > 100)
type = 100;
if (type < 1)
type = 1;
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
int * mm = matrix[i];
switch (type)
{
case 1:
mm[j] = 1;
break;
case 2:
mm[j] = j;
break;
default:
mm[j] = rand() % type;
}
#if OUTPUT
printf("matrix[%d][%d]=%d \n",i,j,mm[j]);
#endif
}
}
}
void GenMatrix(int ** matrix, const int height, const int width)
{
GenMatrixType(matrix, height, width, 1);
}
// TO DO
// Implement the AvgElement function
int AvgElement(int ** matrix, const int height, const int width)
{
int sum = SumMatrix(matrix, height, width);
int num = height * width;
int avg = sum / num;
return avg;
}
int SumMatrix(int ** matrix, const int height, const int width)
{
int sum=0;
int y=0;
int i, j;
for (i=0; i<height; i++)
{
int *mm = matrix[i];
for (j=0; j<width; j++)
{
y=mm[j];
sum=sum+y;
}
}
return sum;
}
void DisplayMatrix(int ** matrix, const int height, const int width, FILE *stream)
{
int y=0;
int i, j;
for (i=0; i<height; i++)
{
int *mm = matrix[i];
fprintf(stream, "|");
for (j=0; j<width; j++)
{
y=mm[j];
if (j==0)
fprintf(stream, "%3d",y);
else
fprintf(stream, " %3d",y);
}
fprintf(stream, "|\n");
}
}