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>
33 #include <readline/readline.h>
34 #include <readline/history.h>
38 typedef struct _item {
52 CATEGORY_ORDER_RANDOM,
53 CATEGORY_ORDER_SEQUENTIAL
56 typedef struct _category {
62 /* Support sequential introduction of items from bin 0 */
63 category_order_t order;
67 typedef struct _mnemon {
72 category_t *categories;
91 fprintf (stderr, "Error: out of memory\n");
99 xrealloc (void *ptr, size_t size)
103 ret = realloc (ptr, size);
105 fprintf (stderr, "Error: out of memory\n");
113 xstrdup (const char *s)
119 fprintf (stderr, "Error: out of memory\n");
127 xasprintf (char **strp, const char *fmt, ...)
133 ret = vasprintf (strp, fmt, ap);
137 fprintf (stderr, "Error: out of memory\n");
143 item_init (item_t *item,
145 const char *challenge,
146 const char *response)
150 item->challenge = xmalloc (strlen (challenge) + 1 +
151 strlen (response) + 1);
152 item->response = item->challenge + strlen (challenge) + 1;
154 strcpy (item->challenge, challenge);
155 strcpy (item->response, response);
159 item_fini (item_t *item)
161 /* item->response shares allocation with item->challenge, so
162 * doesn't require a separate call to free */
163 free (item->challenge);
167 category_init (category_t *category,
170 category->name = xstrdup (name);
172 category->items_size = 0;
173 category->num_items = 0;
174 category->items = NULL;
175 category->order = CATEGORY_ORDER_RANDOM;
176 category->bin_zero_head = 0;
180 category_fini (category_t *category)
184 for (i = 0; i < category->num_items; i++)
185 item_fini (&category->items[i]);
187 free (category->items);
189 free (category->name);
193 category_grow (category_t *category)
195 if (category->items_size)
196 category->items_size *= 2;
198 category->items_size = 1;
200 category->items = xrealloc (category->items,
201 category->items_size * sizeof (item_t));
205 category_add_item (category_t *category,
207 const char *challenge,
208 const char *response)
212 if (category->num_items == category->items_size)
213 category_grow (category);
215 item = &category->items[category->num_items++];
217 item_init (item, score, challenge, response);
223 category_next_bin_zero_item (category_t *category)
225 int *i = &category->bin_zero_head;
227 for ( ; *i < category->num_items; *i = *i + 1)
228 if (category->items[*i].score == 0)
229 return &category->items[*i];
235 category_print (category_t *category,
241 fprintf (file, "order = %s\n\n",
242 category->order == CATEGORY_ORDER_RANDOM ? "random" : "sequential");
244 for (i = 0; i < category->num_items; i++) {
245 item = &category->items[i];
247 fprintf (file, "\n");
248 fprintf (file, "%d\n%s\n%s\n",
256 bin_init (bin_t *bin,
267 bin_fini (bin_t *bin)
273 bin_grow (bin_t *bin)
276 bin->items_size *= 2;
280 bin->items = xrealloc (bin->items,
281 bin->items_size * sizeof (item_t*));
285 bin_add_item (bin_t *bin,
288 assert (item->score == bin->score);
290 if (bin->num_items == bin->items_size)
293 bin->items[bin->num_items++] = item;
297 bin_remove_item (bin_t *bin,
300 /* Replace the current item with the last item, (no need to shift
301 * any more than that since we don't care about the order of the
302 * items within a bin). */
305 bin->items[item_index] = bin->items[bin->num_items];
308 /* Find the index for an item within a bin.
310 * XXX: This is currently a linear search, so is a potential
311 * performance problem.
314 bin_item_index (bin_t *bin,
319 for (i = 0; i < bin->num_items; i++)
320 if (bin->items[i] == item)
326 typedef int (item_match_predicate_t) (void *closure, item_t *item);
328 /* Return the number of items in the bin from the given category (or
329 * from all categories if category == NULL) */
331 bin_num_items_matching (bin_t *bin,
332 item_match_predicate_t *predicate,
335 int i, num_items = 0;
337 if (predicate == NULL)
338 return bin->num_items;
340 for (i = 0; i < bin->num_items; i++)
341 if ((predicate) (closure, bin->items[i]))
348 mnemon_init (mnemon_t *mnemon)
352 home = getenv ("HOME");
356 xasprintf (&mnemon->dir_name, "%s/.mnemon", getenv ("HOME"));
358 mnemon->categories_size = 0;
359 mnemon->num_categories = 0;
360 mnemon->categories = NULL;
362 mnemon->bins_size = 0;
363 mnemon->num_bins = 0;
366 mnemon->to_introduce = 10;
367 mnemon->to_master = 0;
368 mnemon->unlearned = 0;
369 mnemon->mastered = -1;
373 mnemon_fini (mnemon_t *mnemon)
377 for (i = 0; i < mnemon->num_bins; i++)
378 bin_fini (&mnemon->bins[i]);
381 for (i = 0; i < mnemon->num_categories; i++)
382 category_fini (&mnemon->categories[i]);
383 free (mnemon->categories);
385 free (mnemon->dir_name);
389 mnemon_categories_grow (mnemon_t *mnemon)
391 if (mnemon->categories_size)
392 mnemon->categories_size *= 2;
394 mnemon->categories_size = 1;
396 mnemon->categories = xrealloc (mnemon->categories,
397 mnemon->categories_size * sizeof (category_t));
400 /* Get a category by name if it exists */
402 mnemon_get_category_if_exists (mnemon_t *mnemon,
407 for (i = 0; i < mnemon->num_categories; i++)
408 if (strcmp (mnemon->categories[i].name, name) == 0)
409 return &mnemon->categories[i];
414 /* Get a category by name, creating new one if necessary. */
416 mnemon_get_category (mnemon_t *mnemon,
419 category_t *category;
421 category = mnemon_get_category_if_exists (mnemon, name);
425 mnemon_categories_grow (mnemon);
427 category = &mnemon->categories[mnemon->num_categories++];
429 category_init (category, name);
435 mnemon_bins_grow (mnemon_t *mnemon)
437 if (mnemon->bins_size)
438 mnemon->bins_size *= 2;
440 mnemon->bins_size = 1;
442 mnemon->bins = xrealloc (mnemon->bins,
443 mnemon->bins_size * sizeof (bin_t));
447 mnemon_get_bin (mnemon_t *mnemon,
453 for (i = 0; i < mnemon->num_bins; i++)
454 if (mnemon->bins[i].score == score)
455 return &mnemon->bins[i];
456 else if (mnemon->bins[i].score > score)
459 if (mnemon->num_bins == mnemon->bins_size)
460 mnemon_bins_grow (mnemon);
462 bin = &mnemon->bins[i];
464 /* Make room to insert new bin at its sorted location. */
465 if (i < mnemon->num_bins)
466 memmove (bin + 1, bin, (mnemon->num_bins - i) * sizeof (bin_t));
469 bin_init (bin, score);
475 mnemon_remove_bin (mnemon_t *mnemon,
478 int i = bin - mnemon->bins;
482 memmove (bin, bin + 1, (mnemon->num_bins - i) * sizeof (bin_t));
489 int len = strlen (s);
492 if (s[len - 1] == '\n')
497 trim_space (char *string)
502 while (*s && isspace (*s))
507 s = string + strlen (string) - 1;
508 while (s > string && isspace (*s)) {
517 mnemon_load_category (mnemon_t *mnemon,
521 char *line = NULL, *end;
522 size_t line_size = 0;
526 category_t *category;
529 path = xmalloc (strlen (mnemon->dir_name) + 1 + strlen (name) + 1);
530 sprintf (path, "%s/%s", mnemon->dir_name, name);
532 file = fopen (path, "r");
534 fprintf (stderr, "Error: Failed to open %s: %s\n",
535 path, strerror (errno));
539 category = mnemon_get_category (mnemon, name);
541 #define READ_LINE do { \
542 bytes_read = getline (&line, &line_size, file); \
543 if (bytes_read == -1) \
551 char *name, *equal, *value;
553 /* Ignore blank lines */
558 /* An initial digit means we hit an item. Trigger the
559 * spaghetti machine. */
560 if (*line >= '0' && *line <= '9')
563 equal = strchr (line, '=');
565 fprintf (stderr, "Malformed option, (expected name=value): \"%s\" at %s:%d\n",
566 line, path, line_count);
574 name = trim_space (name);
575 value = trim_space (value);
577 if (strcmp (name, "order") == 0) {
578 if (strcmp (value, "sequential") == 0) {
579 category->order = CATEGORY_ORDER_SEQUENTIAL;
580 } else if (strcmp (value, "random") == 0) {
581 category->order = CATEGORY_ORDER_RANDOM;
583 fprintf (stderr, "Unknown value for \"order\" option \"%s\" at %s:%d\n",
584 value, path, line_count);
588 fprintf (stderr, "Unknown option %s at %s:%d\n",
589 name, path, line_count);
597 char *challenge, *response;
599 /* Ignore blank lines */
604 /* Read bin number */
606 score = strtol (line, &end, 10);
608 fprintf (stderr, "Failed to parse bin number from \"%s\" at %s:%d\n",
609 line, path, line_count);
615 challenge = strdup (line);
621 category_add_item (category, score, challenge, response);
631 /* Resize category items to fit exactly. */
632 category->items_size = category->num_items;
633 category->items = xrealloc (category->items, category->items_size * sizeof (item_t));
635 /* Now that the category is completely loaded, with stable
636 * pointers to every item, we can add each item to its appropriate
638 for (i = 0; i < category->num_items; i++) {
639 item_t *item = &category->items[i];
640 bin_t *bin = mnemon_get_bin (mnemon, item->score);
642 bin_add_item (bin, item);
647 mnemon_load (mnemon_t *mnemon)
650 struct dirent *dirent;
652 dir = opendir (mnemon->dir_name);
654 fprintf (stderr, "Error: Failed to open directory %s: %s\n",
655 mnemon->dir_name, strerror (errno));
660 dirent = readdir (dir);
664 if (dirent->d_type == DT_REG) {
665 /* Ignore files matching *~, (yes, this shouldn't be
666 * hard-coded in such an ad-hoc way, but there you go. */
667 if (dirent->d_name[strlen(dirent->d_name)-1] != '~')
668 mnemon_load_category (mnemon, dirent->d_name);
676 mnemon_save (mnemon_t *mnemon)
679 char *filename, *lock_filename;
681 category_t *category;
683 for (i = 0; i < mnemon->num_categories; i++) {
684 category = &mnemon->categories[i];
686 xasprintf (&filename, "%s/%s",
687 mnemon->dir_name, category->name);
688 xasprintf (&lock_filename, "%s/.#%s",
689 mnemon->dir_name, category->name);
691 file = fopen (lock_filename, "w");
693 fprintf (stderr, "Error: Failed to open %s for writing: %s\n",
694 lock_filename, strerror (errno));
698 category_print (category, file);
702 err = rename (lock_filename, filename);
704 fprintf (stderr, "Error: Failed to rename %s to %s: %s\n",
705 lock_filename, filename, strerror (errno));
710 free (lock_filename);
714 /* Return a uniformly-distributed pseudo-random integer within the
717 * 0 <= result < num_values
720 rand_within (int num_values)
722 return (int) (num_values * (rand() / (RAND_MAX + 1.0)));
725 /* Return an exponentially-distributed pseudo-random integer within
728 * 0 <= result < num_values
730 * The distribution is such that each successively larger value will
731 * occur with a probability of half of the previous value.
734 rand_within_exponential (int num_values)
737 static uint32_t mask = 0;
741 /* Optimize the constant case. */
751 while (mask > RAND_MAX)
758 if (ones == num_values)
766 /* Find the category to which an item belongs. */
768 mnemon_item_category (mnemon_t *mnemon,
771 category_t *category;
774 for (i = 0; i < mnemon->num_categories; i++) {
775 category = &mnemon->categories[i];
776 item_index = item - category->items;
777 if (item_index >= 0 && item_index < category->num_items)
784 typedef struct _item_in_category_closure
787 category_t *category;
788 } item_in_category_closure_t;
791 mnemon_item_in_category (void *closure, item_t *item)
793 item_in_category_closure_t *iicc = closure;
794 mnemon_t *mnemon = iicc->mnemon;
795 category_t *category = iicc->category;
797 return (mnemon_item_category (mnemon, item) == category);
801 mnemon_select_item (mnemon_t *mnemon,
805 int bin_index, item_index;
808 bin_index = rand_within_exponential (mnemon->num_bins);
810 bin = &mnemon->bins[bin_index];
812 item_index = rand_within (bin->num_items);
814 if (bin->score == 0) {
815 category_t *category;
818 item = bin->items[item_index];
820 category = mnemon_item_category (mnemon, item);
822 if (category->order == CATEGORY_ORDER_SEQUENTIAL) {
823 item = category_next_bin_zero_item (category);
825 item_index = bin_item_index (bin, item);
830 *item_index_ret = item_index;
834 #define HISTOGRAM_ROW_FORMAT "%3d: %3d"
835 #define HISTOGRAM_BAR_WIDTH 63
838 print_histogram_bar (double size,
841 int units_per_cell = (int) ceil (max / HISTOGRAM_BAR_WIDTH);
842 static char const *boxes[8] = {
847 while (size > units_per_cell) {
849 size -= units_per_cell;
852 size /= units_per_cell;
856 else if (size > 6.5/8.0)
858 else if (size > 5.5/8.0)
860 else if (size > 4.5/8.0)
862 else if (size > 3.5/8.0)
864 else if (size > 2.5/8.0)
866 else if (size > 1.5/8.0)
868 else if (size > 0.5/8.0)
875 mnemon_print_histogram (mnemon_t *mnemon,
876 const char *category_name)
878 int i, last_score, max;
879 category_t *category = NULL;
882 item_match_predicate_t *predicate = NULL;
883 void *closure = NULL;
884 item_in_category_closure_t item_in_category;
886 if (mnemon->num_bins == 0)
890 category = mnemon_get_category_if_exists (mnemon, category_name);
892 predicate = mnemon_item_in_category;
893 item_in_category.mnemon = mnemon;
894 item_in_category.category = category;
895 closure = &item_in_category;
899 for (i = 0; i < mnemon->num_bins; i++) {
900 num_items = bin_num_items_matching (&mnemon->bins[i],
902 if (i == 0 || num_items > max)
906 for (i = 0; i < mnemon->num_bins; i++) {
907 bin = &mnemon->bins[i];
909 while (bin->score - last_score > 1)
910 printf (HISTOGRAM_ROW_FORMAT "\n", ++last_score, 0);
911 num_items = bin_num_items_matching (bin,
913 printf (HISTOGRAM_ROW_FORMAT " ", bin->score, num_items);
914 print_histogram_bar (num_items, max);
915 last_score = bin->score;
920 mnemon_handle_command (mnemon_t *mnemon,
924 switch (command[0]) {
927 while (*arg && isspace (*arg))
931 mnemon_print_histogram (mnemon, arg);
934 printf ("Unknown command: %s\n", command);
940 mnemon_handle_response (mnemon_t *mnemon,
944 const char *response)
948 correct = (strcmp (response, item->response) == 0);
950 bin_remove_item (bin, item_index);
952 /* If the bin is now empty, we must remove it. Also if we just
953 * picked the last word we'll ever pick from the bin with
954 * score 0, then we can remove that as well. */
955 if (bin->num_items == 0 ||
956 (bin->score == 0 && mnemon->to_introduce == 0))
958 mnemon_remove_bin (mnemon, bin);
963 /* We reserve an item score of 0 for an item that has
964 * never been asked. */
965 if (item->score == 0) {
968 printf ("You got it!");
969 } else if (item->score < 0) {
970 printf ("Yes---just give me %d more.",
972 } else if (item->score == 1) {
973 printf ("On your first try, no less!");
975 printf ("Masterful (%dx).", item->score);
976 if (mnemon->to_master)
980 printf (" %s is the correct answer.",
982 /* Penalize an incorrect response by forcing the score
984 if (item->score >= 0) {
986 printf ( " Oops, you knew that, right?\n ");
988 /* We go to -2 to force a little extra reinforcement
989 * when re-learning an item, (otherwise, it will often
990 * get asked again immediately where it is easy to get
991 * a correct response without any learning). */
998 if (mnemon->to_introduce == 0 &&
999 mnemon->unlearned == 0 &&
1000 mnemon->to_master == 0)
1002 mnemon->to_master = 10;
1003 mnemon->mastered = 0;
1007 if (mnemon->to_introduce)
1008 printf ("%d to come. ", mnemon->to_introduce);
1009 if (mnemon->unlearned)
1010 printf ("%d still unlearned. ", mnemon->unlearned);
1011 if (mnemon->to_master) {
1012 if (mnemon->mastered < mnemon->to_master)
1013 printf ("%d items to master",
1014 mnemon->to_master - mnemon->mastered);
1016 printf ("Great job!");
1020 bin = mnemon_get_bin (mnemon, item->score);
1022 bin_add_item (bin, item);
1026 mnemon_do_challenges (mnemon_t *mnemon)
1034 /* Count the number of items with negative scores. */
1035 mnemon->unlearned = 0;
1036 for (i = 0; i < mnemon->num_bins; i++) {
1037 bin = &mnemon->bins[i];
1038 if (bin->score >= 0)
1040 mnemon->unlearned += bin->num_items;
1043 mnemon->to_introduce -= mnemon->unlearned;
1044 if (mnemon->to_introduce < 0)
1045 mnemon->to_introduce = 0;
1047 /* Get rid of bin with score of 0 if we aren't going to be
1048 * introducing anything from it. */
1049 if (mnemon->to_introduce == 0) {
1050 bin = mnemon_get_bin (mnemon, 0);
1051 mnemon_remove_bin (mnemon, bin);
1054 if (mnemon->unlearned) {
1055 printf ("You've got %d items to learn already. ", mnemon->unlearned);
1056 if (mnemon->to_introduce)
1057 printf ("I'll introduce %d more as we go.", mnemon->to_introduce);
1060 printf ("Introducing %d new items.\n", mnemon->to_introduce);
1065 mnemon_select_item (mnemon, &bin, &item_index);
1066 item = bin->items[item_index];
1068 if (bin->score == 0)
1069 mnemon->to_introduce--;
1072 printf ("%s\n", item->challenge);
1074 response = readline ("> ");
1075 /* Terminate on EOF */
1076 if (response == NULL) {
1081 if (response[0] == '/')
1082 mnemon_handle_command (mnemon, response + 1);
1087 mnemon_handle_response (mnemon, bin, item_index,
1089 } while (mnemon->mastered < mnemon->to_master);
1093 main (int argc, char *argv[])
1097 srand (time (NULL));
1099 mnemon_init (&mnemon);
1101 mnemon_load (&mnemon);
1103 mnemon_do_challenges (&mnemon);
1105 mnemon_save (&mnemon);
1107 mnemon_fini (&mnemon);