-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcartesian_plane.c
95 lines (77 loc) · 2.69 KB
/
cartesian_plane.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
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "cartesian_plane.h"
#include "point.h"
static const int ARRAY_INIT_SIZE = 100;
static const int ARRAY_GROWTH_RATE = 150;
struct CartesianPlane {
Point **points;
int number_points;
int allocated_points;
int dimension;
};
CartesianPlane *cartesian_plane_construct() {
CartesianPlane *cp = (CartesianPlane *)calloc(1, sizeof(CartesianPlane));
if (cp == NULL)
exit(printf("Error: cartesian_plane_construct failed to allocate memory.\n"));
cp->allocated_points = ARRAY_INIT_SIZE;
cp->points = (Point **)calloc(cp->allocated_points, sizeof(Point *));
cp->number_points = 0;
return cp;
}
void cartesian_plane_destroy(CartesianPlane *cp) {
for (int i = 0; i < cp->number_points; i++)
point_destroy(cp->points[i]);
free(cp->points);
free(cp);
}
void cartesian_plane_read(CartesianPlane *cp, char *input_file) {
char *line = NULL;
size_t len = 0;
ssize_t read;
FILE *input = fopen(input_file, "r");
if (input == NULL)
exit(printf("Error: cartesian_plane_read failed to open input file.\n"));
if ((read = getline(&line, &len, input)) == -1)
exit(printf("Error: cartesian_plane_read input file is empty.\n"));
// Remove o caractere de nova linha (\n) do final da linha.
line[strcspn(line, "\n")] = 0;
//Encontra o tamanho da dimensão para evitar realloc na leitura dos pontos.
for (int i = 0; line[i] != '\0'; i++) {
if (line[i] == ',')
cp->dimension++;
}
// Retorna ao início do arquivo para processar novamente
fseek(input, 0, SEEK_SET);
while((read = getline(&line, &len, input)) != -1) {
line[strcspn(line, "\n")] = 0;
Point *p = point_read(cp->dimension, line);
if(cp->number_points == cp->allocated_points) {
cp->allocated_points *= ARRAY_GROWTH_RATE;
cp->points = (Point **)realloc(cp->points, cp->allocated_points * sizeof(Point *));
}
cp->points[cp->number_points] = p;
cp->number_points++;
}
free(line);
fclose(input);
}
int cartesian_plane_get_number_points(CartesianPlane *cp) {
return cp->number_points;
}
Point *cartesian_plane_get_point(CartesianPlane *cp, int i) {
return cp->points[i];
}
int cartesian_plane_get_dimension(CartesianPlane *cp) {
return cp->dimension;
}
void cartesian_plane_qsort(CartesianPlane *cp) {
qsort(cp->points, cp->number_points, sizeof(Point *), point_compare);
}
// Debug
// void cartesian_plane_print(CartesianPlane *cp) {
// for (int i = 0; i < cp->number_points; i++)
// point_print(cp->points[i], cp->dimension);
// }