Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <limits.h>
- #define STEP (1 << 8)
- void allocCheck(void *p) {
- if (!p) {
- perror("");
- exit(EXIT_FAILURE);
- }
- }
- typedef struct {
- int x, y;
- } Point;
- typedef struct {
- int len, buff;
- Point *at;
- } DynArr;
- int readPoint(Point *p, FILE *file) {
- char aux;
- int read = fscanf(file, "%d%c%d", &(p->x), &aux, &(p->y));
- return read == 3 && aux == '.';
- }
- DynArr *mkArr(int ini) {
- DynArr *arr = malloc(sizeof(DynArr));
- allocCheck(arr);
- arr->len = arr->buff = ini;
- if (ini) {
- arr->at = calloc(sizeof(Point), ini);
- allocCheck(arr->at);
- } else {
- arr->at = NULL;
- }
- return arr;
- }
- void add(Point p, DynArr *arr) {
- if (arr->len == arr->buff) {
- arr->buff += STEP;
- arr->at = realloc(arr->at, sizeof(Point) * arr->buff);
- allocCheck(arr->at);
- }
- arr->at[(arr->len)++] = p;
- }
- void printPoint(const Point *const point, FILE *file) {
- fprintf(file, "{ x:%d y:%d }\n", point->x, point->y);
- }
- void printArr(const DynArr *const arr, FILE *file) {
- for (int i = 0; i < arr->len; i++) {
- printPoint(&(arr->at[i]), file);
- }
- }
- int getMag(const Point *const p) {
- int x = p->x, y = p->y;
- return x * x + y * y;
- }
- Point getClosest(const DynArr *const arr) {
- int minMag = INT_MAX;
- Point res = {};
- for (int i = 0; i < arr->len; i++) {
- int newMag = getMag(&(arr->at[i]));
- if (minMag > newMag) {
- minMag = newMag;
- res = arr->at[i];
- }
- }
- return res;
- }
- int main(void) {
- DynArr *arr = mkArr(0);
- for (Point p; readPoint(&p, stdin);) {
- add(p, arr);
- }
- printArr(arr, stdout);
- printf("closest to O: ");
- Point res = getClosest(arr);
- printPoint(&res, stdout);//*/
- free(arr->at);
- free(arr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement