196 Agent-Based Modeling and Simulation with Swarm
colorMap=new ColormapImpl(this);
colorMap.setColor$ToName((byte)0,"black");
colorMap.setColor$ToName((byte)1,"red");
colorMap.setColor$ToName((byte)2,"green");
colorMap.setColor$ToName((byte)3,"red");
colorMap.setColor$ToName((byte)4,"red");
colorMap.setColor$ToName((byte)5,"red");
colorMap.setColor$ToName((byte)6,"red");
colorMap.setColor$ToName((byte)7,"red");
In other words, state 0 is black, state 2 is green, and all others are being
turned red.
7.3 Program that replicates itself
Making a prog ram that outputs its source code looks easy but is a very
difficult problem. In particular, care is necessary in treating newline characters
and spaces. The following is an example of a self-replicating code in C.
#include <stdio.h>
char *s="#include <stdio.h>%cchar *s=%c%s%c;main(){printf(s,10,34,s,34,10);return 0;}%c";main(){printf(s,10,34,s,34,10);return 0;}
Character strings are used effectively. There should be no carelessly in-
serted newline characters in this code: when a newline character is inserted,
the code must be changed to output this additional newline character. Note
that 10 and 34 in ASCII code are the newline and " characters, respectively.
Therefore, executing printf(s,10,34,s,34,10); in the main function prints
the first and second lines of the code.
To confirm that the ab ove is a self-replicating code, copy the above file
as a source file such as ev.c and ex e c ute the following. You can confirm that
the output file and the source c ode are the same (it is recommen ded that you
use the diff command that displays the differe nce between two files). The
following is an example of how the self-replicating code is executed.
iba@fs(~/tmp)[514]: cat ev.c
#include <stdio.h>
char *s="#include <stdio.h>%cchar *s=%c%s%c;main(){printf(s,10,34,s,34,10);return 0;}%c";main(){printf(s,10,34,s,34,10);return 0;}
iba@fs(~/tmp)[515]: gcc ev.c
iba@fs(~/tmp)[516]: ./a.out > ev2.c
iba@fs(~/tmp)[517]: diff ev.c ev2.c
It is also possible to compile code that outputs its source code in languages
other than C. For example, the following line in Lisp which is us e d in artificial
intelligence,
(setf f ’(lambda (x) ‘(,x ’,x)))