1 /* $OpenBSD: arithmetic.c,v 1.8 1998/09/15 05:22:45 pjanzen 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[] = "$OpenBSD: arithmetic.c,v 1.8 1998/09/15 05:22:45 pjanzen Exp $"; 50 #endif 51 #endif /* not lint */ 52 53 /* 54 * By Eamonn McManus, Trinity College Dublin <emcmanus@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 <err.h> 83 #include <ctype.h> 84 #include <signal.h> 85 #include <stdio.h> 86 #include <stdlib.h> 87 #include <string.h> 88 #include <time.h> 89 #include <unistd.h> 90 91 int getrandom __P((int, int, int)); 92 void intr __P((int)); 93 int opnum __P((int)); 94 void penalise __P((int, int, int)); 95 int problem __P((void)); 96 void showstats __P((void)); 97 void usage __P((void)); 98 99 const char keylist[] = "+-x/"; 100 const char defaultkeys[] = "+-"; 101 const char *keys = defaultkeys; 102 int nkeys = sizeof(defaultkeys) - 1; 103 int rangemax = 10; 104 int nright, nwrong; 105 time_t qtime; 106 #define NQUESTS 20 107 108 /* 109 * Select keys from +-x/ to be asked addition, subtraction, multiplication, 110 * and division problems. More than one key may be given. The default is 111 * +-. Specify a range to confine the operands to 0 - range. Default upper 112 * bound is 10. After every NQUESTS questions, statistics on the performance 113 * so far are printed. 114 */ 115 int 116 main(argc, argv) 117 int argc; 118 char **argv; 119 { 120 extern char *optarg; 121 extern int optind; 122 int ch, cnt; 123 124 /* revoke privs */ 125 setegid(getgid()); 126 setgid(getgid()); 127 128 while ((ch = getopt(argc, argv, "hr:o:")) != -1) 129 switch(ch) { 130 case 'o': { 131 const char *p; 132 133 for (p = keys = optarg; *p; ++p) 134 if (!strchr(keylist, *p)) 135 errx(1, "unknown key."); 136 nkeys = p - optarg; 137 break; 138 } 139 case 'r': 140 if ((rangemax = atoi(optarg)) <= 0) 141 errx(1, "invalid range."); 142 break; 143 case '?': 144 case 'h': 145 default: 146 usage(); 147 } 148 if (argc -= optind) 149 usage(); 150 151 /* Seed the random-number generator. */ 152 srandom((int)time((time_t *)NULL)); 153 154 (void)signal(SIGINT, intr); 155 156 /* Now ask the questions. */ 157 for (;;) { 158 for (cnt = NQUESTS; cnt--;) 159 if (problem() == EOF) 160 intr(0); /* Print score and exit */ 161 showstats(); 162 } 163 /* NOTREACHED */ 164 } 165 166 /* Handle interrupt character. Print score and exit. */ 167 void 168 intr(dummy) 169 int dummy; 170 { 171 showstats(); 172 exit(0); 173 } 174 175 /* Print score. Original `arithmetic' had a delay after printing it. */ 176 void 177 showstats() 178 { 179 if (nright + nwrong > 0) { 180 (void)printf("\n\nRights %d; Wrongs %d; Score %d%%", 181 nright, nwrong, (int)(100L * nright / (nright + nwrong))); 182 if (nright > 0) 183 (void)printf("\nTotal time %ld seconds; %.1f seconds per problem\n\n", 184 (long)qtime, (float)qtime / nright); 185 } 186 (void)printf("\n"); 187 } 188 189 /* 190 * Pick a problem and ask it. Keeps asking the same problem until supplied 191 * with the correct answer, or until EOF or interrupt is typed. Problems are 192 * selected such that the right operand and either the left operand (for +, x) 193 * or the correct result (for -, /) are in the range 0 to rangemax. Each wrong 194 * answer causes the numbers in the problem to be penalised, so that they are 195 * more likely to appear in subsequent problems. 196 */ 197 int 198 problem() 199 { 200 register char *p; 201 time_t start, finish; 202 int left, op, right, result; 203 char line[80]; 204 205 op = keys[random() % nkeys]; 206 if (op != '/') 207 right = getrandom(rangemax + 1, op, 1); 208 retry: 209 /* Get the operands. */ 210 switch (op) { 211 case '+': 212 left = getrandom(rangemax + 1, op, 0); 213 result = left + right; 214 break; 215 case '-': 216 result = getrandom(rangemax + 1, op, 0); 217 left = right + result; 218 break; 219 case 'x': 220 left = getrandom(rangemax + 1, op, 0); 221 result = left * right; 222 break; 223 case '/': 224 right = getrandom(rangemax, op, 1) + 1; 225 result = getrandom(rangemax + 1, op, 0); 226 left = right * result + random() % right; 227 break; 228 } 229 230 /* 231 * A very big maxrange could cause negative values to pop 232 * up, owing to overflow. 233 */ 234 if (result < 0 || left < 0) 235 goto retry; 236 237 (void)printf("%d %c %d = ", left, op, right); 238 (void)fflush(stdout); 239 (void)time(&start); 240 241 /* 242 * Keep looping until the correct answer is given, or until EOF or 243 * interrupt is typed. 244 */ 245 for (;;) { 246 if (!fgets(line, sizeof(line), stdin)) { 247 (void)printf("\n"); 248 return(EOF); 249 } 250 for (p = line; *p && isspace(*p); ++p); 251 if (!isdigit(*p)) { 252 (void)printf("Please type a number.\n"); 253 continue; 254 } 255 if (atoi(p) == result) { 256 (void)printf("Right!\n"); 257 ++nright; 258 break; 259 } 260 /* Wrong answer; penalise and ask again. */ 261 (void)printf("What?\n"); 262 ++nwrong; 263 penalise(right, op, 1); 264 if (op == 'x' || op == '+') 265 penalise(left, op, 0); 266 else 267 penalise(result, op, 0); 268 } 269 270 /* 271 * Accumulate the time taken. Obviously rounding errors happen here; 272 * however they should cancel out, because some of the time you are 273 * charged for a partially elapsed second at the start, and some of 274 * the time you are not charged for a partially elapsed second at the 275 * end. 276 */ 277 (void)time(&finish); 278 qtime += finish - start; 279 return(0); 280 } 281 282 /* 283 * Here is the code for accumulating penalties against the numbers for which 284 * a wrong answer was given. The right operand and either the left operand 285 * (for +, x) or the result (for -, /) are stored in a list for the particular 286 * operation, and each becomes more likely to appear again in that operation. 287 * Initially, each number is charged a penalty of WRONGPENALTY, giving it that 288 * many extra chances of appearing. Each time it is selected because of this, 289 * its penalty is decreased by one; it is removed when it reaches 0. 290 * 291 * The penalty[] array gives the sum of all penalties in the list for 292 * each operation and each operand. The penlist[] array has the lists of 293 * penalties themselves. 294 */ 295 296 int penalty[sizeof(keylist) - 1][2]; 297 struct penalty { 298 int value, penalty; /* Penalised value and its penalty. */ 299 struct penalty *next; 300 } *penlist[sizeof(keylist) - 1][2]; 301 302 #define WRONGPENALTY 5 /* Perhaps this should depend on maxrange. */ 303 304 /* 305 * Add a penalty for the number `value' to the list for operation `op', 306 * operand number `operand' (0 or 1). If we run out of memory, we just 307 * forget about the penalty (how likely is this, anyway?). 308 */ 309 void 310 penalise(value, op, operand) 311 int value, op, operand; 312 { 313 struct penalty *p; 314 315 op = opnum(op); 316 if ((p = (struct penalty *)malloc((u_int)sizeof(*p))) == NULL) 317 return; 318 p->next = penlist[op][operand]; 319 penlist[op][operand] = p; 320 penalty[op][operand] += p->penalty = WRONGPENALTY; 321 p->value = value; 322 } 323 324 /* 325 * Select a random value from 0 to maxval - 1 for operand `operand' (0 or 1) 326 * of operation `op'. The random number we generate is either used directly 327 * as a value, or represents a position in the penalty list. If the latter, 328 * we find the corresponding value and return that, decreasing its penalty. 329 */ 330 int 331 getrandom(maxval, op, operand) 332 int maxval, op, operand; 333 { 334 int value; 335 register struct penalty **pp, *p; 336 337 op = opnum(op); 338 value = random() % (maxval + penalty[op][operand]); 339 340 /* 341 * 0 to maxval - 1 is a number to be used directly; bigger values 342 * are positions to be located in the penalty list. 343 */ 344 if (value < maxval) 345 return(value); 346 value -= maxval; 347 348 /* 349 * Find the penalty at position `value'; decrement its penalty and 350 * delete it if it reaches 0; return the corresponding value. 351 */ 352 for (pp = &penlist[op][operand]; (p = *pp) != NULL; pp = &p->next) { 353 if (p->penalty > value) { 354 value = p->value; 355 penalty[op][operand]--; 356 if (--(p->penalty) <= 0) { 357 p = p->next; 358 (void)free((char *)*pp); 359 *pp = p; 360 } 361 return(value); 362 } 363 value -= p->penalty; 364 } 365 /* 366 * We can only get here if the value from the penalty[] array doesn't 367 * correspond to the actual sum of penalties in the list. Provide an 368 * obscure message. 369 */ 370 errx(1, "bug: inconsistent penalties\n"); 371 /* NOTREACHED */ 372 } 373 374 /* Return an index for the character op, which is one of [+-x/]. */ 375 int 376 opnum(op) 377 int op; 378 { 379 char *p; 380 381 if (op == 0 || (p = strchr(keylist, op)) == NULL) 382 errx(1, "bug: op %c not in keylist %s\n", op, keylist); 383 return(p - keylist); 384 } 385 386 /* Print usage message and quit. */ 387 void 388 usage() 389 { 390 (void)fprintf(stderr, "usage: arithmetic [-o +-x/] [-r range]\n"); 391 exit(1); 392 } 393