Merge branch 'vendor/OPENRESOLV' with the following changes:
[dragonfly.git] / games / arithmetic / arithmetic.c
1 /*-
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Eamonn McManus of Trinity College Dublin.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * @(#) Copyright (c) 1989, 1993 The Regents of the University of California.  All rights reserved.
33  * @(#)arithmetic.c     8.1 (Berkeley) 5/31/93
34  * $FreeBSD: src/games/arithmetic/arithmetic.c,v 1.10 1999/12/12 06:40:28 billf Exp $
35  */
36
37 /*
38  * By Eamonn McManus, Trinity College Dublin <emcmanus@cs.tcd.ie>.
39  *
40  * The operation of this program mimics that of the standard Unix game
41  * `arithmetic'.  I've made it as close as I could manage without examining
42  * the source code.  The principal differences are:
43  *
44  * The method of biasing towards numbers that had wrong answers in the past
45  * is different; original `arithmetic' seems to retain the bias forever,
46  * whereas this program lets the bias gradually decay as it is used.
47  *
48  * Original `arithmetic' delays for some period (3 seconds?) after printing
49  * the score.  I saw no reason for this delay, so I scrapped it.
50  *
51  * There is no longer a limitation on the maximum range that can be supplied
52  * to the program.  The original program required it to be less than 100.
53  * Anomalous results may occur with this program if ranges big enough to
54  * allow overflow are given.
55  *
56  * I have obviously not attempted to duplicate bugs in the original.  It
57  * would go into an infinite loop if invoked as `arithmetic / 0'.  It also
58  * did not recognise an EOF in its input, and would continue trying to read
59  * after it.  It did not check that the input was a valid number, treating any
60  * garbage as 0.  Finally, it did not flush stdout after printing its prompt,
61  * so in the unlikely event that stdout was not a terminal, it would not work
62  * properly.
63  */
64
65 #include <sys/types.h>
66 #include <ctype.h>
67 #include <signal.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <time.h>
72 #include <unistd.h>
73
74 static int getrandom(int, int, int);
75 static void intr(int) __dead2;
76 static int opnum(int);
77 static void penalise(int, int, int);
78 static int problem(void);
79 static void showstats(void);
80 static void usage(void) __dead2;
81
82 static const char keylist[] = "+-x/";
83 static const char defaultkeys[] = "+-";
84 static const char *keys = defaultkeys;
85 static int nkeys = sizeof(defaultkeys) - 1;
86 static int rangemax = 10;
87 static int nright, nwrong;
88 static time_t qtime;
89 #define NQUESTS 20
90
91 /*
92  * Select keys from +-x/ to be asked addition, subtraction, multiplication,
93  * and division problems.  More than one key may be given.  The default is
94  * +-.  Specify a range to confine the operands to 0 - range.  Default upper
95  * bound is 10.  After every NQUESTS questions, statistics on the performance
96  * so far are printed.
97  */
98 int
99 main(int argc, char *argv[])
100 {
101         int ch, cnt;
102
103         /* Revoke setgid privileges */
104         setgid(getgid());
105
106         while ((ch = getopt(argc, argv, "r:o:")) != -1)
107                 switch(ch) {
108                 case 'o': {
109                         const char *p;
110
111                         for (p = keys = optarg; *p; ++p)
112                                 if (!index(keylist, *p)) {
113                                         fprintf(stderr,
114                                             "arithmetic: unknown key.\n");
115                                         exit(1);
116                                 }
117                         nkeys = p - optarg;
118                         break;
119                 }
120                 case 'r':
121                         if ((rangemax = atoi(optarg)) <= 0) {
122                                 fprintf(stderr,
123                                     "arithmetic: invalid range.\n");
124                                 exit(1);
125                         }
126                         break;
127                 case '?':
128                 default:
129                         usage();
130                 }
131         if (argc -= optind)
132                 usage();
133
134         /* Seed the random-number generator. */
135         srandomdev();
136
137         signal(SIGINT, intr);
138
139         /* Now ask the questions. */
140         for (;;) {
141                 for (cnt = NQUESTS; cnt--;)
142                         if (problem() == EOF)
143                                 exit(0);
144                 showstats();
145         }
146         /* NOTREACHED */
147 }
148
149 /* Handle interrupt character.  Print score and exit. */
150 static void
151 intr(__unused int sig)
152 {
153         showstats();
154         exit(0);
155 }
156
157 /* Print score.  Original `arithmetic' had a delay after printing it. */
158 static void
159 showstats(void)
160 {
161         if (nright + nwrong > 0) {
162                 printf("\n\nRights %d; Wrongs %d; Score %d%%",
163                     nright, nwrong, (int)(100L * nright / (nright + nwrong)));
164                 if (nright > 0)
165         printf("\nTotal time %ld seconds; %.1f seconds per problem\n\n",
166                             (long)qtime, (float)qtime / nright);
167         }
168         printf("\n");
169 }
170
171 /*
172  * Pick a problem and ask it.  Keeps asking the same problem until supplied
173  * with the correct answer, or until EOF or interrupt is typed.  Problems are
174  * selected such that the right operand and either the left operand (for +, x)
175  * or the correct result (for -, /) are in the range 0 to rangemax.  Each wrong
176  * answer causes the numbers in the problem to be penalised, so that they are
177  * more likely to appear in subsequent problems.
178  */
179 static int
180 problem(void)
181 {
182         char *p;
183         time_t start, finish;
184         int left, op, right, result;
185         char line[80];
186
187         left = 0;
188         right = 0;
189         result = 0;
190         op = keys[random() % nkeys];
191         if (op != '/')
192                 right = getrandom(rangemax + 1, op, 1);
193 retry:
194         /* Get the operands. */
195         switch (op) {
196         case '+':
197                 left = getrandom(rangemax + 1, op, 0);
198                 result = left + right;
199                 break;
200         case '-':
201                 result = getrandom(rangemax + 1, op, 0);
202                 left = right + result;
203                 break;
204         case 'x':
205                 left = getrandom(rangemax + 1, op, 0);
206                 result = left * right;
207                 break;
208         case '/':
209                 right = getrandom(rangemax, op, 1) + 1;
210                 result = getrandom(rangemax + 1, op, 0);
211                 left = right * result + random() % right;
212                 break;
213         }
214
215         /*
216          * A very big maxrange could cause negative values to pop
217          * up, owing to overflow.
218          */
219         if (result < 0 || left < 0)
220                 goto retry;
221
222         printf("%d %c %d =   ", left, op, right);
223         fflush(stdout);
224         time(&start);
225
226         /*
227          * Keep looping until the correct answer is given, or until EOF or
228          * interrupt is typed.
229          */
230         for (;;) {
231                 if (!fgets(line, sizeof(line), stdin)) {
232                         printf("\n");
233                         return(EOF);
234                 }
235                 for (p = line; *p && isspace(*p); ++p);
236                 if (!isdigit(*p)) {
237                         printf("Please type a number.\n");
238                         continue;
239                 }
240                 if (atoi(p) == result) {
241                         printf("Right!\n");
242                         ++nright;
243                         break;
244                 }
245                 /* Wrong answer; penalise and ask again. */
246                 printf("What?\n");
247                 ++nwrong;
248                 penalise(right, op, 1);
249                 if (op == 'x' || op == '+')
250                         penalise(left, op, 0);
251                 else
252                         penalise(result, op, 0);
253         }
254
255         /*
256          * Accumulate the time taken.  Obviously rounding errors happen here;
257          * however they should cancel out, because some of the time you are
258          * charged for a partially elapsed second at the start, and some of
259          * the time you are not charged for a partially elapsed second at the
260          * end.
261          */
262         time(&finish);
263         qtime += finish - start;
264         return(0);
265 }
266
267 /*
268  * Here is the code for accumulating penalties against the numbers for which
269  * a wrong answer was given.  The right operand and either the left operand
270  * (for +, x) or the result (for -, /) are stored in a list for the particular
271  * operation, and each becomes more likely to appear again in that operation.
272  * Initially, each number is charged a penalty of WRONGPENALTY, giving it that
273  * many extra chances of appearing.  Each time it is selected because of this,
274  * its penalty is decreased by one; it is removed when it reaches 0.
275  *
276  * The penalty[] array gives the sum of all penalties in the list for
277  * each operation and each operand.  The penlist[] array has the lists of
278  * penalties themselves.
279  */
280
281 static int penalty[sizeof(keylist) - 1][2];
282 static struct penalty {
283         int value, penalty;     /* Penalised value and its penalty. */
284         struct penalty *next;
285 } *penlist[sizeof(keylist) - 1][2];
286
287 #define WRONGPENALTY    5       /* Perhaps this should depend on maxrange. */
288
289 /*
290  * Add a penalty for the number `value' to the list for operation `op',
291  * operand number `operand' (0 or 1).  If we run out of memory, we just
292  * forget about the penalty (how likely is this, anyway?).
293  */
294 static void
295 penalise(int value, int op, int operand)
296 {
297         struct penalty *p;
298
299         op = opnum(op);
300         if ((p = malloc(sizeof(*p))) == NULL)
301                 return;
302         p->next = penlist[op][operand];
303         penlist[op][operand] = p;
304         penalty[op][operand] += p->penalty = WRONGPENALTY;
305         p->value = value;
306 }
307
308 /*
309  * Select a random value from 0 to maxval - 1 for operand `operand' (0 or 1)
310  * of operation `op'.  The random number we generate is either used directly
311  * as a value, or represents a position in the penalty list.  If the latter,
312  * we find the corresponding value and return that, decreasing its penalty.
313  */
314 static int
315 getrandom(int maxval, int op, int operand)
316 {
317         int value;
318         struct penalty **pp, *p;
319
320         op = opnum(op);
321         value = random() % (maxval + penalty[op][operand]);
322
323         /*
324          * 0 to maxval - 1 is a number to be used directly; bigger values
325          * are positions to be located in the penalty list.
326          */
327         if (value < maxval)
328                 return(value);
329         value -= maxval;
330
331         /*
332          * Find the penalty at position `value'; decrement its penalty and
333          * delete it if it reaches 0; return the corresponding value.
334          */
335         for (pp = &penlist[op][operand]; (p = *pp) != NULL; pp = &p->next) {
336                 if (p->penalty > value) {
337                         value = p->value;
338                         penalty[op][operand]--;
339                         if (--(p->penalty) <= 0) {
340                                 p = p->next;
341                                 free((char *)*pp);
342                                 *pp = p;
343                         }
344                         return(value);
345                 }
346                 value -= p->penalty;
347         }
348         /*
349          * We can only get here if the value from the penalty[] array doesn't
350          * correspond to the actual sum of penalties in the list.  Provide an
351          * obscure message.
352          */
353         fprintf(stderr, "arithmetic: bug: inconsistent penalties\n");
354         exit(1);
355         /* NOTREACHED */
356 }
357
358 /* Return an index for the character op, which is one of [+-x/]. */
359 static int
360 opnum(int op)
361 {
362         char *p;
363
364         if (op == 0 || (p = index(keylist, op)) == NULL) {
365                 fprintf(stderr,
366                     "arithmetic: bug: op %c not in keylist %s\n", op, keylist);
367                 exit(1);
368         }
369         return(p - keylist);
370 }
371
372 /* Print usage message and quit. */
373 static void
374 usage(void)
375 {
376         fprintf(stderr, "usage: arithmetic [-o +-x/] [-r range]\n");
377         exit(1);
378 }