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