-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_sparse_mat.c
73 lines (59 loc) · 1.81 KB
/
create_sparse_mat.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
/**
* Author: Jack Robbins
* This simple program creates a sparse matrix in a binary file, according to
* the user's specification
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Include time for randomness
#include <time.h>
//Define a ratio constant
#define RATIO 0.2
/**
* This simple function can be used to write a sparse matrix, with user
* provided dimensions, into a binary file
*/
int main(int argc, char** argv){
//rows and columns are to be provided by the user
unsigned int rowNum, colNum;
if(argc < 3 || strlen(argv[1]) == 0 || strlen(argv[2]) == 0) {
printf("Error: Invalid number of arguments or invalid arguments\n");
return 1;
}
//Grab the rowNum and colNum from the command line
rowNum = atoi(argv[1]);
colNum = atoi(argv[2]);
//Create a binary file matrix.bin
FILE* fl = fopen("matrix.bin", "wb");
//If we can't create the file, exit the program
if(fl == NULL){
printf("File creation failed\n");
return 1;
}
//As our standard, rowNum and colNum are the first two ints in the file
fwrite(&rowNum, sizeof(unsigned int), 1, fl);
fwrite(&colNum, sizeof(unsigned int), 1, fl);
//Set the RNG seed using current time
srand(time(NULL));
unsigned int value;
//Use a double for loop to keep track of how much we need to write
for(unsigned int i = 0; i < rowNum; i++){
for(unsigned int j = 0; j < colNum; j++){
//Here is our chance element, this won't happen very often
//making our matrix sparse
if((double)rand() / (double)RAND_MAX < RATIO){
value = rand();
} else {
//Most of the time, value will be 0
value = 0;
}
//Write the unsigned int into the file
fwrite(&value, sizeof(unsigned int), 1, fl);
}
}
//We are done writing the file now
fclose(fl);
printf("Sparse matrix created successfully in: 'matrix.bin'\n\n");
return 0;
}