# Golf you a quine for great good!

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;

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}
body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)
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> 

• Do you not mean, "Golf you a quine for greater good!"? May 3, 2011 at 2:49
• @muntoo it's a play on "Learn you a Haskell for Great Good". May 3, 2011 at 2:52
• Did anybody notice that this is question 69? Oct 24, 2020 at 22:47

# Labyrinth, 52 bytes

411096280599923751453245172184368156!
_
2/:@
" .
71_


Try it online!

Just beats out the previous Labyrinth quine by one byte, through using the modulo behaviour of ., and an unorthodox divisor.

### Explanation:

This uses a similar setup to the other answer, but where that used a divmod of 98, this divides by 172 and modulos by 256. This first saves on the decoder section because the . instruction already moduloes by 256 before printing. But this alone isn't enough, so I started looking for a smaller divisor.

This is possible by brute-forcing the required number through rearranging the source code until it works, and only when the encoded string is really small (in this case 16 bytes). I wrote a Raku script to help brute force these variations of the code, with minor tweaks needed for different layouts.

The code itself is a simple loop

.....!  Push number and print it
.....   Then reverse direction, pushing the number in reverse

_       Enter the loop by
2/     Integer dividing the initial number by 2



:     Duplicate and print value modulo 256
 .


2/     Integer divide by 172
"
71_

@    If the division results in 0, terminate




The above code ended up being one of my first attempts at this method, and I only ever found a couple of others that were the same size, this one and this one, both with divisor 172. I'm not sure why this is the magic number.

Some thoughts on further golfing through this method:

