245
\$\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\$
3
  • 6
    \$\begingroup\$ Do you not mean, "Golf you a quine for greater good!"? \$\endgroup\$ May 3, 2011 at 2:49
  • 64
    \$\begingroup\$ @muntoo it's a play on "Learn you a Haskell for Great Good". \$\endgroup\$ May 3, 2011 at 2:52
  • 26
    \$\begingroup\$ Did anybody notice that this is question 69? \$\endgroup\$
    – aidan0626
    Oct 24, 2020 at 22:47

455 Answers 455

1
8 9
10
11 12
16
2
\$\begingroup\$

C, 125 84 chars

main(){char*p="main(){char*p=%c%s%c,c='%c',s[256];sprintf(s,p,c,p,c,c);puts(s);}",c='"',s[256];sprintf(s,p,c,p,c,c);puts(s);}

It turns out that my idea was implemented much better:

main(){char*p="main(){char*p=%c%s%c;printf(p,34,p,34,10);}%c";printf(p,34,p,34,10);}
\$\endgroup\$
1
  • 3
    \$\begingroup\$ You could shave 9 chars off the shorter version by leaving out the trailing newline. \$\endgroup\$ Feb 3, 2012 at 18:55
2
\$\begingroup\$

Haskell, 93 68 characters

s="\nmain=putStrLn$\"s=\"++show s++s"
main=putStrLn$"s="++show s++s
\$\endgroup\$
2
\$\begingroup\$

Bash, 67/51 chars

f () 
{ 
    printf "%s\n${!1} $1" "$(local -f ${!1})"
}
f FUNCNAME

And 51 chars:

trap -- 'printf "%s\n:" "$(trap -p DEBUG)"' DEBUG
:
\$\endgroup\$
2
\$\begingroup\$

Erlang escript 225 164 140

$ escript quine

main(_)->[A|B]=["main(_)->[A|B]=[","],io:put_chars([10,A,34,A,34,44,34,B,34,B,10,10])."],io:put_chars([10,A,34,A,34,44,34,B,34,B,10,10]).

$

Apparently escript has to have at least three lines.

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

Zozotez Lisp: 73

