Quine-spirations: To infinity and beyond

Quine-spirations: To infinity and beyond

Stephen Hawking begins his book, A Brief History of Time, with this story:

A well-known scientist (some say it was Bertrand Russell) once gave a public lecture on astronomy. He described how the earth orbits around the sun and how the sun, in turn, orbits around the center of a vast collection of stars called our galaxy. At the end of the lecture, a little old lady at the back of the room got up and said: "What you have told us is rubbish. The world is really a flat plate supported on the back of a giant tortoise." The scientist gave a superior smile before replying, "What is the tortoise standing on?" "You're very clever, young man, very clever," said the old lady. "But it's turtles all the way down!"

We are pretty sure that the Universe isn't turtles all the way down, but we certainly can create Quines - Self replicating computer programs, going all the way down to infinity.

Zip Quine

Below is a zip file, that when extracted, unpacks into the same zip file, which when extracted, unpacks to the same zip file, and on and on ad infinitum. There's also an Image taking a free ride along the infinite recursion, injecting itself as an Intron.

Download the ZIP quine, and try extracting it for yourself!

How is this possible, you might ask? Well, there are several lossless compression standards, and one basic algorithm you might've come across is Run-Length encoding (RLE), wherein a prefix integer tells how many times to repeat the next alphabet. Ex: The compressed data 2a6b1c9d, gets decompressed into aabbbbbbcddddddddd

Similarly, one of the sophisticated standards is L-Zip. Given an input data sequence, It spits out a compressed data sequence, and a series of commands to decompress. Running the commands as an action on the compressed data will decompress into the original sequence. There are only 2 possible commands:

  • print M: prints the next M lines of input as is.

  • repeat M N: seeks back N lines from the end of the output and prints the next M lines of output as is.

One can carefully design an input sequence, that is also made of the same two commands, such that it decompresses to itself.

Try solving the interactive Zip Quine puzzle. It's fun!

Below are some Inspirational-Quines; or more generally, programs with a self-referential nature in them.

Fluid simulation Quine

This is an HTML, CSS, and JavaScript Quine, that not only prints itself but also simulates fluid flow animation on its own source code!

GitHub

Website Source

HTML / CSS / JavaScript: Watch it online!

<body id="b" style="font-size:6vw;width:29ch"><tt><b>1kb Fluid
Simulation Quine</b><p>Click to restart / <a href="https://github.com/xem/
miniFluid/">github</a></p><canvas width="512" height="192" id="c"
style="width:99%;background:#9cf"><script>M=o=>//<3
a.map(p         =>{   p.t=.1   ;p.s   =0;   o||(       p.D=p.w)
;a.map(  q=>(g=Math   .hypot   (e=p   .x-   q.x,  f=    p.y-q.y
)/2-1)<       0?o?(   g/=p.D   ,p.t   +=(   f*(z  =3-   p.D-q.D
)+p.v-q   .v)*g,p.s   +=(e*z   +p.u   -q.   u)*g  ):    p.D+=g*
g:1)});   ;;;;;;;;;       ;G=        b.outerHTML  .    slice/*#
#*/(0,-22);Q=o=>{_=a=[];for(C of G)_++,C!=" "&&a.push({x:_%/*.#
#*/64+4,y:5+_/64|0,C,w:"#"==C,u:0,v:0})};setInterval(`R-->0/*;#
#*/&&Q();M(c.width^=M());for(p of a)with(p)c.getContext(/*Vida#
#*/"2d").fillText(C,7*x,8*y),w||(y+=v+=t/4,x+=u+=s/8)`,R=19)/*#
#*/;onclick=o=>R=1;/*                                        ##
##                                                 ########### 
 ###################################################*/</script>

What's more, is that the code can be formatted to fit 64 characters wide, and 16 lines tall, making it 64 * 16 = 1024 bytes. The entire source code of this fluid simulation Quine is exactly 1 KB!

The big empty spaces in the middle of the code spell out a certain word. Did you notice?

