stage2: Extensively comment the source code
[gaul-genprog.git] / generator.c
blobd6d822bcb0a87d948497a479fd7dc4cfa355fd8d
1 /* Simple generator of text files for the genetic program testing. */
3 #include <stdio.h>
4 #include <stdlib.h>
6 int
7 main(int argc, char *argv[])
9 /* Test if we were executed properly. */
10 if (argc != 4) {
11 fprintf(stderr, "Usage: %s EQUATION_COUNT INPUT_FILE OUTPUT_FILE\n", argv[0]);
12 exit(EXIT_FAILURE);
15 /* Retrieve parameters. */
16 int eqcount = atoi(argv[1]);
17 FILE *infile = fopen(argv[2], "w");
18 if (!infile) {
19 perror(argv[2]);
20 exit(EXIT_FAILURE);
22 FILE *outfile = fopen(argv[3], "w");
23 if (!outfile) {
24 perror(argv[2]);
25 exit(EXIT_FAILURE);
28 /* Produce equations. */
29 for (int i = 0; i < eqcount; i++) {
30 /* Available operators. */
31 static char ops[4] = "+-*/";
33 /* Pick an operator and parameters. */
34 int arg1 = rand() % 100; /* 0 to 99 */
35 char op = ops[rand() % 4]; /* random operator character */
36 int arg2 = rand() % 100; /* 0 to 99 */
38 /* Make sure we do not divide by zero. */
39 if (op == '/' && arg2 == 0)
40 arg2 = 1 + rand() % 99; /* 1 to 99 */
42 /* Write the equation. */
43 fprintf(infile, "%d%c%d=\n", arg1, op, arg2);
45 /* Figure out the result. */
46 int result = 0;
47 switch (op) {
48 case '+': result = arg1 + arg2; break;
49 case '-': result = arg1 - arg2; break;
50 case '*': result = arg1 * arg2; break;
51 case '/': result = arg1 / arg2; break;
54 /* Write the result. */
55 fprintf(outfile, "%d\n", result);