1 /*
2  * Copyright (c) 2018 CPqD Foundation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <time.h>
11 
12 /* generate random numbers for the nodes */
random_nodes(void)13 float random_nodes(void)
14 {
15 	float random_number = ((float)rand()) / ((float)RAND_MAX);
16 	return random_number;
17 }
18 
19 /* free the memory */
free_memory(float ** m,int length)20 void free_memory(float **m, int length)
21 {
22 	for (int i = 0; i < length; i++) {
23 		free(m[i]);
24 	}
25 	free(m);
26 }
27 
28 /* create a dinamic matrix */
create_matrix(int n)29 float **create_matrix(int n)
30 {
31 	float **matrix = (float **)malloc(n * sizeof(float *));
32 
33 	for (int i = 0; i < n; i++) {
34 		matrix[i] = (float *)malloc(n * sizeof(float));
35 		for (int j = 0; j < n; j++) {
36 			matrix[i][j] = 0.0;
37 		}
38 	}
39 
40 	return matrix;
41 }
42 
43 /* read the number of lines of .csv files */
read_lines(char * file)44 int read_lines(char *file)
45 {
46 	FILE *fd;
47 	int lines = 0;
48 	char c;
49 
50 	fd = fopen(file, "r");
51 
52 	while ((c = getc(fd)) != '\n') {
53 		if (c == ',') {
54 			lines++;
55 		}
56 	}
57 	lines++;
58 	return lines;
59 }
60 
61 /* print the matrix */
print_matrix(float ** m,int n)62 void print_matrix(float **m, int n)
63 {
64 	for (int i = 0; i < n; i++) {
65 		for (int j = 0; j < n; j++) {
66 			printf(" %1.2f ", m[i][j]);
67 		}
68 		printf("\n");
69 	}
70 }
71 
72 /* read .csv files containing only float contents */
read_csv(char * file)73 float **read_csv(char *file)
74 {
75 	int file_lines = read_lines(file);
76 	FILE *fd;
77 	float **m = create_matrix(file_lines);
78 	int lines = 0, cols = 0;
79 	float num;
80 
81 	fd = fopen(file, "r");
82 
83 	while (fscanf(fd, "%f", &m[lines][cols++]) != EOF) {
84 		char separator = getc(fd);
85 
86 		if (separator == '\n') {
87 			lines++;
88 			cols = 0;
89 		} else if (separator != ',') {
90 			printf("Unexpected char received: %c\n", separator);
91 			return NULL;
92 		}
93 	}
94 	fclose(fd);
95 	return m;
96 }
97