• You can push 0 through ? or { (replacing _)
• You can push 1 through # or ,  (replacing _1)
• The wall in the center can be anything that isn't an instruction
• " can be replaced with ' or some other no-op and can be placed pretty much anywhere in the loop

I'm honestly not sure if this format can be golfed. It seems unlikely that there's a format that supports a smaller divisor than 172, but then again, I'm not sure why 172 was an island of stability in the first place.

# C (gcc), 70 bytes

#define a(b)*s=#b;b
a(main(){printf("#define a(b)*s=#b;b\na(%s)",s);})


Try it online!

# Assembly (NASM, 32-bit, Linux), 620 bytes

section .text
mov di,1
mov ebx,1
m:mov esi,a
l:mov ecx,esi
mov edx,1
mov al,[esi]
cmp al,10
jne p
mov ecx,b
mov dx,2
p:mov eax,4
int 128
mov al,[esi]
inc esi
cmp al,96
jne l
dec di
jz m
mov ecx,c
mov dx,3
mov ax,4
int 128
mov ax,1
int 128
section .data
c db 44,57,54
b db 92,110
a dbsection .text\nmov di,1\nmov ebx,1\nm:mov esi,a\nl:mov ecx,esi\nmov edx,1\nmov al,[esi]\nadd ax,di\ncmp al,10\njne p\nmov ecx,b\nmov dx,2\np:mov eax,4\nint 128\nmov dl,[esi]\ninc esi\ncmp dl,34\njne l\ndec di\njz m\nmov ecx,c\nmov dx,3\nmov ax,4\nint 128\nmov ax,1\nint 128\nsection .data\nc db 44,57,54\nb db 92,110\na db,96


-149 bytes by using backqoutes

-26 bytes by simplifying jumps

Try it online!

# Swift 5, 202 bytes

While much longer than the shortest Swift submission, this has important aesthetic points for me since it avoids numerical ASCII references as well as any declarations at all, using an anonymous function, resulting in a single-statement solution.

import Foundation;({print($0+"("+String(data:try!JSONEncoder().encode($0),encoding:.utf8)!+")")})("import Foundation;({print($0+\"(\"+String(data:try!JSONEncoder().encode($0),encoding:.utf8)!+\")\")})")

• Welcome to the site! Nov 13, 2020 at 4:38

# Setanta, 254 bytes

s:="s:=?q:='\"'n:=cuid@s(0,9)o:=cuid@s(9,fad@s)scriobh(athchuir@n(\"?\",q+athchuir@(athchuir@s(\"\\\\\",\"\\\\\\\\\"))('\"','\\\\\"')+q)+o)"q:='"'n:=cuid@s(0,9)o:=cuid@s(9,fad@s)scriobh(athchuir@n("?",q+athchuir@(athchuir@s("\\","\\\\"))('"','\\"')+q)+o)


Try it here!

This was pretty long, mainly because Setanta doesn't have any string formatting builtins. Probably could still be improved.

Edit 2021/2/4: It seems that you now need to spell the function to print a value as scríobh (previously, you could use scriobh without the accent on the i). Making that fix adds 2 bytes to the solution.

# Perl 5, 24 bytes

print<<""x2
print<<""x2



24 bytes without any options.

Try it online!

# Perl 5, 38 bytes

$_=q{$_=q{0};s/0/$_/;say};s/0/$_/;say



Try it online!

@96c$+.+O@96c$+.+O



Try it online!

Basically just a port of the Adapt quine, but updated with Adjust's swap command ($ vs Adapt's s) and no longer implicit output # Python 3, 48 bytes s='print(f"s={s!r};{s}")';print(f"s={s!r};{s}")  Try it online! ### Python 3, 74 bytes s=r"s=;print(f'{s[:2]}r\"{s}\"{s[2:]}')";print(f'{s[:2]}r\"{s}\"{s[2:]}')  Try it online! First two attempts... I think this is the basic approach, just used Python's f-strings. # 05AB1E, 13 bytes "34çì«"34çì«  Try it online! "..."34çì« # trimmed program "..." # push literal... ì # prepended with... ç # character with codepoint... 34 # literal... « # concatenated with... # (implicit) itself # implicit output  # PxemPxem (esolang-box notation), 162113 109 bytes. Eventually as in meta discussion I had to change the language. The following program equals to filename with same name and empty content in original notation. Be!?BzBc!!B+BzXXFBaBcFBzBsXXFBBaBsBtBvBmBvBcAcB-BaBsBp".e!?.z.c!!.+.zXXF.a.cF.z.sXXF..a.s.t.v.m.v.cAc.-.a.s.p  Try it online! ## With comments XX.z # represents programs from first .m # every dot has to be replaced with B, for example, # because dots are syntaxically special # append " to it .aXX(long)".z # essentially double entire stack .a.eXX.z # loop begin .a!?.zXX.z # move every character to bottom # HOWEVER B is replaced with DOT # when exiting from loop, the stack will be: # "(original data)"(modified data) # # push dummy F if B is not top .a.c!!.+.zXXF.aXX.z # replace B with dot, and push F if F is not top .a.cF.z.sXXF..aXX.z # remove dummy .a.sXX.z # move to bottom .a.t.v.m.vXX.z # get out if " .a.cAc.-.aXX.z # finally; discard top .a.s.p  ## Previous version • 113 bytes: Bm!?BzBcBoBc!!B+BzXXFBaBcFBzBsXXFBBaBsBtBvBmBvBcAcB-BaBp".m!?.z.c.o.c!!.+.zXXF.a.cF.z.sXXF..a.s.t.v.m.v.cAc.-.a.p • 162 bytes: XXx\è\ô\Ú\î\Ú\Þ\Ú\Þ\Ú@\V\Þ\Z\Â\Æ\Æ\Þ\è\ì\Ú\ì\Z\è¢\Â\ì\æ\ì°\î\Æ\Æ\ô\È\Â\H\Þ°\ÂQ.t.z.m.w.m.o.m.o.m .+.o00.-.a.c.c.o.t.v.m.v00.-.tQ.a.v.s.vX.w.c.c.z.d.a.$.oX.a
• This isn't a quine. It's a program that outputs its own file name. A quine would require the filename to not be important; which I'm not sure is possible in Pxem. This is like submitting a 35 byte Python solution with code exec(__file__)\n with filename print'exec(__file__)': TIO. Even though this is not in direct violation of any rules here, it clearly breaks their spirit. But what you're doing here is against the rules. May 29, 2021 at 21:35
• @Makonede but Pxem matters filename first and content is matter if and only if .f and .e are in filename; would I just undo frilom 109-byte version to 113-byte version to remove .e? Or should have I just clarify that a Pxem program consists of filename and optionally its content? In this case I would claim that its filename is the only source code; then I would satisfy the definition of quine: produces a copy of its own source code.
– user100411
May 29, 2021 at 23:32
• A Pxem program may run based on filename, but that does not automatically make it need to output its code instead of its content. A quine is still a quine, no matter how a language is implemented. Remember that you can't just make it output its content, by the way. A quine has to have part of its code that encodes the entire program. And even though I originally thought this isn't breaking rules, I'm 99.9% sure this is a rule somewhere, I just can't describe it in search-friendly keywords. I'll ask TNB about this answer for their opinion, I'm highly doubtful that this is a valid answer. May 30, 2021 at 3:18
• @Makonede; the programs output their filenames; not content.
– user100411
May 30, 2021 at 3:26
• Or should the 109-bytes version be represented in plain-text notation, such as in esolang-box or nk.'s text2pxem.pl?
– user100411
May 30, 2021 at 22:18

# Nim, 87 bytes

