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