xref: /netbsd-src/games/arithmetic/arithmetic.c (revision 277bd0756ca50f412c495785caa07bb33578fd50)
1*277bd075Sdholland /*	$NetBSD: arithmetic.c,v 1.27 2012/06/19 05:46:08 dholland Exp $	*/
21d8bbe81Scgd 
361f28255Scgd /*
41d8bbe81Scgd  * Copyright (c) 1989, 1993
51d8bbe81Scgd  *	The Regents of the University of California.  All rights reserved.
661f28255Scgd  *
761f28255Scgd  * This code is derived from software contributed to Berkeley by
861f28255Scgd  * Eamonn McManus of Trinity College Dublin.
961f28255Scgd  *
1061f28255Scgd  * Redistribution and use in source and binary forms, with or without
1161f28255Scgd  * modification, are permitted provided that the following conditions
1261f28255Scgd  * are met:
1361f28255Scgd  * 1. Redistributions of source code must retain the above copyright
1461f28255Scgd  *    notice, this list of conditions and the following disclaimer.
1561f28255Scgd  * 2. Redistributions in binary form must reproduce the above copyright
1661f28255Scgd  *    notice, this list of conditions and the following disclaimer in the
1761f28255Scgd  *    documentation and/or other materials provided with the distribution.
18e5aeb4eaSagc  * 3. Neither the name of the University nor the names of its contributors
1961f28255Scgd  *    may be used to endorse or promote products derived from this software
2061f28255Scgd  *    without specific prior written permission.
2161f28255Scgd  *
2261f28255Scgd  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2361f28255Scgd  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2461f28255Scgd  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2561f28255Scgd  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2661f28255Scgd  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2761f28255Scgd  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2861f28255Scgd  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2961f28255Scgd  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3061f28255Scgd  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3161f28255Scgd  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3261f28255Scgd  * SUCH DAMAGE.
3361f28255Scgd  */
3461f28255Scgd 
35ff14dd5aSlukem #include <sys/cdefs.h>
3661f28255Scgd #ifndef lint
372fe2731dSlukem __COPYRIGHT("@(#) Copyright (c) 1989, 1993\
382fe2731dSlukem  The Regents of the University of California.  All rights reserved.");
3961f28255Scgd #endif /* not lint */
4061f28255Scgd 
4161f28255Scgd #ifndef lint
421d8bbe81Scgd #if 0
431d8bbe81Scgd static char sccsid[] = "@(#)arithmetic.c	8.1 (Berkeley) 5/31/93";
441d8bbe81Scgd #else
45*277bd075Sdholland __RCSID("$NetBSD: arithmetic.c,v 1.27 2012/06/19 05:46:08 dholland Exp $");
461d8bbe81Scgd #endif
4761f28255Scgd #endif /* not lint */
4861f28255Scgd 
4961f28255Scgd /*
5061f28255Scgd  * By Eamonn McManus, Trinity College Dublin <emcmanus@cs.tcd.ie>.
5161f28255Scgd  *
5261f28255Scgd  * The operation of this program mimics that of the standard Unix game
5361f28255Scgd  * `arithmetic'.  I've made it as close as I could manage without examining
5461f28255Scgd  * the source code.  The principal differences are:
5561f28255Scgd  *
5661f28255Scgd  * The method of biasing towards numbers that had wrong answers in the past
5761f28255Scgd  * is different; original `arithmetic' seems to retain the bias forever,
5861f28255Scgd  * whereas this program lets the bias gradually decay as it is used.
5961f28255Scgd  *
6061f28255Scgd  * Original `arithmetic' delays for some period (3 seconds?) after printing
6161f28255Scgd  * the score.  I saw no reason for this delay, so I scrapped it.
6261f28255Scgd  *
6361f28255Scgd  * There is no longer a limitation on the maximum range that can be supplied
6461f28255Scgd  * to the program.  The original program required it to be less than 100.
6561f28255Scgd  * Anomalous results may occur with this program if ranges big enough to
6661f28255Scgd  * allow overflow are given.
6761f28255Scgd  *
6861f28255Scgd  * I have obviously not attempted to duplicate bugs in the original.  It
6961f28255Scgd  * would go into an infinite loop if invoked as `arithmetic / 0'.  It also
7061f28255Scgd  * did not recognise an EOF in its input, and would continue trying to read
7161f28255Scgd  * after it.  It did not check that the input was a valid number, treating any
7261f28255Scgd  * garbage as 0.  Finally, it did not flush stdout after printing its prompt,
7361f28255Scgd  * so in the unlikely event that stdout was not a terminal, it would not work
7461f28255Scgd  * properly.
7561f28255Scgd  */
7661f28255Scgd 
7761f28255Scgd #include <sys/types.h>
78ff14dd5aSlukem #include <err.h>
7961f28255Scgd #include <ctype.h>
80ff14dd5aSlukem #include <signal.h>
8161f28255Scgd #include <stdio.h>
82ff14dd5aSlukem #include <stdlib.h>
8361f28255Scgd #include <string.h>
8411a76ec0Smycroft #include <time.h>
8575a6e035Sperry #include <unistd.h>
8661f28255Scgd 
87c62bf84cSdholland static int	getrandom(int, int, int);
88c62bf84cSdholland static void	intr(int) __dead;
89c62bf84cSdholland static int	opnum(int);
90c62bf84cSdholland static void	penalise(int, int, int);
91c62bf84cSdholland static int	problem(void);
92c62bf84cSdholland static void	showstats(int);
93c62bf84cSdholland static void	usage(void) __dead;
94ff14dd5aSlukem 
95c62bf84cSdholland static const char keylist[] = "+-x/";
96c62bf84cSdholland static const char defaultkeys[] = "+-";
97c62bf84cSdholland static const char *keys = defaultkeys;
98c62bf84cSdholland static int nkeys = sizeof(defaultkeys) - 1;
99c62bf84cSdholland static int rangemax = 10;
100c62bf84cSdholland static int nright, nwrong;
101c62bf84cSdholland static time_t qtime;
10261f28255Scgd #define	NQUESTS	20
10361f28255Scgd 
10461f28255Scgd /*
10561f28255Scgd  * Select keys from +-x/ to be asked addition, subtraction, multiplication,
10661f28255Scgd  * and division problems.  More than one key may be given.  The default is
10761f28255Scgd  * +-.  Specify a range to confine the operands to 0 - range.  Default upper
10861f28255Scgd  * bound is 10.  After every NQUESTS questions, statistics on the performance
10961f28255Scgd  * so far are printed.
11061f28255Scgd  */
11104b0ab53Sjtc int
main(int argc,char ** argv)112c62bf84cSdholland main(int argc, char **argv)
11361f28255Scgd {
11461f28255Scgd 	int ch, cnt;
11561f28255Scgd 
116dceb2464Shubertf 	/* Revoke setgid privileges */
117f9eca697Smycroft 	setgid(getgid());
118dceb2464Shubertf 
1193e66e415Slukem 	while ((ch = getopt(argc, argv, "r:o:")) != -1)
12061f28255Scgd 		switch(ch) {
12161f28255Scgd 		case 'o': {
1224e418728Shubertf 			const char *p;
12361f28255Scgd 
12461f28255Scgd 			for (p = keys = optarg; *p; ++p)
125ff14dd5aSlukem 				if (!strchr(keylist, *p))
126ff14dd5aSlukem 					errx(1, "arithmetic: unknown key.");
12761f28255Scgd 			nkeys = p - optarg;
12861f28255Scgd 			break;
12961f28255Scgd 		}
13061f28255Scgd 		case 'r':
131ff14dd5aSlukem 			if ((rangemax = atoi(optarg)) <= 0)
132ff14dd5aSlukem 				errx(1, "arithmetic: invalid range.");
13361f28255Scgd 			break;
13461f28255Scgd 		case '?':
13561f28255Scgd 		default:
13661f28255Scgd 			usage();
13761f28255Scgd 		}
13861f28255Scgd 	if (argc -= optind)
13961f28255Scgd 		usage();
14061f28255Scgd 
14161f28255Scgd 	/* Seed the random-number generator. */
1429f61b804Splunky 	srandom((int)time(NULL));
14361f28255Scgd 
14461f28255Scgd 	(void)signal(SIGINT, intr);
14561f28255Scgd 
14661f28255Scgd 	/* Now ask the questions. */
14761f28255Scgd 	for (;;) {
14861f28255Scgd 		for (cnt = NQUESTS; cnt--;)
14961f28255Scgd 			if (problem() == EOF)
15061f28255Scgd 				exit(0);
1518b821e52Shubertf 		showstats(0);
15261f28255Scgd 	}
15361f28255Scgd 	/* NOTREACHED */
15461f28255Scgd }
15561f28255Scgd 
15661f28255Scgd /* Handle interrupt character.  Print score and exit. */
157c62bf84cSdholland static void
intr(int dummy __unused)158*277bd075Sdholland intr(int dummy __unused)
15961f28255Scgd {
1608b821e52Shubertf 	showstats(1);
16161f28255Scgd 	exit(0);
16261f28255Scgd }
16361f28255Scgd 
16461f28255Scgd /* Print score.  Original `arithmetic' had a delay after printing it. */
165c62bf84cSdholland static void
showstats(int bool_sigint)166*277bd075Sdholland showstats(int bool_sigint)
16761f28255Scgd {
16861f28255Scgd 	if (nright + nwrong > 0) {
16961f28255Scgd 		(void)printf("\n\nRights %d; Wrongs %d; Score %d%%",
17061f28255Scgd 		    nright, nwrong, (int)(100L * nright / (nright + nwrong)));
17161f28255Scgd 		if (nright > 0)
17261f28255Scgd 	(void)printf("\nTotal time %ld seconds; %.1f seconds per problem\n\n",
17361f28255Scgd 			    (long)qtime, (float)qtime / nright);
17461f28255Scgd 	}
1758b821e52Shubertf 	if(!bool_sigint) {
1768b821e52Shubertf 		(void)printf("Press RETURN to continue...\n");
1778b821e52Shubertf 		while(!getchar()) ;
1788b821e52Shubertf 	}
17961f28255Scgd 	(void)printf("\n");
18061f28255Scgd }
18161f28255Scgd 
18261f28255Scgd /*
18361f28255Scgd  * Pick a problem and ask it.  Keeps asking the same problem until supplied
18461f28255Scgd  * with the correct answer, or until EOF or interrupt is typed.  Problems are
18561f28255Scgd  * selected such that the right operand and either the left operand (for +, x)
18661f28255Scgd  * or the correct result (for -, /) are in the range 0 to rangemax.  Each wrong
18761f28255Scgd  * answer causes the numbers in the problem to be penalised, so that they are
18861f28255Scgd  * more likely to appear in subsequent problems.
18961f28255Scgd  */
190c62bf84cSdholland static int
problem(void)191*277bd075Sdholland problem(void)
19261f28255Scgd {
193ff14dd5aSlukem 	char *p;
19461f28255Scgd 	time_t start, finish;
19561f28255Scgd 	int left, op, right, result;
19661f28255Scgd 	char line[80];
19761f28255Scgd 
1982aac8873Sis 	right = left = result = 0;
19961f28255Scgd 	op = keys[random() % nkeys];
20061f28255Scgd 	if (op != '/')
20161f28255Scgd 		right = getrandom(rangemax + 1, op, 1);
20261f28255Scgd retry:
20361f28255Scgd 	/* Get the operands. */
20461f28255Scgd 	switch (op) {
20561f28255Scgd 	case '+':
20661f28255Scgd 		left = getrandom(rangemax + 1, op, 0);
20761f28255Scgd 		result = left + right;
20861f28255Scgd 		break;
20961f28255Scgd 	case '-':
21061f28255Scgd 		result = getrandom(rangemax + 1, op, 0);
21161f28255Scgd 		left = right + result;
21261f28255Scgd 		break;
21361f28255Scgd 	case 'x':
21461f28255Scgd 		left = getrandom(rangemax + 1, op, 0);
21561f28255Scgd 		result = left * right;
21661f28255Scgd 		break;
21761f28255Scgd 	case '/':
21861f28255Scgd 		right = getrandom(rangemax, op, 1) + 1;
21961f28255Scgd 		result = getrandom(rangemax + 1, op, 0);
22061f28255Scgd 		left = right * result + random() % right;
22161f28255Scgd 		break;
22261f28255Scgd 	}
22361f28255Scgd 
22461f28255Scgd 	/*
22561f28255Scgd 	 * A very big maxrange could cause negative values to pop
22661f28255Scgd 	 * up, owing to overflow.
22761f28255Scgd 	 */
22861f28255Scgd 	if (result < 0 || left < 0)
22961f28255Scgd 		goto retry;
23061f28255Scgd 
23161f28255Scgd 	(void)printf("%d %c %d =   ", left, op, right);
23261f28255Scgd 	(void)fflush(stdout);
23361f28255Scgd 	(void)time(&start);
23461f28255Scgd 
23561f28255Scgd 	/*
23661f28255Scgd 	 * Keep looping until the correct answer is given, or until EOF or
23761f28255Scgd 	 * interrupt is typed.
23861f28255Scgd 	 */
23961f28255Scgd 	for (;;) {
24061f28255Scgd 		if (!fgets(line, sizeof(line), stdin)) {
24161f28255Scgd 			(void)printf("\n");
24261f28255Scgd 			return(EOF);
24361f28255Scgd 		}
24449f7d8a9Sdsl 		for (p = line; *p && isspace((unsigned char)*p); ++p);
24549f7d8a9Sdsl 		if (!isdigit((unsigned char)*p)) {
24661f28255Scgd 			(void)printf("Please type a number.\n");
24761f28255Scgd 			continue;
24861f28255Scgd 		}
24961f28255Scgd 		if (atoi(p) == result) {
25061f28255Scgd 			(void)printf("Right!\n");
25161f28255Scgd 			++nright;
25261f28255Scgd 			break;
25361f28255Scgd 		}
25461f28255Scgd 		/* Wrong answer; penalise and ask again. */
25561f28255Scgd 		(void)printf("What?\n");
25661f28255Scgd 		++nwrong;
25761f28255Scgd 		penalise(right, op, 1);
25861f28255Scgd 		if (op == 'x' || op == '+')
25961f28255Scgd 			penalise(left, op, 0);
26061f28255Scgd 		else
26161f28255Scgd 			penalise(result, op, 0);
26261f28255Scgd 	}
26361f28255Scgd 
26461f28255Scgd 	/*
26561f28255Scgd 	 * Accumulate the time taken.  Obviously rounding errors happen here;
26661f28255Scgd 	 * however they should cancel out, because some of the time you are
26761f28255Scgd 	 * charged for a partially elapsed second at the start, and some of
26861f28255Scgd 	 * the time you are not charged for a partially elapsed second at the
26961f28255Scgd 	 * end.
27061f28255Scgd 	 */
27161f28255Scgd 	(void)time(&finish);
27261f28255Scgd 	qtime += finish - start;
27361f28255Scgd 	return(0);
27461f28255Scgd }
27561f28255Scgd 
27661f28255Scgd /*
27761f28255Scgd  * Here is the code for accumulating penalties against the numbers for which
27861f28255Scgd  * a wrong answer was given.  The right operand and either the left operand
27961f28255Scgd  * (for +, x) or the result (for -, /) are stored in a list for the particular
28061f28255Scgd  * operation, and each becomes more likely to appear again in that operation.
28161f28255Scgd  * Initially, each number is charged a penalty of WRONGPENALTY, giving it that
28261f28255Scgd  * many extra chances of appearing.  Each time it is selected because of this,
28361f28255Scgd  * its penalty is decreased by one; it is removed when it reaches 0.
28461f28255Scgd  *
28561f28255Scgd  * The penalty[] array gives the sum of all penalties in the list for
28661f28255Scgd  * each operation and each operand.  The penlist[] array has the lists of
28761f28255Scgd  * penalties themselves.
28861f28255Scgd  */
28961f28255Scgd 
290c62bf84cSdholland static int penalty[sizeof(keylist) - 1][2];
291c62bf84cSdholland static struct penalty {
29261f28255Scgd 	int value, penalty;	/* Penalised value and its penalty. */
29361f28255Scgd 	struct penalty *next;
29461f28255Scgd } *penlist[sizeof(keylist) - 1][2];
29561f28255Scgd 
29661f28255Scgd #define	WRONGPENALTY	5	/* Perhaps this should depend on maxrange. */
29761f28255Scgd 
29861f28255Scgd /*
29961f28255Scgd  * Add a penalty for the number `value' to the list for operation `op',
30061f28255Scgd  * operand number `operand' (0 or 1).  If we run out of memory, we just
30161f28255Scgd  * forget about the penalty (how likely is this, anyway?).
30261f28255Scgd  */
303c62bf84cSdholland static void
penalise(int value,int op,int operand)304*277bd075Sdholland penalise(int value, int op, int operand)
30561f28255Scgd {
30661f28255Scgd 	struct penalty *p;
30761f28255Scgd 
30861f28255Scgd 	op = opnum(op);
309fe142521Sdholland 	if ((p = malloc(sizeof(*p))) == NULL)
31061f28255Scgd 		return;
31161f28255Scgd 	p->next = penlist[op][operand];
31261f28255Scgd 	penlist[op][operand] = p;
31361f28255Scgd 	penalty[op][operand] += p->penalty = WRONGPENALTY;
31461f28255Scgd 	p->value = value;
31561f28255Scgd }
31661f28255Scgd 
31761f28255Scgd /*
31861f28255Scgd  * Select a random value from 0 to maxval - 1 for operand `operand' (0 or 1)
31961f28255Scgd  * of operation `op'.  The random number we generate is either used directly
32061f28255Scgd  * as a value, or represents a position in the penalty list.  If the latter,
32161f28255Scgd  * we find the corresponding value and return that, decreasing its penalty.
32261f28255Scgd  */
323c62bf84cSdholland static int
getrandom(int maxval,int op,int operand)324*277bd075Sdholland getrandom(int maxval, int op, int operand)
32561f28255Scgd {
32661f28255Scgd 	int value;
327ff14dd5aSlukem 	struct penalty **pp, *p;
32861f28255Scgd 
32961f28255Scgd 	op = opnum(op);
33061f28255Scgd 	value = random() % (maxval + penalty[op][operand]);
33161f28255Scgd 
33261f28255Scgd 	/*
33361f28255Scgd 	 * 0 to maxval - 1 is a number to be used directly; bigger values
33461f28255Scgd 	 * are positions to be located in the penalty list.
33561f28255Scgd 	 */
33661f28255Scgd 	if (value < maxval)
33761f28255Scgd 		return(value);
33861f28255Scgd 	value -= maxval;
33961f28255Scgd 
34061f28255Scgd 	/*
34161f28255Scgd 	 * Find the penalty at position `value'; decrement its penalty and
34261f28255Scgd 	 * delete it if it reaches 0; return the corresponding value.
34361f28255Scgd 	 */
34461f28255Scgd 	for (pp = &penlist[op][operand]; (p = *pp) != NULL; pp = &p->next) {
34561f28255Scgd 		if (p->penalty > value) {
34661f28255Scgd 			value = p->value;
34761f28255Scgd 			penalty[op][operand]--;
34861f28255Scgd 			if (--(p->penalty) <= 0) {
34961f28255Scgd 				p = p->next;
35061f28255Scgd 				(void)free((char *)*pp);
35161f28255Scgd 				*pp = p;
35261f28255Scgd 			}
35361f28255Scgd 			return(value);
35461f28255Scgd 		}
35561f28255Scgd 		value -= p->penalty;
35661f28255Scgd 	}
35761f28255Scgd 	/*
35861f28255Scgd 	 * We can only get here if the value from the penalty[] array doesn't
35961f28255Scgd 	 * correspond to the actual sum of penalties in the list.  Provide an
36061f28255Scgd 	 * obscure message.
36161f28255Scgd 	 */
362ff14dd5aSlukem 	errx(1, "arithmetic: bug: inconsistent penalties.");
36361f28255Scgd 	/* NOTREACHED */
36461f28255Scgd }
36561f28255Scgd 
36661f28255Scgd /* Return an index for the character op, which is one of [+-x/]. */
367c62bf84cSdholland static int
opnum(int op)368*277bd075Sdholland opnum(int op)
36961f28255Scgd {
37061f28255Scgd 	char *p;
37161f28255Scgd 
372ff14dd5aSlukem 	if (op == 0 || (p = strchr(keylist, op)) == NULL)
373ff14dd5aSlukem 		errx(1, "arithmetic: bug: op %c not in keylist %s",
374ff14dd5aSlukem 		    op, keylist);
37561f28255Scgd 	return(p - keylist);
37661f28255Scgd }
37761f28255Scgd 
37861f28255Scgd /* Print usage message and quit. */
379c62bf84cSdholland static void
usage(void)380*277bd075Sdholland usage(void)
38161f28255Scgd {
38257bae045Schristos 	(void)fprintf(stderr, "Usage: %s [-o +-x/] [-r range]\n",
383668a4dd9Scgd 		getprogname());
38461f28255Scgd 	exit(1);
38561f28255Scgd }
386