Quines

From CS315

Jump to: navigation, search

Written by Joshua Housh

A quine (pronounced like the English word "queen") is a program which takes no arguments, reads in nothing, and whose's only output is its source code. "Quine" is the common name for the programs written for Self. Programs which contain no source are considered trivial and thus not counted (a number of languages simply print nothing when executing such a file). Quines are named after the American philosopher Willard Van Orman Quine. A quine can be written in any language which can output any computable string.[1]

Quines have proved to be a very interesting and amusing subject for certain people. People who enjoy writing quines often try to challenge themselves in certain ways. Two of the most popular challenges includes designing short quines, and writing quines which work in multiple different languages (such quines are called polygots).

History

The first known quine was written in the 1960's in Atlas Autocode:

%BEGIN
!THIS IS A SELF-REPRODUCING PROGRAM
%ROUTINESPEC R
R
PRINT SYMBOL(39)
R
PRINT SYMBOL(39)
NEWLINE
%CAPTION %END~
%CAPTION %ENDOFPROGRAM~
%ROUTINE R
%PRINTTEXT '
%BEGIN
!THIS IS A SELF-REPRODUCING PROGRAM
%ROUTINESPEC R
R
PRINT SYMBOL(39)
R
PRINT SYMBOL(39)
NEWLINE
%CAPTION %END~
%CAPTION %ENDOFPROGRAM~
%ROUTINE R
%PRINTTEXT '
%END
%ENDOFPROGRAM

Examples in Java

This example uses printf to format the string that it is printing:

class X{public static void main(String[]a){String x="class X{public static void main(String[]a){String x=%c%s%1$c;System.out.printf(x,34,x);}}";System.out.printf(x,34,x);}}

The following example uses an enum. Note that compiling an enum can generate a class file which the JVM can execute:

enum Q{T;System a;String x="enum Q{T;System a;String x=%c%s%1$c;{a.out.printf(x,34,x);a.exit(0);}}";{a.out.printf(x,34,x);a.exit(0);}}

Examples of Quines in Other Languages

This quine was written in C and also happens to be a palindrome:[2]

/**/char q='"',*a="*//**/char q='%c',*a=%c%s%c*/};)b(stup;]d[b=]d-852[b)--d(elihw;)q,a,q,q,2+a,b(ftnirps{)(niam;031=d tni;]952[b,",b[259];int d=130;main(){sprintf(b,a+2,q,q,a,q);while(d--)b[258-d]=b[d];puts(b);}/*c%s%c%=a*,'c%'=q rahc/**//*"=a*,'"'=q rahc/**/

Here is an example of a polyglot quine.[3] It works in the following languages: C, Ruby, Python, and Perl:

 #include/*
s='''*/<stdio.h>
main(){char*_;/*==;sub _:lvalue{$_}<<s;#';<<s#'''
def printf(a,*b):print a%b,
s
#*/
_=" #include/*%cs='''*/<stdio.h>%cmain(){char*_;/*==;sub _:lvalue{%c_}<<s;#';<<s#'''%cdef printf(a,*b):print a%%b,%cs%c#*/%c_=%c%s%c;printf(_,10,10,36,10,10,10,10,34,_,34,10,10,10,10);%c#/*%cs='''*/%c}//'''#==%c";printf(_,10,10,36,10,10,10,10,34,_,34,10,10,10,10);
#/*
s='''*/
}//'''#==
Personal tools