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