import strutils;let s="import strutils;let s=$1$2$1;echo s%[$$'$1',s]";echo s%[$'"',s]  Try it online! # Agda, 160 bytes open import IO;open import Data.String;main = run(putStr(r ++ show r))where r ="open import IO;open import Data.String;main = run(putStr(r ++ show r))where r ="  Try it online! Agda is an interesting Haskell-like language with some interesting ideas and a lot of imports. Luckily I've managed to avoid most of those (though my early attempts weren't so successful). The version on TIO is a bit out of date, which led to some frustration with the docs, but I think this code should still work with the latest version. ### Explanation: open import IO -- Import the IO library for run and putStr open import Data.String -- Import Data.String for ++ and show main = run(putStr -- with main, print the string (r ++ show r)) -- r appended with the string representation of r where r = -- where r is "..." -- the string of the rest of the program  # ErrLess, 34 24 bytes Thanks to Jo King for saving 10 bytes S'R1+,$:@:?.S'R1+,$:@:?.  No trailing newline. ## Explanation S'R1+,$:@:?.S { Put the rest of the program in a string: ("'R1+,$:@:?.") } 'R1+, { Add a one-element string containing S: ("'R1+,$:@:?." "S") }
$: { Swap & concatenate: ("S'R1+,$:@:?.") }
@:            { Duplicate & concatenate: ("S'R1+,$:@:?.S'R1+,$:@:?.") }
?.            { Print & halt }


ErrLess is a stack-based language I made for fun over the last few months. You can read the docs here, and I also started a tutorial.

Try it online!

# Pari/GP, 28 bytes

(()->print1("("self")()"))()


Try it online!

# Joy, 32 bytes

[put "x." putchars 10 putch] x.



Try it online!

Joy is a stack-based language. It has an interesting operation, x, which means executing a block without popping it. So [P] x is equivalent to [P] P. This is useful for writing quines.

• The second time I've seen Joy, after the appearance in your article about Esolangs.
– null
Apr 15 at 5:23
• Let's see some DipDup answers too!
– null
Apr 15 at 5:26
• As a sidenote, are you still in the CGoL community?
– null
Apr 15 at 5:27
• @null I'm not active in the forum, just occasionally search the word "rlifesrc" to see if anyone has found a bug. Apr 15 at 5:44

# !@#$%^&*()_+, 112811161069960877844540477407383 33 bytes Edit: Woah... -304 B with space Edit 2: Bruh. Edit 3: Thanks Jo King for the idea! I outgolfed ya! A stack-based language(The first on TIO's list!) It's a big pile of unprintables though N0N (!&+$*)^(!&@^)!


(Spaces are NUL bytes)

Try it online!

Here's the code, but in Control Pictures form:

␙N0␖␑␘N␙␚␔␛␀␖␑␘␀␐(!&␐+$*)^(!&@^)!  ## Explanation ␙N0␖␑␘N␙␚␔␛␀␖␑␘␀␐ Data (!&␐+$*)         Push the stack, reversed and +16 back on top
^(!&@^)! Print everything reversed, including the length (Hence the final !)


It does error on overflow though...

• Will it get to BF length? I wonder... Apr 18 at 11:44
• Almost there... Apr 18 at 12:02
• just as a note, i have posted a quine in this language before, though don't let that stop you improving this further
– Jo King
Apr 18 at 13:27
• SO messed up the unprintables Apr 18 at 18:34

## 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);}

• You could shave 9 chars off the shorter version by leaving out the trailing newline. Feb 3, 2012 at 18:55

# F♯# - 349 Characters

let s="\\\"\nnlet s=let z a b=s.Substring(a,b)System.Console.WriteLine()z 4 6+z 1 1+z 0 1+z 0 1+z 0 1+z 1 1+z 0 1+z 3 1+z 3 1+z 4 169+z 1 1+z 2 1+z 10 26+z 2 1+z 36 25+z 62 111+z 61 1"
let z a b=s.Substring(a,b)
System.Console.WriteLine(z 4 6+z 1 1+z 0 1+z 0 1+z 0 1+z 1 1+z 0 1+z 3 1+z 3 1+z 4 169+z 1 1+z 2 1+z 10 26+z 2 1+z 36 25+z 62 111+z 61 1)


My first attempt at a quine - probably an easier (or shorter) way to do it, but not a bad first attempt I don't think

set c {set c {$c};puts [subst -noc \$c]};puts [subst -noc $c]  ## Erlang escript 225164 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. # 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])} }  • this is awesome. – cat Dec 7, 2015 at 14:50 # Cobra - 143 class P def main s='class P{2} def main{2} s={1}{0}{1}{2} Console.write(s,s,39to char,10to char)' Console.write(s,s,39to char,10to char)  ## Lua, 76 characters s="s=%c%s%c;print(string.format(s,34,s,34))";print(string.format(s,34,s,34))  Another one with the usual format string technique. ## 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. ## Minkolang 0.9, 10 bytes This language was made after this challenge, but was not made for it. "66*2-(O).  Like other 2D languages, the " makes everything between it and the next " a string. 66*2- adds the not-included " and (O). prints everything out and stops. ## Scala, 84 bytes val d=""" print("val d=\"\"\""+d+"\"\"\""+d) """ print("val d=\"\"\""+d+"\"\"\""+d)  Kinda straightforward, but putting it out there for completion. ## Seriously, 2 bytes 1  Pushes the number 1, implicit print with trailing newline. Since this is fairly trivial, here is the smallest non-trivial quine which can contain arbitrary characters (12 bytes): è";ƒ"@+;ƒ  ## 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)))  ## 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));}}
`
• 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. Oct 6, 2018 at 23:08