Advertisement
STANAANDREY

point arr

Feb 3rd, 2023 (edited)
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <limits.h>
  4. #define STEP (1 << 8)
  5.  
  6. void allocCheck(void *p) {
  7.   if (!p) {
  8.     perror("");
  9.     exit(EXIT_FAILURE);
  10.   }
  11. }
  12.  
  13. typedef struct {
  14.   int x, y;
  15. } Point;
  16.  
  17. typedef struct {
  18.   int len, buff;
  19.   Point *at;
  20. } DynArr;
  21.  
  22. int readPoint(Point *p, FILE *file) {
  23.   char aux;
  24.   int read = fscanf(file, "%d%c%d", &(p->x), &aux, &(p->y));
  25.   return read == 3 && aux == '.';
  26. }
  27.  
  28. DynArr *mkArr(int ini) {
  29.   DynArr *arr = malloc(sizeof(DynArr));
  30.   allocCheck(arr);
  31.   arr->len = arr->buff = ini;
  32.   if (ini) {
  33.     arr->at = calloc(sizeof(Point), ini);
  34.     allocCheck(arr->at);
  35.   } else {
  36.     arr->at = NULL;
  37.   }
  38.   return arr;
  39. }
  40.  
  41. void add(Point p, DynArr *arr) {
  42.   if (arr->len == arr->buff) {
  43.     arr->buff += STEP;
  44.     arr->at = realloc(arr->at, sizeof(Point) * arr->buff);
  45.     allocCheck(arr->at);
  46.   }
  47.   arr->at[(arr->len)++] = p;
  48. }
  49.  
  50. void printPoint(const Point *const point, FILE *file) {
  51.   fprintf(file, "{ x:%d y:%d }\n", point->x, point->y);
  52. }
  53.  
  54. void printArr(const DynArr *const arr, FILE *file) {
  55.   for (int i = 0; i < arr->len; i++) {
  56.     printPoint(&(arr->at[i]), file);
  57.   }
  58. }
  59.  
  60. int getMag(const Point *const p) {
  61.   int x = p->x, y = p->y;
  62.   return x * x + y * y;
  63. }
  64.  
  65. Point getClosest(const DynArr *const arr) {
  66.   int minMag = INT_MAX;
  67.   Point res = {};
  68.   for (int i = 0; i < arr->len; i++) {
  69.     int newMag = getMag(&(arr->at[i]));
  70.     if (minMag > newMag) {
  71.       minMag = newMag;
  72.       res = arr->at[i];
  73.     }
  74.   }
  75.   return res;
  76. }
  77.  
  78. int main(void) {
  79.   DynArr *arr = mkArr(0);
  80.   for (Point p; readPoint(&p, stdin);) {
  81.     add(p, arr);
  82.   }
  83.  
  84.   printArr(arr, stdout);
  85.   printf("closest to O: ");
  86.   Point res = getClosest(arr);
  87.   printPoint(&res, stdout);//*/
  88.   free(arr->at);
  89.   free(arr);
  90.   return 0;
  91. }
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement