Created
December 7, 2010 07:36
-
-
Save kakkun61/731561 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#include <math.h> | |
#define MAX_N 100 | |
typedef struct { | |
double real; | |
double imag; | |
double abs; | |
} complex; | |
void generate(complex *c, const int n, const int max); | |
void print_complex(const complex *c, const int n); | |
int compare(const complex *c1, const complex *p2); | |
int debug = 0; | |
int main(int argc, char **argv) { | |
if (argc < 3) { | |
printf("Usage\n\t%s <N> <MAX>\n\nN: the number of complex numbers (<%d)\nMAX: the maximum real or imaginary component which will be genaerated\n", argv[0], MAX_N); | |
return -1; | |
} else { | |
int n, max; | |
complex c[MAX_N]; | |
n = atoi(argv[1]); | |
max = atoi(argv[2]); | |
if (argc == 4) | |
debug = 1; | |
generate(c, n, max); | |
if (debug) { | |
print_complex(c, n); | |
printf("\n"); | |
} | |
qsort(c, n, sizeof(complex), (int (*)(const void*, const void*))compare); | |
print_complex(c, n); | |
return 0; | |
} | |
} | |
void generate(complex *c, const int n, const int max) { | |
int i; | |
srand(time(NULL)); | |
for (i=0; i<n; i++) { | |
c[i].real = rand() % max; | |
c[i].imag = rand() % max; | |
c[i].abs = sqrt((c[i].real)*(c[i].real) + (c[i].imag)*(c[i].imag)); | |
} | |
} | |
void print_complex(const complex *c, const int n) { | |
int i; | |
for (i=0; i<n; i++) { | |
printf("(%lf, %lf) %lf\n", c[i].real, c[i].imag, c[i].abs); | |
} | |
} | |
int compare(const complex *c1, const complex *c2) { | |
if (c1->abs < c2->abs) | |
return -1; | |
else if (c1->abs > c2->abs) | |
return 1; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment