194
\$\begingroup\$

Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

  • Smallest code (in bytes)
  • Most obfuscated/obscure solution
  • Using esoteric/obscure languages
  • Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}
function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}
function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=!1;comment_page=1;getComments()}})}
function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}
getAnswers();var SCORE_REG=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}
function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))
body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)
valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,})});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)
lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<i>'+a.language+'</i>').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)return-1;return 0});for(var i=0;i<langs.length;++i)
{var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> 

\$\endgroup\$
  • 4
    \$\begingroup\$ Do you not mean, "Golf you a quine for greater good!"? \$\endgroup\$ – Mateen Ulhaq May 3 '11 at 2:49
  • 44
    \$\begingroup\$ @muntoo it's a play on "Learn you a Haskell for Great Good". \$\endgroup\$ – Rafe Kettler May 3 '11 at 2:52

312 Answers 312

2
\$\begingroup\$

SWI-Prolog, 22 bytes

a :-
        listing(a).
 

A surprisingly short and elegant solution.

The 8 spaces and the new line (the space in the last line is just to display the empty line, there is actually no space) are both required in SWI-Prolog because that is the formatting that listing displays in the interpreter.

\$\endgroup\$
2
\$\begingroup\$

DUP, 51 bytes

0"0.[34,0[$;$][,1+]#]$!%%!"0.[34,0[$;$][,1+]#]$!%%!

Try it here.

Well, DUP quines are possible, just really, really, long. I'll have to golf some more.

\$\endgroup\$
2
\$\begingroup\$

Python 2 and 3 - 32 bytes

s='s=%r;print(s%%s)';print(s%s)

From Ray Toal's Quine Page

\$\endgroup\$
2
\$\begingroup\$

reticular, 9 bytes

"'34'coo;

This captures the string '34'coo;, then wraps around. After that, the number 34 is pushed the stack, converted to a character with c, finally being outputted with o. The next o outputs the captured string, and ; terminates the program.

Other quines:

"'34'c~O;
"6@P2*c~O;
\$\endgroup\$
2
\$\begingroup\$

Jelly, 6 bytes

There are two proper and payload capable "built-in" quines of 6-bytes:

“ØV”ṘV - takes no input
“ØV”   - make the string “ØV”
    Ṙ  - print and yield left (prints “ØV”, yields “ØV”)
     V - eval Jelly code (the code ØV yields the string “ṘV”)
       - implicit return of the string “ṘV”, so the final output is “ØV”ṘV

and

“Øv”Ṙv - as above,  except:
         v evals with an input, which in this case is empty; and
         Øv yields “Ṙv”

A payload may be placed directly after the leading open quote in either.

\$\endgroup\$
2
\$\begingroup\$

Straw, 10 bytes (non-competing)

(:%>>):%>>
\$\endgroup\$
2
\$\begingroup\$

Y, 2 bytes

Try it here!

Up

This is two commands. U is a capture link, and begins quoting the code, and has a U at the beginning of the result. It wraps around, since there is no matching U, and captures the string Up. Then, p prints it, and we are done.

\$\endgroup\$
2
\$\begingroup\$

PowerShell, 41 37 Bytes:

function q{"function q{$function:q};q"};q

filter q{"filter q{$function:q};q"};q

Thanks to TimmyD for saving 4 bytes

\$\endgroup\$
  • \$\begingroup\$ What interpreter / compiler does this work in? In this interpreter, this submission doesn't work (it outputs function q{End: { "function q{$function:q};q" }};q). \$\endgroup\$ – Loovjo Oct 6 '16 at 18:00
  • \$\begingroup\$ @Loovjo Most online PowerShell interpreters use an open-source PoSH that's roughly equivalent to PowerShell v0.5 and lacking many features. The above works fine in an actual install on Windows. \$\endgroup\$ – AdmBorkBork Oct 7 '16 at 13:08
  • \$\begingroup\$ At least in v4 on Windows 8.1, you can shave a few bytes using filter as follows -- filter q{"filter q{$function:q};q"};q for 37. \$\endgroup\$ – AdmBorkBork Oct 7 '16 at 13:09
  • \$\begingroup\$ $MyInvocation.MyCommand.ScriptBlock is 2 bytes shorter but almost definitely cheating? \$\endgroup\$ – colsw Feb 22 '17 at 22:38
2
\$\begingroup\$

Cheddar, 56 bytes

Try this one online!

let q='let q=%s%s%s;print IO.sprintf(q,@"39,q,@"39)';print IO.sprintf(q,@"39,q,@"39)

See the explanation below, except mentally replace % with IO.sprintf.




Well darn. @ETHProductions came up with this solution before me..

This is the shortest I could come up with... Maybe some abuse of functional operators could help me.

let q='let q=%s;print q%@"39+q+@"39';print q%@"39+q+@"39

Try it online! You can guess what the output is.

This code can be divided into two parts: the string and the output. The string part:

let q='let q=%s;print q%@"39+q+@"39';

is simply a formatting template.

The output part:

;print q%@"39+q+@"39

formats the string. @"39 is char 39, or '.

\$\endgroup\$
2
\$\begingroup\$

Pushy, 9 bytes

95 34
_"

(non-competing as the language postdates the challenge)

Although writing functional programs in Pushy is sometimes difficult, the quine is relatively simple:

95   % Push 95 to the stack (ASCII code for _ )
34   % Push 34 to the stack (ASCII code for " )
_    % Print representation of the stack: 95 34
"    % Print stack converted to string: _"

Notice that, although Pushy ignores newlines, it is needed here because the default separator for printing is \n - and there needs to be a trailing newline, hence making it 9 bytes


Alternatively, an 11-byte solution that does not require a newline:

78 95 34N_"

Works similarly to the one above, but N sets the separator an empty string.

\$\endgroup\$
2
\$\begingroup\$

Java 8, 94 bytes

()->{String s="()->{String s=%c%s%1$c;System.out.printf(s,34,s);}";System.out.printf(s,34,s);}

This is a lambda expression which prints its own source code to STDOUT. It uses a similar tactic to other Java quines here, but the lambda really helps cut down bytes.

If we wanted to be really cheeky and cut down two bytes, we could declare the lambda as x->, where x is an empty string, as according to meta, "taking no input" means you can assume empty input, and in function submissions input is given as a parameter.

\$\endgroup\$
2
\$\begingroup\$

Python 3, 38 bytes

There are already a lot of Python quines, but as far as I can see this one hasn't been posted yet. Technically it is a statement that evaluates to a string representation of itself, but other submissions do similar things.

'.__repr__()[:-1]*2'.__repr__()[:-1]*2

This works in a similar way to many quines in 2D langauges with "edge-wrap", where "string mode" is entered, the whole program is pushed to the stack, then string mode is executed and the program runs, printing the string mode character (usually ") followed by the contents of the stack (i.e. the program's source) then exiting.

A breakdown of the statement is as follows:

'.__repr__()[:-1]*2'                   # A string containing the body of the program.
                                       # .__repr__()[:-1]*2
                    .__repr__()        # The same string, but enclosed in single quote marks.
                                       # '.__repr__()[:-1]*2'
                               [:-1]   # A splice that crops off the last character.
                                       # '.__repr__()[:-1]*2
                                    *2 # Repeat the string.
                                       # '.__repr__()[:-1]*2'.__repr__()[:-1]*2

The reason I have used .__repr__() instead of repr(string) is because the quine relies on code following and not preceding the string. This is also why this is a statement and not a program; the print() function requires code before the string, which is not possible with this quine layout.

As you may have noticed, there's a much golfier statement that evaluates to this statement:

"'.__repr__()[:-1]*2"*2

But this isn't a quine, because it doesn't evaluate to itself.

\$\endgroup\$
  • 1
    \$\begingroup\$ Unfortunately, I don't think this is valid, since it's an expression (and therefore a snippet) rather than a full program. \$\endgroup\$ – Esolanging Fruit Jul 30 '17 at 2:33
2
\$\begingroup\$

Threead, 101 bytes

>91>60>93>62>91>105>54>50>99>111>100>111>62>93>60>91>60>93>62>91>99>111>62>93[<]>[i62codo>]<[<]>[co>]

Try it online!

My first thought for writing a Threead quine was to store the entire data section as one large number, in order to get a good compression ratio. This doesn't work because a) % appears to be broken, and b) Threead doesn't support bignum arithmetic.

Instead, I wrote this solution, which works along the same lines as a brainfuck quine, storing the characters of the code section of the program as individual tape elements. Then we just have to scan the list once in order to print it as data, and again to print it as code.

Although Threead allows for three threads, and requires their use when performing binary operations, this style of quine uses only unary operations and thus there was no point in using more than one thread, so I just did everything inside the first.

Explanation

>91>60>…>62>93            ASCII character codes of the rest of the program
[<]>                      Return the pointer to the start of the data
[                         While the current data cell is nonzero:
 i62                        Place 62 (ASCII code of >) on a temporary tape cell
 co                         Output it as a character (i.e. >)
 d                          Delete the temporary tape cell
 o                          Output the current data element as an integer
>]                        then continue the loop with the next data cell
<[<]>                     Return the pointer to the start of the data
[                         While the current data cell is nonzero:
 co                         Output it as a character
>]                        then continue the loop with the next data cell
\$\endgroup\$
  • \$\begingroup\$ Nice. Basically the same as mine but with > at the beginning. I like it \$\endgroup\$ – Riley Jan 16 '17 at 23:01
  • \$\begingroup\$ I hope you don't mind that I used that trick in my new version :) \$\endgroup\$ – Riley Jan 16 '17 at 23:23
  • \$\begingroup\$ @Riley: That's OK, we're pretty much all cooperating to improve the quine at this point. \$\endgroup\$ – user62131 Jan 16 '17 at 23:25
2
\$\begingroup\$

Alice, 9 bytes

Credits to Sp3000 for the idea of including the !.

"!<@o&9h.

Try it online!

Explanation

This works much like quines in other Fungeoids with an unmatched " that wraps the entire code (except itself) in a string because the instruction pointer move cyclically through the code.

"!<@o&9h."   Push code points of the entire program except the " to the
             stack (irrelevant).
!            Store 46 (the code point of '.') on the tape (irrelevant).
<            Send IP back west.
!            Store 104 (the code point of 'h') on the tape (irrelevant).
".h9&o@<!"   Push code points of the entire program except the " to the
             stack in reverse.
.            Duplicate the 33 (the code point of '!').
h            Increment to 34 (the code point of '"').
             Now the top nine values on the stack correspond to the entire
             code in reverse order.
9&           Repeat the next command 9 times.
o            Print 9 characters from the top of the stack.
@            Terminate the program.
\$\endgroup\$
2
\$\begingroup\$

Ohm, 22 20 bytes

-2 bytes thanks to Business Cat

"D34'DLaJL"D34'DLaJL

Try it online!

"D34'DLaJL"          # Push this string (everything after this)
           D         # Duplicate
            34'      # Push the character "
               D     # Duplicate
                L    # Print "
                 a   # Swap the top 2 elements 
                  JL # Print the string, ", then the string again.
\$\endgroup\$
  • \$\begingroup\$ You can save 2 bytes by replacing LLL with JL (in both occurrences). \$\endgroup\$ – Business Cat May 18 '17 at 17:56
2
\$\begingroup\$

ACL2, 41 bytes

(let((q"(let((q~x0))(cw q q))"))(cw q q))
\$\endgroup\$
2
\$\begingroup\$

BaCon, 54 bytes

s$="s$=%c%s%c:?34,s$,34 FORMAT s$":?34,s$,34 FORMAT s$
\$\endgroup\$
2
\$\begingroup\$

Go, 112 bytes

As far as I can tell, there's no Go answer here. Here's mine and I think this is the shortest possible.

package main;import.`fmt`;func main(){s:="package main;import.`fmt`;func main(){s:=%q;Printf(s,s)}";Printf(s,s)}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

QBIC, 8 bytes

?A+@?A+@

I was trying to do this, but I accidentally golfed an actual quine. Whadda you know?

Explanation

?           Print
 A            A$
  +         concatenated with
   @       a string literal containing
    ?A+@   "?A+@"

When A$ is used the first time, it might not seem to have a value yet, but it already contains the string literal ?A+@ because the QBIC interpreter first scans the code, sees the @, looks up what the first available string variable is (it's A$, because it hasn't been used by other QBIC language features yet), and it then extracts the definition A$ = "?A+@" to the top of the file, and inserts A$ at the place where it found the literal.

\$\endgroup\$
2
\$\begingroup\$

Micro, 5 bytes

{_BS}

Explination:

{_BS}

{      start a code block (this block will be run due to implicit evaluation)
 _     push the item most recently popped. this pushes the code block which was popped due to implicit evaluation
  BS}  convert the code block to a string, and end the block. Micro's implicit evaluation is weird, because the evaluated variable may generate new items on the stack, in which case the program's execution will continue as if it hadn't ended. this second implicit evaluation displays the string which is left on the stack: "{_BS}", and ends execution.
\$\endgroup\$
2
\$\begingroup\$

Mathcad, 94 characters

f:(c{"f:(c{"")]concat(substr(c,0,6),c,substr(c,6,41))")]concat(substr(c,0,6),c,substr(c,6,41))

Watch out for quotation marks autocompletion in the editor!

This should create a parameterless function f which returns its own code.

This quine makes use of (another) weird feature of Mathcad: you can put as much quotation marks inside a string as you like. No idea how they handle it...

\$\endgroup\$
2
\$\begingroup\$

JScript, 175 bytes

WScript.Echo((k="WScript.Echo((k=\"%Z\").replace(/%[Z]/,k.replace(/[\"\\\\]/g,function(e){return\"\\\\\"+e})))").replace(/%[Z]/,k.replace(/["\\]/g,function(e){return"\\"+e})))

JScript is Microsoft's implementation of the JavaScript language. On a microsoft console, you can invoke the program as <name>.js, and this will output to a popup. To output to the console, one must use:

cscript //E:JScript //nologo <name>.js

and add a trailing CRLF to the source code.

\$\endgroup\$
2
\$\begingroup\$

Foam, 15 bytes

[. <' |: ~|]: ~

This prints itself with a trailing newline. Without a trailing newline:

[. .' |: ~|]: ~
\$\endgroup\$
2
\$\begingroup\$

Gaia, 10 bytes

“:ṙpp”:ṙpp

Try it online!

Explanation

“:ṙpp”      Push this string.
      :     Copy it.
       ṙ    Get the string representation of it.
        p   Print the string representation.
         p  Print the string.
\$\endgroup\$
2
\$\begingroup\$

PHP, 50 chars

<?printf($s='<?printf($s=%c%s%1$c,39,$s);',39,$s);

I realized I could save four chars by enabling short tags (<?=sprintf becomes <?printf)

I saved four more bytes by reusing one of the values in my printf.

\$\endgroup\$
2
\$\begingroup\$

Proton, 32 30 bytes

-2 bytes thanks to ppperry.

s='s=%rprint(s%%s)'print(s%s)

Try it online!

I swear, if I get a bounty for this...

\$\endgroup\$
  • \$\begingroup\$ Hey, I promised a bounty, so if nobody beats it, good for you I guess :P \$\endgroup\$ – HyperNeutrino Aug 17 '17 at 19:39
  • 1
    \$\begingroup\$ You can save two bytes by deleting the semicolons \$\endgroup\$ – pppery Aug 18 '17 at 22:18
2
\$\begingroup\$

C (tcc), 64 bytes

main(t){printf(t,34,t="main(t){printf(t,34,t=%c%s%c,34);}",34);}

Try it online!

could be one problem if compiler not use the stack based way of push arguments.
result of the print (tcc, gcc all in TIO today at last ok (not ok in clang)):

main(t){printf(t,34,t="main(t){printf(t,34,t=%c%s%c,34);}",34);}
\$\endgroup\$
  • \$\begingroup\$ Related \$\endgroup\$ – No one Dec 23 '17 at 19:09
2
\$\begingroup\$

V, 4 bytes

2i2i

Try it online!

Marked as non-competing because this language postdates the challenge by several years.

Explanation:

2       " Two times:
 i      " Insert the following:
  2i    " The string '2i'

This is pretty straightforward. In fact, this almost works in regular vim. There is just one minor thing in the way: The string '2i' isn't inserted twice until you hit <esc>. In V, this is solved by implicitly ending every program with an <esc> (Really, that's an oversimplification, but it's close enough to the truth).

Old versions of V always added a newline to the output, which is why I didn't post this earlier. However, in commit b6c238d, this was fixed.

This answer works just because of luck. The approach doesn't extend well to general purpose quines/quine-variations. The shortest quine I'm aware of that can be trivially modified is

ñéÑ~"qpÿ

Try it online!

Explanation:

ñ           " Start recording into register 'q'
 éÑ         " Insert 'Ñ' (uppercase so that the recording doesn't stop here)
   ~        " Toggle the case the character under the cursor (the 'Ñ')
    "qp     " Paste the contents of register 'q'
       ÿ    " Stop recording and play it all back

The reason the ÿ is needed, is because it is implicitly added to the end of macros, a feature that is unfortunate for quines, but very convenient for golf.

The nice thing about this quine is that we can do almost anything inside of the recording and it is still valid since it will be pasted later anyway.

\$\endgroup\$
2
\$\begingroup\$

MaybeLater, 74 bytes

x="write(('x='+chr(34))+x+(chr(34))+x)"write(('x='+chr(34))+x+(chr(34))+x)

Try it online!

\$\endgroup\$
2
\$\begingroup\$

ABAP, 515 bytes

REPORT R NO STANDARD PAGE HEADING.DATA:A TYPE TABLE OF STRING,B(8).APPEND:
`REPORT.FORM F TABLES T.NEW-PAGE LINE-SIZE 78.WRITE:'REPORT R NO',` TO A,
`'STANDARD PAGE HEADING.DATA:A TYPE TABLE OF STRING,B(8).APPEND:'.LOOP` TO A,
`AT T.REPLACE ALL OCCURENCES OF'``' IN T WITH'````'.WRITE:/'``'` TO A,
`NO-GAP,T NO-GAP,'`` TO A,'.ENDLOOP.WRITE:AT 78'.','GENERATE',` TO A,
`'SUBROUTINE POOL A NAME B.PERFORM F IN PROGRAM (B) TABLES A.'.ENDFORM.` TO A.
GENERATE SUBROUTINE POOL A NAME B.PERFORM F IN PROGRAM (B) TABLES A.

Should work on on any SAP system with SY-SAPRL >= '700'.

source

\$\endgroup\$
  • \$\begingroup\$ is this an error quine? \$\endgroup\$ – Destructible Lemon May 24 '17 at 23:53
  • \$\begingroup\$ @DestructibleLemon No, why do you ask? \$\endgroup\$ – MD XF May 25 '17 at 0:46
  • \$\begingroup\$ Anyone care to explain the serial downvoting? \$\endgroup\$ – MD XF May 25 '17 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.