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