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