Palindromic Quine

This is a JavaScript Quine that is also a palindrome! Try it in the console.

JavaScript:

(q=u=>(i=`(q=${q},q())`,i+' // '+[...i].reverse().join``),q()) // ))(q,)``nioj.)(esrever.]i...[+' // '+i,`))(q,}q{$=q(`=i(>=u=q(

Palindromic PolyQuine

This is a C# and Java Polyglot-Quine, that is also a palindrome!

GitHub

C#: Try it online!

Java: Try it online!

/**///\u000A\u002F\u002A
using System;//\u002A\u002F
class Program{public static void//\u000A\u002F\u002A
Main//\u002A\u002Fmain
(String[]z){String s="`**?`@#_^using System;?_#^class Program{public static void?@#_^Main?_#main^(String[]z){String s=!$!,t=s;int i;int[]a=new int[]{33,94,38,64,35,95,96,63,36};String[]b=new String[]{!&!!,!&n!,!&&!,!&@!,!&#!,!&_!,!`!,!?!,s};for(i=0;i<9;i++)t=t.?@#_^Replace?_#replace^(!!+(char)a[i],b[i]);t+='*';for(i=872;i>=0;i--)t=t+t?@#_^[i];Console.Write?_#.charAt(i);System.out.printf^(t);}}/",t=s;int i;int[]a=new int[]{33,94,38,64,35,95,96,63,36};String[]b=new String[]{"\"","\n","\\","\\u000A","\\u002F","\\u002A","/","//",s};for(i=0;i<9;i++)t=t.//\u000A\u002F\u002A
Replace//\u002A\u002Freplace
(""+(char)a[i],b[i]);t+='*';for(i=872;i>=0;i--)t=t+t//\u000A\u002F\u002A
[i];Console.Write//\u002A\u002F.charAt(i);System.out.printf
(t);}}/*/}};)t(
ftnirp.tuo.metsyS;)i(tArahc.F200u\A200u\//etirW.elosnoC;]i[
A200u\F200u\A000u\//t+t=t)--i;0=>i;278=i(rof;'*'=+t;)]i[b,]i[a)rahc(+""(
ecalperF200u\A200u\//ecalpeR
A200u\F200u\A000u\//.t=t)++i;9<i;0=i(rof;}s,"//","/","A200u\\","F200u\\","A000u\\","\\","n\",""\"{][gnirtS wen=b][gnirtS;}63,36,69,59,53,46,83,49,33{][tni wen=a][tni;i tni;s=t,"/}};)t(^ftnirp.tuo.metsyS;)i(tArahc.#_?etirW.elosnoC;]i[^_#@?t+t=t)--i;0=>i;278=i(rof;'*'=+t;)]i[b,]i[a)rahc(+!!(^ecalper#_?ecalpeR^_#@?.t=t)++i;9<i;0=i(rof;}s,!?!,!`!,!_&!,!#&!,!@&!,!&&!,!n&!,!!&!{][gnirtS wen=b][gnirtS;}63,36,69,59,53,46,83,49,33{][tni wen=a][tni;i tni;s=t,!$!=s gnirtS{)z][gnirtS(^niam#_?niaM^_#@?diov citats cilbup{margorP ssalc^#_?;metsyS gnisu^_#@`?**`"=s gnirtS{)z][gnirtS(
niamF200u\A200u\//niaM
A200u\F200u\A000u\//diov citats cilbup{margorP ssalc
F200u\A200u\//;metsyS gnisu
A200u\F200u\A000u\///**/

Upside-down Quine

Here's a JavaScript Quine, that not only prints itself backwards character by character but also flips each character upside-down!

JavaScript: (Try it in console)

(o=(Z="()[]<>⌄^Ɩ1nueǝrɹvʌmɯaɐjɾiᴉfɟpd\"⹂˙.")=>[..."(o="+o+")()"].reverse().map(s=>Z[Z.indexOf(s)^1]||s).join(""))()

prints

