arithmetic.c 11 KB

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