2 * Copyright © 2006 Carl Worth
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2, or (at your option)
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA."
27 #include <sys/types.h>
34 #include <readline/readline.h>
35 #include <readline/history.h>
39 typedef struct _item {
53 CATEGORY_ORDER_RANDOM,
54 CATEGORY_ORDER_SEQUENTIAL
57 typedef struct _category {
63 /* Support sequential introduction of items from bin 0 */
64 category_order_t order;
65 /* Support categories where responses are timed (0.0 == disable). */
70 typedef struct _mnemon {
75 category_t *categories;
94 fprintf (stderr, "Error: out of memory\n");
102 xrealloc (void *ptr, size_t size)
106 ret = realloc (ptr, size);
108 fprintf (stderr, "Error: out of memory\n");
116 xstrdup (const char *s)
122 fprintf (stderr, "Error: out of memory\n");
130 xstrndup (const char *s, size_t n)
134 ret = strndup (s, n);
136 fprintf (stderr, "Error: out of memory\n");
144 xasprintf (char **strp, const char *fmt, ...)
150 ret = vasprintf (strp, fmt, ap);
154 fprintf (stderr, "Error: out of memory\n");
160 item_init (item_t *item,
162 const char *challenge,
163 const char *response)
167 item->challenge = xmalloc (strlen (challenge) + 1 +
168 strlen (response) + 1);
169 item->response = item->challenge + strlen (challenge) + 1;
171 strcpy (item->challenge, challenge);
172 strcpy (item->response, response);
176 item_fini (item_t *item)
178 /* item->response shares allocation with item->challenge, so
179 * doesn't require a separate call to free */
180 free (item->challenge);
184 category_init (category_t *category,
187 category->name = xstrdup (name);
189 category->items_size = 0;
190 category->num_items = 0;
191 category->items = NULL;
192 category->order = CATEGORY_ORDER_RANDOM;
193 category->time_limit = 0.0;
194 category->bin_zero_head = 0;
198 category_fini (category_t *category)
202 for (i = 0; i < category->num_items; i++)
203 item_fini (&category->items[i]);
205 free (category->items);
207 free (category->name);
211 category_grow (category_t *category)
213 if (category->items_size)
214 category->items_size *= 2;
216 category->items_size = 1;
218 category->items = xrealloc (category->items,
219 category->items_size * sizeof (item_t));
223 category_add_item (category_t *category,
225 const char *challenge,
226 const char *response)
230 if (category->num_items == category->items_size)
231 category_grow (category);
233 item = &category->items[category->num_items++];
235 item_init (item, score, challenge, response);
241 category_next_bin_zero_item (category_t *category)
243 int *i = &category->bin_zero_head;
245 for ( ; *i < category->num_items; *i = *i + 1)
246 if (category->items[*i].score == 0)
247 return &category->items[*i];
253 category_print (category_t *category,
259 fprintf (file, "order = %s\n\n",
260 category->order == CATEGORY_ORDER_RANDOM ? "random" : "sequential");
261 fprintf (file, "time = %f\n\n",
262 category->time_limit);
264 for (i = 0; i < category->num_items; i++) {
265 item = &category->items[i];
267 fprintf (file, "\n");
268 fprintf (file, "%d\n%s\n%s\n",
276 bin_init (bin_t *bin,
287 bin_fini (bin_t *bin)
293 bin_grow (bin_t *bin)
296 bin->items_size *= 2;
300 bin->items = xrealloc (bin->items,
301 bin->items_size * sizeof (item_t*));
305 bin_add_item (bin_t *bin,
308 assert (item->score == bin->score);
310 if (bin->num_items == bin->items_size)
313 bin->items[bin->num_items++] = item;
317 bin_remove_item (bin_t *bin,
320 /* Replace the current item with the last item, (no need to shift
321 * any more than that since we don't care about the order of the
322 * items within a bin). */
325 bin->items[item_index] = bin->items[bin->num_items];
328 /* Find the index for an item within a bin.
330 * XXX: This is currently a linear search, so is a potential
331 * performance problem.
334 bin_item_index (bin_t *bin,
339 for (i = 0; i < bin->num_items; i++)
340 if (bin->items[i] == item)
346 typedef int (item_match_predicate_t) (void *closure, item_t *item);
348 /* Return the number of items in the bin from the given category (or
349 * from all categories if category == NULL) */
351 bin_num_items_matching (bin_t *bin,
352 item_match_predicate_t *predicate,
355 int i, num_items = 0;
357 if (predicate == NULL)
358 return bin->num_items;
360 for (i = 0; i < bin->num_items; i++)
361 if ((predicate) (closure, bin->items[i]))
368 mnemon_init (mnemon_t *mnemon)
372 home = getenv ("HOME");
376 xasprintf (&mnemon->dir_name, "%s/.mnemon", getenv ("HOME"));
378 mnemon->categories_size = 0;
379 mnemon->num_categories = 0;
380 mnemon->categories = NULL;
382 mnemon->bins_size = 0;
383 mnemon->num_bins = 0;
386 mnemon->to_introduce = 10;
387 mnemon->to_master = 10;
388 mnemon->unlearned = 0;
389 mnemon->mastered = -1;
393 mnemon_fini (mnemon_t *mnemon)
397 for (i = 0; i < mnemon->num_bins; i++)
398 bin_fini (&mnemon->bins[i]);
401 for (i = 0; i < mnemon->num_categories; i++)
402 category_fini (&mnemon->categories[i]);
403 free (mnemon->categories);
405 free (mnemon->dir_name);
409 mnemon_categories_grow (mnemon_t *mnemon)
411 if (mnemon->categories_size)
412 mnemon->categories_size *= 2;
414 mnemon->categories_size = 1;
416 mnemon->categories = xrealloc (mnemon->categories,
417 mnemon->categories_size * sizeof (category_t));
420 /* Get a category by name if it exists */
422 mnemon_get_category_if_exists (mnemon_t *mnemon,
427 for (i = 0; i < mnemon->num_categories; i++)
428 if (strcmp (mnemon->categories[i].name, name) == 0)
429 return &mnemon->categories[i];
434 /* Get a category by name, creating new one if necessary. */
436 mnemon_get_category (mnemon_t *mnemon,
439 category_t *category;
441 category = mnemon_get_category_if_exists (mnemon, name);
445 mnemon_categories_grow (mnemon);
447 category = &mnemon->categories[mnemon->num_categories++];
449 category_init (category, name);
455 mnemon_bins_grow (mnemon_t *mnemon)
457 if (mnemon->bins_size)
458 mnemon->bins_size *= 2;
460 mnemon->bins_size = 1;
462 mnemon->bins = xrealloc (mnemon->bins,
463 mnemon->bins_size * sizeof (bin_t));
467 mnemon_get_bin (mnemon_t *mnemon,
473 for (i = 0; i < mnemon->num_bins; i++)
474 if (mnemon->bins[i].score == score)
475 return &mnemon->bins[i];
476 else if (mnemon->bins[i].score > score)
479 if (mnemon->num_bins == mnemon->bins_size)
480 mnemon_bins_grow (mnemon);
482 bin = &mnemon->bins[i];
484 /* Make room to insert new bin at its sorted location. */
485 if (i < mnemon->num_bins)
486 memmove (bin + 1, bin, (mnemon->num_bins - i) * sizeof (bin_t));
489 bin_init (bin, score);
495 mnemon_remove_bin (mnemon_t *mnemon,
498 int i = bin - mnemon->bins;
502 memmove (bin, bin + 1, (mnemon->num_bins - i) * sizeof (bin_t));
509 int len = strlen (s);
512 if (s[len - 1] == '\n')
517 trim_space (char *string)
522 while (*s && isspace (*s))
527 s = string + strlen (string) - 1;
528 while (s > string && isspace (*s)) {
537 mnemon_load_category (mnemon_t *mnemon,
541 char *line = NULL, *end;
542 size_t line_size = 0;
546 category_t *category;
549 path = xmalloc (strlen (mnemon->dir_name) + 1 + strlen (name) + 1);
550 sprintf (path, "%s/%s", mnemon->dir_name, name);
552 file = fopen (path, "r");
554 fprintf (stderr, "Error: Failed to open %s: %s\n",
555 path, strerror (errno));
559 category = mnemon_get_category (mnemon, name);
561 #define READ_LINE do { \
562 bytes_read = getline (&line, &line_size, file); \
563 if (bytes_read == -1) \
571 char *name, *equal, *value;
573 /* Ignore blank lines */
578 /* An initial digit means we hit an item. Trigger the
579 * spaghetti machine. */
580 if (*line >= '0' && *line <= '9')
583 equal = strchr (line, '=');
585 fprintf (stderr, "Malformed option, (expected name=value): \"%s\" at %s:%d\n",
586 line, path, line_count);
594 name = trim_space (name);
595 value = trim_space (value);
597 if (strcmp (name, "order") == 0) {
598 if (strcmp (value, "sequential") == 0) {
599 category->order = CATEGORY_ORDER_SEQUENTIAL;
600 } else if (strcmp (value, "random") == 0) {
601 category->order = CATEGORY_ORDER_RANDOM;
603 fprintf (stderr, "Unknown value for \"order\" option \"%s\" at %s:%d\n",
604 value, path, line_count);
607 } else if (strcmp (name, "time") == 0) {
610 limit = strtod (value, &end);
611 while (isspace (*end))
614 category->time_limit = limit;
616 fprintf (stderr, "Failed to parse time value: %s at %s:%d\n",
617 value, path, line_count);
621 fprintf (stderr, "Unknown option %s at %s:%d\n",
622 name, path, line_count);
630 char *challenge, *response;
632 /* Ignore blank lines */
637 /* Read bin number */
639 score = strtol (line, &end, 10);
641 fprintf (stderr, "Failed to parse bin number from \"%s\" at %s:%d\n",
642 line, path, line_count);
648 challenge = strdup (line);
654 category_add_item (category, score, challenge, response);
664 /* Resize category items to fit exactly. */
665 category->items_size = category->num_items;
666 category->items = xrealloc (category->items, category->items_size * sizeof (item_t));
668 /* Now that the category is completely loaded, with stable
669 * pointers to every item, we can add each item to its appropriate
671 for (i = 0; i < category->num_items; i++) {
672 item_t *item = &category->items[i];
673 bin_t *bin = mnemon_get_bin (mnemon, item->score);
675 bin_add_item (bin, item);
680 mnemon_load (mnemon_t *mnemon)
683 struct dirent *dirent;
685 dir = opendir (mnemon->dir_name);
687 fprintf (stderr, "Error: Failed to open directory %s: %s\n",
688 mnemon->dir_name, strerror (errno));
693 dirent = readdir (dir);
697 if (dirent->d_type == DT_REG) {
698 /* Ignore files matching *~, (yes, this shouldn't be
699 * hard-coded in such an ad-hoc way, but there you go. */
700 if (dirent->d_name[strlen(dirent->d_name)-1] != '~')
701 mnemon_load_category (mnemon, dirent->d_name);
709 mnemon_save (mnemon_t *mnemon)
712 char *filename, *lock_filename;
714 category_t *category;
716 for (i = 0; i < mnemon->num_categories; i++) {
717 category = &mnemon->categories[i];
719 xasprintf (&filename, "%s/%s",
720 mnemon->dir_name, category->name);
721 xasprintf (&lock_filename, "%s/.#%s",
722 mnemon->dir_name, category->name);
724 file = fopen (lock_filename, "w");
726 fprintf (stderr, "Error: Failed to open %s for writing: %s\n",
727 lock_filename, strerror (errno));
731 category_print (category, file);
735 err = rename (lock_filename, filename);
737 fprintf (stderr, "Error: Failed to rename %s to %s: %s\n",
738 lock_filename, filename, strerror (errno));
743 free (lock_filename);
747 /* Return a uniformly-distributed pseudo-random integer within the
750 * 0 <= result < num_values
753 rand_within (int num_values)
755 return (int) (num_values * (rand() / (RAND_MAX + 1.0)));
758 /* Return an exponentially-distributed pseudo-random integer within
761 * 0 <= result < num_values
763 * The distribution is such that each successively larger value will
764 * occur with a probability of half of the previous value.
767 rand_within_exponential (int num_values)
770 static uint32_t mask = 0;
774 /* Optimize the constant case. */
784 while (mask > RAND_MAX)
791 if (ones == num_values)
799 /* Find the category to which an item belongs. */
801 mnemon_item_category (mnemon_t *mnemon,
804 category_t *category;
807 for (i = 0; i < mnemon->num_categories; i++) {
808 category = &mnemon->categories[i];
809 item_index = item - category->items;
810 if (item_index >= 0 && item_index < category->num_items)
817 typedef struct _item_in_category_closure
820 category_t *category;
821 } item_in_category_closure_t;
824 mnemon_item_in_category (void *closure, item_t *item)
826 item_in_category_closure_t *iicc = closure;
827 mnemon_t *mnemon = iicc->mnemon;
828 category_t *category = iicc->category;
830 return (mnemon_item_category (mnemon, item) == category);
833 typedef struct _item_in_category_of_length_closure
836 category_t *category;
838 } item_in_category_of_length_closure_t;
841 mnemon_item_in_category_of_length (void *closure, item_t *item)
843 item_in_category_of_length_closure_t *iicolc = closure;
844 mnemon_t *mnemon = iicolc->mnemon;
845 category_t *category = iicolc->category;
846 int length = iicolc->length;
848 if (mnemon_item_category (mnemon, item) != category)
851 return strlen (item->challenge) == length;
855 mnemon_select_item (mnemon_t *mnemon,
858 category_t **category_ret)
860 int bin_index, item_index;
863 category_t *category;
865 bin_index = rand_within_exponential (mnemon->num_bins);
867 bin = &mnemon->bins[bin_index];
869 item_index = rand_within (bin->num_items);
871 item = bin->items[item_index];
872 category = mnemon_item_category (mnemon, item);
874 if (bin->score == 0) {
875 if (category->order == CATEGORY_ORDER_SEQUENTIAL) {
876 item = category_next_bin_zero_item (category);
878 item_index = bin_item_index (bin, item);
883 *item_index_ret = item_index;
884 *category_ret = category;
888 #define HISTOGRAM_ROW_FORMAT "%3d: %3d"
889 #define HISTOGRAM_BAR_WIDTH 63
892 print_histogram_bar (double size,
895 int units_per_cell = (int) ceil (max / HISTOGRAM_BAR_WIDTH);
896 static char const *boxes[8] = {
901 while (size > units_per_cell) {
903 size -= units_per_cell;
906 size /= units_per_cell;
910 else if (size > 6.5/8.0)
912 else if (size > 5.5/8.0)
914 else if (size > 4.5/8.0)
916 else if (size > 3.5/8.0)
918 else if (size > 2.5/8.0)
920 else if (size > 1.5/8.0)
922 else if (size > 0.5/8.0)
929 mnemon_print_histogram (mnemon_t *mnemon,
930 const char *category_name,
933 int i, last_score, max;
934 category_t *category = NULL;
937 item_match_predicate_t *predicate = NULL;
938 void *closure = NULL;
939 item_in_category_closure_t item_in_category;
940 item_in_category_of_length_closure_t item_in_category_of_length;
942 if (mnemon->num_bins == 0)
946 category = mnemon_get_category_if_exists (mnemon, category_name);
949 predicate = mnemon_item_in_category_of_length;
950 item_in_category_of_length.mnemon = mnemon;
951 item_in_category_of_length.category = category;
952 item_in_category_of_length.length = length;
953 closure = &item_in_category_of_length;
955 predicate = mnemon_item_in_category;
956 item_in_category.mnemon = mnemon;
957 item_in_category.category = category;
958 closure = &item_in_category;
963 for (i = 0; i < mnemon->num_bins; i++) {
964 num_items = bin_num_items_matching (&mnemon->bins[i],
966 if (i == 0 || num_items > max)
970 for (i = 0; i < mnemon->num_bins; i++) {
971 bin = &mnemon->bins[i];
973 while (bin->score - last_score > 1)
974 printf (HISTOGRAM_ROW_FORMAT "\n", ++last_score, 0);
975 num_items = bin_num_items_matching (bin,
977 printf (HISTOGRAM_ROW_FORMAT " ", bin->score, num_items);
978 print_histogram_bar (num_items, max);
979 last_score = bin->score;
984 mnemon_handle_command (mnemon_t *mnemon,
989 switch (command[0]) {
992 char *category = NULL;
996 arg += strspn (arg, " \t");
997 len = strcspn (arg, " \t");
999 category = xstrndup (arg, len);
1001 arg += strspn (arg, " \t");
1003 length = atoi (arg);
1005 mnemon_print_histogram (mnemon, category, length);
1009 printf ("Unknown command: %s\n", command);
1015 mnemon_handle_response (mnemon_t *mnemon,
1019 const char *response,
1020 double response_time,
1025 correct = (strcmp (response, item->response) == 0);
1027 bin_remove_item (bin, item_index);
1029 /* If the bin is now empty, we must remove it. Also if we just
1030 * picked the last word we'll ever pick from the bin with
1031 * score 0, then we can remove that as well. */
1032 if (bin->num_items == 0 ||
1033 (bin->score == 0 && mnemon->to_introduce == 0))
1035 mnemon_remove_bin (mnemon, bin);
1039 (time_limit == 0.0 || response_time < time_limit))
1042 mnemon->to_master--;
1043 /* We reserve an item score of 0 for an item that has
1044 * never been asked. */
1045 if (item->score == 0) {
1047 mnemon->unlearned--;
1048 mnemon->to_master--;
1049 printf ("You got it!");
1050 } else if (item->score < 0) {
1051 printf ("Yes---just give me %d more.",
1053 } else if (item->score == 1) {
1054 printf ("On your first try, no less!");
1056 printf ("Masterful (%dx).", item->score);
1060 printf (" %s is the correct answer.",
1063 printf ("Correct, but not quite quick enough (%0.2f seconds---needed %0.2f seconds)\n",
1064 response_time, time_limit);
1065 /* Penalize an incorrect response by forcing the score
1067 if (item->score >= 0) {
1068 if (item->score > 0)
1069 printf (" Oops, you knew that, right? (%dx)\n ",
1071 mnemon->unlearned++;
1072 /* We add three here, (rather than just 2 to track the
1073 * change in the item's score below), as an extra
1074 * penalty. If the user is forgetting stuff learned
1075 * previously, then more time should be spent on mastering
1076 * than learning new items. */
1077 mnemon->to_master += item->score + 3;
1078 /* We go to -2 to force a little extra reinforcement
1079 * when re-learning an item, (otherwise, it will often
1080 * get asked again immediately where it is easy to get
1081 * a correct response without any learning). */
1085 mnemon->to_master++;
1090 if (mnemon->to_introduce)
1091 printf ("%d to come. ", mnemon->to_introduce);
1092 if (mnemon->unlearned)
1093 printf ("%d still unlearned. ", mnemon->unlearned);
1094 if (mnemon->to_introduce == 0 && mnemon->to_master > 0)
1095 printf ("%d items to master", mnemon->to_master);
1098 bin = mnemon_get_bin (mnemon, item->score);
1100 bin_add_item (bin, item);
1104 mnemon_do_challenges (mnemon_t *mnemon)
1109 category_t *category;
1113 /* Count the number of items with negative scores. */
1114 mnemon->unlearned = 0;
1115 for (i = 0; i < mnemon->num_bins; i++) {
1116 bin = &mnemon->bins[i];
1117 if (bin->score >= 0)
1119 mnemon->unlearned += bin->num_items;
1122 mnemon->to_introduce -= mnemon->unlearned;
1123 if (mnemon->to_introduce < 0)
1124 mnemon->to_introduce = 0;
1126 /* Get rid of bin with score of 0 if we aren't going to be
1127 * introducing anything from it. */
1128 if (mnemon->to_introduce == 0) {
1129 bin = mnemon_get_bin (mnemon, 0);
1130 mnemon_remove_bin (mnemon, bin);
1133 if (mnemon->unlearned) {
1134 printf ("You've got %d items to learn already. ", mnemon->unlearned);
1135 if (mnemon->to_introduce)
1136 printf ("I'll introduce %d more as we go.", mnemon->to_introduce);
1139 printf ("Introducing %d new items.\n", mnemon->to_introduce);
1144 struct timeval start, end;
1146 mnemon_select_item (mnemon, &bin, &item_index, &category);
1147 item = bin->items[item_index];
1149 if (bin->score == 0)
1150 mnemon->to_introduce--;
1153 if (category->time_limit > 0.0) {
1154 response = readline ("The next one is timed. Press enter when ready:");
1158 printf ("%s\n", item->challenge);
1160 gettimeofday (&start, NULL);
1161 response = readline ("> ");
1162 gettimeofday (&end, NULL);
1164 /* Terminate on EOF */
1165 if (response == NULL) {
1170 if (response[0] == '/') {
1171 mnemon_handle_command (mnemon, response + 1);
1178 mnemon_handle_response (mnemon, bin, item_index,
1180 (end.tv_sec + end.tv_usec / 1e6) -
1181 (start.tv_sec + start.tv_usec / 1e6),
1182 category->time_limit);
1184 } while (mnemon->to_introduce ||
1185 mnemon->unlearned ||
1186 mnemon->to_master > 0);
1188 printf ("Great job.\nHere are your current results:\n");
1189 mnemon_print_histogram (mnemon, NULL, 0);
1190 response = readline ("Press enter to quit.\n");
1195 main (int argc, char *argv[])
1199 srand (time (NULL));
1201 mnemon_init (&mnemon);
1203 mnemon_load (&mnemon);
1205 mnemon_do_challenges (&mnemon);
1207 mnemon_save (&mnemon);
1209 mnemon_fini (&mnemon);