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