((\ (x) (c x (c (c (" ") (c x))))) (" (\ (x) (c x (c (c (" ") (c x)))))))

This requires one of the REPLs. For one bootstrap expression quine I need it to print: 81

((\ (x) (p (c x (c (c (" ") (c x)))))) (" (\ (x) (p (c x (c (c (" ") (c x))))))))

Extended BrainFuck: 68

This uses mostly Brainfuck code except for the store string procedure.

>~"~!<<.[<]>.>+.-<[.>]<[<]>>+.->[.>]"<<.[<]>.>+.-<[.>]<[<]>>+.->[.>]

A 94 byte version that uses more EBF features:

{c|"{q$q.$p(-)}:q:p$q 34+$p|'{c|'&q&c&q|'}'(-)&c"}{q$q.$p(-)}:q:p$q 34+$p|'{c|'&q&c&q|'}'(-)&c
\$\endgroup\$
2
\$\begingroup\$

Go - 583

Just because d;

package main
import "fmt"
func main(){
    a := string(byte(34))
    b := []string{
        "package main",
        "import fmt",
        "func main(){",
        "   a := string(byte(34))",
        "   b := []string{",
        "       ",
        "   }",
        "   for i:=0;i<5;i++{if i != 1{fmt.Println(b[i])}else{fmt.Println(b[i][:7]+a+b[i][7:]+a)}}",
        "   for _,v:=range b{fmt.Println(b[6]+a+v+a+string(','))}",
        "   for i:=7;i<9;i++{fmt.Println(b[i])}",
        "}",
        }
    for i:=0;i<5;i++{if i != 1{fmt.Println(b[i])}else{fmt.Println(b[i][:7]+a+b[i][7:]+a)}}
    for _,v:=range b{fmt.Println(b[5]+a+v+a+string(','))}
    for i:=7;i<11;i++{fmt.Println(b[i])}
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ this is awesome. \$\endgroup\$
    – cat
    Dec 7, 2015 at 14:50
2
\$\begingroup\$

Mathematica 17 19

ToString[#0][] & []
\$\endgroup\$
1
  • \$\begingroup\$ Why Community Wiki? \$\endgroup\$
    – MD XF
    Jun 12, 2017 at 23:47
2
\$\begingroup\$

Node.js REPL (22)

console.log(RegExp.$1)
\$\endgroup\$
2
  • \$\begingroup\$ ...this abuses the fact that (I guess) the Node REPL internally executes a regex on the received line? I want to upvote because of the cleverness, but on the other hand I don't want to since it relies on extracting its own source code as a string... \$\endgroup\$
    – FireFly
    Aug 22, 2014 at 15:38
  • \$\begingroup\$ You need to specify the Node version this works in, because running in 7.5.0, this prints a single newline. \$\endgroup\$ Jul 16, 2017 at 5:21
2
\$\begingroup\$

Julia, 101 characters

s="s=%c%s%c;@printf %c%s%c 34 s 34 34 s 34";@printf "s=%c%s%c;@printf %c%s%c 34 s 34" 34 s 34 34 s 34

It's the usual format string technique, but unfortunately you can't get the format specification string from a variable in Julia, so I have to include it twice in the code, which blows everything up.

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

Pretty certain you can't get shorter than this with Common Lisp. The first one I managed to figure out myself; all credit to http://rosettacode.org/wiki/Quine#Common_Lisp for the second one.

Common Lisp - 9 (With REPL)

(write -)

In Common Lisp, - is a special variable that holds the expression currently being evaluated but only during a read-eval-print loop. If you're running from a script or you've disabled the REPL though...

Common Lisp - 25 (No REPL)

#1=(write '#1# :circle t)

This references itself and then prints itself out. :circle t makes it detect the infinite recursion cycle and exit early.

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

AppleScript, 2 Bytes

1

It's a little cheaty, but it is following the restrictions of a quine. If we don't count the trailing newline, then this solution becomes 1 byte - 1.

Whenever AppleScript has a final executed line of code, it prints the result of the last operation (whatever it is) to the command line.

text

Any class name has the same effect.

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

Python 3 - 58 Characters

Since there is a Python 2 version, I suppose this is acceptable:

x='x={};print(x.format(repr(x)))';print(x.format(repr(x)))
\$\endgroup\$
2
\$\begingroup\$

Java, 190 Characters

class I{public static void main(String[]a){String s="class I{public static void main(String[]a){String s=%c%s%1$c;System.out.print(s.format(s,34,s));}}";System.out.print(s.format(s,34,s));}}
\$\endgroup\$
1
  • \$\begingroup\$ Since ye olde Java SE 8, you can put static methods (such as main) in interfaces - no public. Also print and format methods can be collapsed into printf. \$\endgroup\$ Oct 6, 2018 at 23:08
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\$

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\$
0
2
\$\begingroup\$

Straw, 10 bytes (non-competing)

(:%>>):%>>
\$\endgroup\$
1
  • \$\begingroup\$ Link to language is dead. Also, why is this non-competing? \$\endgroup\$ Sep 18, 2020 at 1:35
2
\$\begingroup\$

Common Lisp - 73 35

Thanks to reader variables written #n= and #n#, with n an integer, Lisp code can be self-referential. Also, the printing functions can emit such reader variables when told to handle circular structures. The WRITE function accepts a :circle parameter for that purpose. It also returns the value being printed, which means that we have to globally set *PRINT-CIRCLE* to T (the initial, standard value is NIL), otherwise the REPL would report a stack-overflow exception when printing that value. Initializing the variable takes a lot of bytes and so the shorter solution is to return another value:

#1=(PROGN (WRITE '#1# :CIRCLE T) T)
\$\endgroup\$
2
\$\begingroup\$

Dart, 185 bytes

main(){var c=new String.fromCharCode(34);var l=["main(){var c=new String.fromCharCode(34);var l=[","];print(l[0]+c+l[0]+c+','+c+l[1]+c+l[1]);}"];print(l[0]+c+l[0]+c+','+c+l[1]+c+l[1]);}
\$\endgroup\$
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\$

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
  • 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\$ Jul 30, 2017 at 2:33
2
\$\begingroup\$

D, 85 bytes

enum c=q{import std.stdio;void main(){write("enum c=q{"~c~"};mixin(c);");}};mixin(c);
\$\endgroup\$
0
2
\$\begingroup\$

AWK, 72 bytes

BEGIN{s="BEGIN{s=%c%s%c;printf s,34,s,34}";printf s,34,s,34}

In 6 years nobody had written an AWK solution :(


This can be run from command-line as:

awk 'BEGIN{s="BEGIN{s=%c%s%c;printf s,34,s,34}";printf s,34,s,34}'

or placed in a file, FILE and run as:

awk -f FILE

Note: no newline is printed so if storing in a file... the file shouldn't have an EOF in it... maybe? We can add an EOF by adding print statements but that adds 12 bytes. This happens to be my first ever quine. :) It took me a bit to figure out how to get the quotation marks, since I first wanted to use \" but I'd have to escape the \ and then escape that one... ASCII to the rescue :)

\$\endgroup\$
2
  • 1
    \$\begingroup\$ After I posted this I was curious if there was an extant AWK quine example. Apparently so at nyx.net/~gthompso/self_awk.txt. Given that, I believe this might be the shortest possible AWK quine. \$\endgroup\$ Feb 23, 2017 at 21:07
  • 2
    \$\begingroup\$ No this isn't the shortest AWK quine ;) \$\endgroup\$
    – DialFrost
    Nov 12, 2022 at 2:25
2
\$\begingroup\$

k, 48 bytes

This is, of course, ignoring the trivial quines, such as () or 1.

{}`0:(`c$34)/{(x;x;())}"{}`0:(`c$34)/{(x;x;())}"

Try it out.

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

Scala, 540 Bytes

object Q {
  def main(a:Array[String]):Unit={
    val d=Seq(
      "object Q {",
      "def main(a:Array[String]):Unit={",
      "val d=Seq(",
      "val c=println(_:String)",
      "val b=(x:Int)=>x.toChar.toString",
      "d take 3 map c",
      "val a=d.zipWithIndex.map(x=>b(34)+x._1+b(34)+(if(x._2==d.size-1)b(9).drop(1)else b(44)))",
      "a.map(c)",
      "c(b(41))",
      "d.drop(3).map(c)",
      "c(b(125))",
      "c(b(125))"
    )
    val c=println(_:String)
    val b=(x:Int)=>x.toChar.toString
    d take 3 map c
    val a=d.zipWithIndex.map(x=>b(34)+x._1+b(34)+(if(x._2==d.size-1)b(9).drop(1)else b(44)))
    a.map(c)
    c(b(41))
    d.drop(3).map(c)
    c(b(125))
    c(b(125))
  }
}

Can probably be improved. I decided to call it quits for now as it is 5 in the morning. I think something that can be changed to make this smaller is to encode the d value in some other way other than a sequence of strings. I haven't thought of a cool way to do it yet, though. This would also add to the obfuscation part of the challenge.

\$\endgroup\$
1
  • \$\begingroup\$ This doesn't work as is due to indenting. \$\endgroup\$
    – emanresu A
    Jan 3, 2023 at 10:42
2
\$\begingroup\$

Bash, 65 bytes

set -o history
echo "set -o history"
history|tail -n 2|cut -c 8-

Bash disables the command-history function in scripts, but you can turn it on manually with 'set-o history'.

This first command is obviously not stored in the shell's history file, so the second command prints the same text to the terminal.

The third command pulls the last two out of the history file and cleans them up for displaying.

The output matches:

set -o history
echo "set -o history"
history|tail -n 2|cut -c 8-
\$\endgroup\$
1
  • \$\begingroup\$ reads its source no matter what \$\endgroup\$ Jun 15, 2016 at 8:39
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\$
1
  • \$\begingroup\$ You can save 2 bytes by replacing LLL with JL (in both occurrences). \$\endgroup\$ May 18, 2017 at 17:56
2
\$\begingroup\$

ACL2, 41 bytes

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

Vim, 27 bytes

ii^V^V^V^[BDuplxbbpp^[BDuplxbbpp

^V being CTRL+V and ^[ being ESC.

The other one is beating mine, but it took a while and I didn't think it was possible.

\$\endgroup\$
1
8 9
10
11 12
16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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