-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrandMatrices.c
More file actions
104 lines (77 loc) · 2.05 KB
/
randMatrices.c
File metadata and controls
104 lines (77 loc) · 2.05 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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include<sys/time.h>
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
/* rxc matrix the elements are filled with random numbers
between 0 to k.
outputfile is the random matrix.
histogram test?
*/
int main(int argc, char *argv[])
{
//command line arguments start
if( argc != 5 )
{
printf("Invaild number of Arguments entered \n");
return -1;
}
int k, c, r;
//convert string to integer values
r = atoi(argv[1]);
c = atoi(argv[2]);
k = atoi(argv[3]);
printf("r:%d c:%d k:%d\n", r, c, k);
//inputs range check the assignment
if(!(r > 0 && r <= 10000) || !(c > 0 && c <= 10000) || !(k >= 2 && k <= MIN(r, c)/10))
{
printf("inputs not in range\n");
return -1;
}
//end of command line arguments
srand( time(NULL) );
//function prototypes
void fill_random(int **, int , int , int );
void writeToFile(FILE*, int**, int, int);
//file handling
FILE *outFPtr = fopen(argv[4], "w");
//to calculate executiontime
struct timeval start, end;
//start of execution
gettimeofday(&start, NULL);
//allocating space for the matrix
int **matrix = (int**)malloc(c*sizeof(int*));
for(int i = 0; i < r; i++)
matrix[i] = malloc(sizeof(int)*c);
fill_random(matrix,r,c,k);
writeToFile(outFPtr,matrix, r, c);
//end of execution
gettimeofday(&end, NULL);
//free matrix to prevent memory leaks?
for (int i = 0; i < r; i++)
free(matrix[i]);
free(matrix);
//execution time calculation
float exec_time = ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec));
exec_time /= 1000000;
printf("Time taken to execute: %fs\n\n", exec_time);
return 0;
}
//functions
void fill_random(int **matrix, int r, int c, int k)
{
//using rand to fill every element of the matrix
for (int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
matrix[i][j] = (rand() % k) + 1;
}
void writeToFile(FILE *outFPtr, int **matrix, int r, int c)
{
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
fprintf(outFPtr, "%d ", matrix[i][j]);
fprintf(outFPtr, "\n");
}
}