From c61c79bb88741481c7b29af2983794c8fc1b9c09 Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Sat, 3 Oct 2009 19:00:51 +0000 Subject: simplify algorithm, add getopt() --- weasel.c | 65 ++++++++++++++++++++++++++++++---------------------------------- 1 file changed, 30 insertions(+), 35 deletions(-) diff --git a/weasel.c b/weasel.c index 2a3a196..2470608 100644 --- a/weasel.c +++ b/weasel.c @@ -25,13 +25,15 @@ #include #if 0 -const char aim[] = "METHINKS IT IS LIKE A WEASEL"; +const char defaim[] = "METHINKS IT IS LIKE A WEASEL"; const char alphabet[] = " ABCDEEFGHIJKLMNOPQRSTUVWXYZ"; #else -const char aim[] = "THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG'S BACK 1234567890 TIMES."; +const char defaim[] = "THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG'S BACK 1234567890 TIMES."; const char alphabet[] = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}~"; #endif +const char *aim; + TAILQ_HEAD(creatures, creature) generation; struct creature { char *genom; @@ -122,8 +124,8 @@ cmp(const void *u, const void *v) void intercourse(int population, int mutationsrate) { - struct creature *c[3], *child; - int i, length; + struct creature *c[3]; + int i; for (i = 0; i < 3; i++) { c[i] = pickrandom(population); @@ -131,38 +133,14 @@ intercourse(int population, int mutationsrate) } qsort(c, 3, sizeof(struct creature *), cmp); - length = c[0]->length; - child = malloc(sizeof(struct creature)); - assert(child); - child->genom = malloc(length); - assert(child->genom); - - for (i = 0; i < length; i++) { + for (i = 0; i < c[2]->length; i++) { if (arc4random() % mutationsrate == 0) - child->genom[i] = rndchar(); + c[2]->genom[i] = rndchar(); else - child->genom[i] = c[arc4random() % 2]->genom[i]; + c[2]->genom[i] = c[arc4random() % 2]->genom[i]; } - child->genom[i] = '\0'; - child->length = length; - child->fitness = calculatefitness(child->genom, child->length); - -#if 0 - printw("\n"); - printcreature(c[0]); - printcreature(c[1]); - printcreature(c[2]); - printw("\n"); - printcreature(child); - printw("\n"); - refresh(); -#endif - - /* insert child & kill weakest */ - TAILQ_INSERT_TAIL(&generation, child, link); - TAILQ_REMOVE(&generation, c[2], link); - free(c[2]->genom); - free(c[2]); + c[2]->genom[i] = '\0'; + c[2]->fitness = calculatefitness(c[2]->genom, c[2]->length); } int @@ -186,12 +164,29 @@ success() } int -main() +main(int argc, char **argv) { extern int LINES; int population = 1000; int mutationrate = 100; /* 1/n */ - int i; + int i, c; + + while ((c = getopt(argc, argv, "m:p:")) != -1) + switch (c) { + case 'm': + mutationrate = atoi(optarg); + break; + case 'p': + population = atoi(optarg); + break; + default: + break; + } + + argc -= optind; + argv += optind; + + aim = argc ? strdup(*argv) : defaim; initscr(); setterm("vt220"); -- cgit v1.2.3