GNU/Linux executable: grid.tar
#include <stdio.h> #include <math.h> #define MAXD 1000000 int main(argc,argv) int argc; char *argv[]; { FILE *in; FILE *out; float x[MAXD]; float y[MAXD]; int grid[1000][1000]; int N; int i, k; float xmax, ymax; float xmin, ymin; float nxmax, nymax; float nxmin, nymin; float j1, j2; char line[300]; int real_grid; int xpos; int ypos; if ( argc != 3 ) { printf("Usage : grid <input file> <output file>\n"); exit(1); } out = fopen( argv[2], "w" ); if ( out == NULL ) { printf("Can not open output file. Abort.\n"); exit(1); } in = fopen( argv[1], "r" ); if ( in == NULL ) { printf("Can not open input file. Abort.\n"); exit(1); } N = 0; while ( fscanf(in, "%f %f", &x[N], &y[N]) == 2 ) { N++; if ( N == (MAXD-1) ) { printf("Too many data points. Giving up.\n"); exit(1); } } fclose( in ); printf("Read %d pairs of values.\n", N ); xmax = x[0]; ymax = y[0]; xmin = x[0]; ymin = y[0]; for ( i=0 ; i < N ; i++ ) { if ( x[i] > xmax ) xmax = x[i]; if ( x[i] < xmin ) xmin = x[i]; if ( y[i] > ymax ) ymax = y[i]; if ( y[i] < ymin ) ymin = y[i]; } printf("Range on x is %f to %f. New range (or enter to keep): ", xmin, xmax); gets( line ); if ( sscanf(line, "%f %f", &j1, &j2) == 2 ) { if ( j1 >= j2 ) { printf("Nonsense ...\n"); exit(1); } xmin = j1; xmax = j2; } printf("Range on y is %f to %f. New range (or enter to keep): ", ymin, ymax); gets( line ); if ( sscanf(line, "%f %f", &j1, &j2) == 2 ) { if ( j1 >= j2 ) { printf("Nonsense ...\n"); exit(1); } ymin = j1; ymax = j2; } real_grid = (int)(sqrt((double)(N))); if ( real_grid > 1000 ) real_grid = 1000; nxmin = xmin - 0.050 * (xmax-xmin); nxmax = xmax + 0.050 * (xmax-xmin); nymin = ymin - 0.050 * (ymax-ymin); nymax = ymax + 0.050 * (ymax-ymin); printf("The grid will be %d by %d and will cover:\n", real_grid, real_grid); printf(" from %f to %f along x\n", nxmin, nxmax ); printf(" from %f to %f along y\n", nymin, nymax ); for ( i=0 ; i < real_grid ; i++ ) for ( k=0 ; k < real_grid ; k++ ) grid[i][k] = 0; for ( i=0 ; i < N ; i++ ) { if ( x[i] >= nxmin && x[i] <= nxmax && y[i] >= nymin && y[i] <= nymax ) { xpos = (int)( real_grid * (( x[i] - nxmin ) / (nxmax-nxmin) ) + 0.50 ); ypos = (int)( real_grid * (( y[i] - nymin ) / (nymax-nymin) ) + 0.50 ); grid[ xpos ][ ypos ]++; } } for ( k=0 ; k < real_grid ; k++ ) { for ( i=0 ; i < real_grid ; i++ ) fprintf(out, " %5d", grid[i][k] ); fprintf(out, "\n" ); } fclose(out); }