()((⹂⹂)uᴉoɾ˙(s||[Ɩ⌄(s)ɟOxǝpuᴉ˙Z]Z<=s)dɐɯ˙()ǝsɹǝʌǝɹ˙[⹂()(⹂+o+⹂=o)⹂˙˙˙]<=(⹂˙."⹂\\pdfɟiᴉjɾaɐmɯvʌrɹeǝnuƖ1⌄^<>[]()⹂=Z)=o)

Snake game Quine

A quine that plays snake over its own source code.

GitHub

Too much food for one snake? Share it with others from the Multiplayer variant of the Snake-Quine game below. Each red dot is food, and the other 3 colors are players!

GitHub

C to HTML Quine

This is a C program, that prints the source code of an HTML/JS website, that displays the original C program:

C to HTML Quine

Rubick cube Quine:

This is a JavaScript Quine with a fully functional Rubik Cube at the center!

It does have colors! ANSI escape codes are used to display the colour when output into the terminal.

eval((c=`[b,d,p]=($=String.fromCh              arCode)(96,92,32);M=process.argv[S
='slice'](2).join(W='').split                       (/(\\ww?\\d?'?)/).filter(d=>d
.trim());P=[6,3,0,7,4,1,8,                             5,2];E=/./.constructor;C=$
(85,70,82,66,76,68);s=c.                                 replace(E('[^'+C+']','g'
),W);I=C+'xyz';u=_=>{s                                     =P.map(d=>s[d]).join(W
)+s[S](12,21)+s[S](9,                                       12)+s[S](21)};y=_=>{s
=[P.map(d=>s[d]),[0,                                         12,24].flatMap(_=>[[
q=12+_,21+_],[9+_,q                   UUU                     ]]).map(d=>s[S](...
d)),[...P].reverse                    UUU                      ().map(d=>s[d+45])
].flat().join(W)};                    UUU                      x=_=>{s=[...'ÀÁÂÌÍ
ÎØÙÚ¿Ë×áâãÛÏü»º¾Ê                 LLLFFFRRRBBB                ÖäåæÜП·½ÉÕçèéÝÑ
Ŷµ´àßÞÔÓÒÈÇÆ'].ma                 LLLFFFRRRBBB                p(d=>s[d.charCodeA
t()-180]).join(W)}                 LLLFFFRRRBBB                ;z=[x,y,x,x,x];X=[
x,x,x];m=[[u],[x,u                    DDD                      ,X],[y,y,y,X,u,x,y
],[X,u,x],[z,u,z,z                    DDD                      ,z],[x,x,u,x,x],[x
],[y],z];M.map(d=>                    DDD                      {A=_=>m[I.indexOf(
d[0])].flat().map(d                                           =>d());A();d[1]=="'
"?(A(),A()):d[1]&&A(                                         )});i=0;console.log(
'eval((c='+b+c.replac                                       e(/\\x1b\\[\\d+m/g,''
).replace(E('['+C+']',                                     'g'),_=>'\\x1b['+[47,4
2,41,44,45,43][I.indexOf                                 (s[i])]+'m'+s[i++]+'\\x1
b[0m').replaceAll(d,d+d)+b                             +').replace('+p.repeat(16)
+'/'+d+'x1b'+d+'['+d+'d+m|'+d                       +'s+|['+C+']*/g,""))');/3x3x3
*simulator*by*kirjava/`).replace(                /\x1b\[\d+m|\s+|[UFRBLD]*/g,""))

When executed normally, it functions as a regular Quine, and prints itself. When executed with a moves as arguments, it produces a new Quine with the moves applied! node qube.js "RUR'URU2R'"

Since this is a Quine, you can continuously pipe the program into itself and apply moves on the way. node qube.js "R U" | node - "R' U'" | node - "R' F'"

Hash Quine

This is a PNG Image, which contains it's own MD5 Hash value in the image. Hash Value: 1337e2ef42b9bee8de06a4d223a51337

Try MD5 Hashing Online and check if it spits out the same value.

Globe Quine

A Ruby Quine with an ASCII image of a globe in its source code that rotates by 45 degrees after each run, eventually coming around after eight runs.

GitHub

v=0000;eval$s=%q~d=%!^Lcf<LK8,                  _@7gj*LJ=c5nM)Tp1g0%Xv.,S[<>YoP
4ZojjV)O>qIH1/n[|2yE[>:ieC       "%.#%  :::##"       97N-A&Kj_K_><wS5rtWk@*a+Y5
yH?b[F^e7C/56j|pmRe+:)B     "##%      ::##########"     O98(Zh)'Iof*nm.,$C5Nyt=
PPu01Avw^<IiQ=5$'D-y?    "##:         ###############"    g6`YT+qLw9k^ch|K'),tc
6ygIL8xI#LNz3v}T=4W    "#            #.   .####:#######"    lL27FZ0ij)7TQCI)P7u
}RT5-iJbbG5P-DHB<.   "              ##### # :############"   R,YvZ_rnv6ky-G+4U'
$*are@b4U351Q-ug5   "              #######################"   00x8RR%`Om7VDp4M5
PFixrPvl&<p[]1IJ   "              ############:####  %#####"   EGgDt8Lm#;bc4zS^
y]0`_PstfUxOC(q   "              .#############:##%   .##  ."   /,}.YOIFj(k&q_V
zcaAi?]^lCVYp!;  " %%            .################.     #.   "  ;s="v=%04o;ev"%
(;v=(v-($*+[45,  ":####:          :##############%       :   "  ])[n=0].to_i;)%
360)+"al$s=%q#{  "%######.              #########            "  ;;"%c"%126+$s<<
126}";d.gsub!(/  "##########.           #######%             "  |\s|".*"/,"");;
require"zlib"||  "###########           :######.             "  ;d=d.unpack"C*"
d.map{|c|n=(n||  ":#########:           .######: .           "  )*90+(c-2)%91};
e=["%x"%n].pack   " :#######%           :###### #:          "   &&"H*";e=Zlib::
Inflate.inflate(   "  ######%           .####% ::          "   &&e).unpack("b*"
)[0];22.times{|y|   "  ####%             %###             "   ;w=(Math.sqrt(1-(
(y*2.0-21)/22)**(;   " .###:             .#%             "   ;2))*23).floor;(w*
2-1).times{|x|u=(e+    " %##                           "    )[y*z=360,z]*2;u=u[
90*x/w+v+90,90/w];s[(    " #.                        "    ;y*80)+120-w+x]=(""<<
32<<".:%#")[4*u.count((     " .                   "     ;"0"))/u.size]}};;puts\
s+";_ The Qlobe#{" "*18+ (       "#  :#######"       ;"Copyright(C).Yusuke End\
oh, 2010")}";exit~;_ The Qlobe                  Copyright(C).Yusuke Endoh, 2010

Quine Tweet

Quine Tweet - A tweet that tweets its own link. This was done way before, the edit feature was introduced.

Here's a write-up about how it was done: Write up

Quine blog series

Last but not least, is the existence of this very own blog series! Each blog in this 7-part series has a self-referential easter egg relating to the topic in question. How many did you find?


Although we've explored self-reference in Computing here, you can find self-reference embedded in Art, Literature, Math, Biology and much more. In fact, there is a case to be made that, self reference might be a crucial ingredient for intelligence and consciousness.

That is to say, a Quine, in its essence, embodies a fundamental truth: the capacity for self-reflection and self-replication is not just a quirk of computer science, but a cornerstone of existence itself. From the spiralling double helix of DNA to the introspective musings of the human mind, the universe seems to whisper a persistent message: "Know thyself!"

It beckons us to turn our gaze inward, to explore the depths of our own being, to understand the code that shapes our thoughts, actions, and destinies.

"Until you make the unconscious conscious, it will direct your life and you will call it fate."

- Carl Jung


Sources and references: