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