Sunday, July 15, 2007

A program that prints itself

Update 17th July 2007: Rummaging through my notes I found this - This is a corollary of the Recursion Theorem. This is the way a virus can get a description of itself and print it to a file and do other "wonderfull" stuff to itself like - mutate. Check out this interesting article that talks in detail about the Recursion Theorem - Link

I had been told that any Turing Machine can be made to print itself. Programs are Turing Machines, so they should be able to print themselves. I never actually tried to write such a program myself.

Getting into an argument with some colleagues, I got cornered into defending my statement with a (at the moment) running program or retract my statement. So, with trembling hands, a vague memory of description of such a machine during one of the lectures I attended once and copious amounts of faith in the professor, I gave it a shot. And by golly I got it right ...

Let me lay the ground first.

The program
#include<stdio.h>
main() { printf("Hello, world");}

Prints:
Hello, world
Should print:
#include<stdio.h>
main() { printf("Hello, world");}


To make a program print itself one can attempt:

The program
#include<stdio.h>
main() { printf("#include<stdio.h>\nmain() { printf(\"#include<stdio.h>\n main() { ...\") } ");}

Prints:
#include<stdio.h>
main() { printf("#include<stdio.h>
main() { ...") }

Should Print:
#include<stdio.h>
main() { printf("#include<stdio.h>\nmain() { printf(\"#include<stdio.h>\n main() { ...\") } ");}


So, one gets into a mirror reflecting a mirror kind of a situation.

A program to print its own description:
#include<stdio.h>
main(){ char *str="printf(\"#include<stdio.h>%cmain\(){char *str=%c%str%c; \",10,str,34,34); printf(\"%s\",str); printf(\"}\");"; printf("#include<stdio.h>%cmain\(){char *str=%c%str%c; ",10,34,str,34); printf("%s",str); printf("}"); }

Prints:
#include<stdio.h>
main(){char *str="printf("#include<stdio.h>%cmain(){char *str=%c%str%c; ",10,str,34,34); printf("%s",str); printf("}");tr"; printf("#include<stdio.h>%cmain(){char *str=%c%str%c; ",10,str,34,34); printf("%s",str); printf("}");}


The general idea is like this:

[PartXBegin] = main() { char *str=[PartY];
[PartY] = <Print [PartXBegin]> <Print str> <Print [PartXEnd]>
[PartXEnd] = }

Hence, any program can print a description of itself (obviously,only if it can at least perform the basic turing operations).