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