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