C How to find and group coordinates located in a grid

左心房为你撑大大i 提交于 2021-02-17 06:29:07

问题


I have a C program where a CSV file containing 8 x,y coordinates are inserted into a linked list. Each of the 8 coordinates belongs in a 2x2 grid. There are 4 grids as seen in the picture below:

First I want my program to determine which coordinate belongs in which grid. Once I've determined that, for each grid, I want to sum all of the x-coordinates and y-coordinates. Then for each grid 1-4, I want to then print the total sum of the x coord and y coord.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include <string.h>

#define MAX 200

struct wake {
    double x, y;
    struct wake *next;
}*head;   

typedef struct {
    double x, y;
} grid_t;

typedef struct wake data;

void read_csv();
void gridSearch();
void maxNode();

int main(int argc, char *argv[]) {
    read_csv();
}

void read_csv() {
    // Opens the CSV datafile
    FILE *fp = fopen("data4.csv", "r");
    
    char buffer[MAX];
    struct wake** tail = &head;
    
    while (fgets(buffer, MAX, fp)) {
        data *node = malloc(sizeof(data));
        node->x = atof(strtok(buffer, ","));
        node->y = atof(strtok(NULL, ","));
        node->next = NULL;
        *tail = node;
        tail = &node->next;
        
    }
    gridSearch();
    //maxNode();
}

void gridSearch() {  
    struct wake *current = head;  
    
    int i, j, gridnum = 0;
    grid_t (*grid)[2] = calloc(4, sizeof(grid_t[2][2]));
    //double min;
    
    if(head == NULL) {  
        printf("List is empty \n");  
    }  
    else {  
        //Initializing min with head node data  
        while(current != NULL){
            for (j = 0; j < 2; j++) {
                for (i = 0; i < 2; i++) {
                    if ((current->x >= -2+i*2) && (current->x <= -2+(i+1)*2)) {
                        if ((current->y >= -2+j*2) && (current->x <= -2+(j+1)*2)) {
                            printf("%lf\n", current->x);
                            grid[i][j].x += current->x;
                            grid[i][j].y += current->y;
                        }
                    }
                }
            }
            current= current->next;
        }
    }
    for (i = 0; j < 2; j++) {
        for (j = 0; i < 2; i++) {
            gridnum++;
            printf("Sum of x coord in grid %d: %lf\n", gridnum, grid[i][j].x);
            printf("Sum of y coord in grid %d: %lf\n\n", gridnum, grid[i][j].y);
        }
    }   
}

When I run my program, nothing seems to happen. I'm not sure why it's not working. Here is the input CSV file:

-1,-1
-1,1.5
1,-1
1,1
-1.5,-1.5
-1,0.5
1.5,-1.5
0.5,0.5

来源:https://stackoverflow.com/questions/63646104/c-how-to-find-and-group-coordinates-located-in-a-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!