#include #include #include #include "gene.h" static Window window; static Pixmap backmap; static unsigned int width, height; static struct CityPosition { double x, y; } position[NCities]; extern Display *dpy; extern int scr; extern GC gc; extern unsigned int Drawfg, Drawbg; extern double drand48(); double fitness(g) gene *g; { int i; struct CityPosition *p, *q; double dist = 0.; for (i = 0; i < NCities; i ++) { p = position + g->city[i]; q = position + g->city[(i + 1) % NCities]; dist += hypot(p->x - q->x, p->y - q->y); } return NCities / dist; } redisplay(e) XExposeEvent *e; { XCopyArea(dpy,backmap,window,gc,e->x,e->y, e->width,e->height,e->x,e->y); } gene *random_gene() { int i, j; char c; static gene new; for (i = 0; i < NCities; i ++) new.city[i] = i; for (i = 1; i < NCities; i ++) { j = lrand48() % (NCities - i) + i; if (j != i) { c = new.city[i]; new.city[i] = new.city[j]; new.city[j] = c; } } return &new; } domain_init(win) Window win; { Window root; int x, y; unsigned int border, depth; char *dp; XImage *xip; window = win; XGetGeometry(dpy,window,&root,&x,&y,&width,&height,&border,&depth); if (depth < 8) { fprintf(stderr,"Sorry, this program works only on depth >= 8.\n"); exit(1); } backmap = XCreatePixmap(dpy,window,width,height,depth); } random_arrange() { int i; for (i = 0; i < NCities; i ++) { position[i].x = drand48(); position[i].y = drand48(); } } double_circle(r1,r2) double r1,r2; { int i, n = NCities / 2; double th; for (i = 0; i < n; i ++) { th = M_PI * 2 * i / n; position[i].x = r1 * cos(th) + 0.5; position[i].y = r1 * sin(th) + 0.5; position[i+n].x = r2 * cos(th) + 0.5; position[i+n].y = r2 * sin(th) + 0.5; } } static void draw_individual(id,x,y) int id, x, y; { int i; gene *g = (gene *)get_ith_gene(id); XPoint xp[NCities+1]; for (i = 0; i < NCities; i ++) { xp[i].x = position[g->city[i]].x * width / 3 + x; xp[i].y = position[g->city[i]].y * height / 3 + y; XFillRectangle(dpy,backmap,gc,xp[i].x-1,xp[i].y,3,3); } xp[NCities] = xp[0]; XDrawLines(dpy,backmap,gc,xp,NCities+1,CoordModeOrigin); } domain_draw() { int i, j; XSetForeground(dpy,gc,Drawbg); XFillRectangle(dpy,backmap,gc,0,0,width,height); XSetForeground(dpy,gc,Drawfg); for (i = 0; i < 3; i ++) for (j = 0; j < 3; j ++) draw_individual(i*3+j,j*width/3,i*height/3); XCopyArea(dpy,backmap,window,gc,0,0,width,height,0,0); } fitness_string(value,str) double value; char *str; { sprintf(str,"%.3f",value); }