235
\$\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
  • 21
    \$\begingroup\$ Did anybody notice that this is question 69? \$\endgroup\$
    – aidan0626
    Oct 24, 2020 at 22:47

427 Answers 427

1 2
3
4 5
15
10
\$\begingroup\$

Minecraft Java Edition, 241 bytes

This can be run as a function in a datapack, or by running each of the commands:

data modify storage z x set value ['["data modify storage z x set value ",{"nbt":"x","storage":"z"},"\\ntellraw @a {\\"storage\\":\\"z\\",\\"nbt\\":\\"x[0]\\",\\"interpret\\":true}"]']
tellraw @a {"storage":"z","nbt":"x[0]","interpret":true}

Explanation

data modify storage z x set value ...   # set the variable x in the storage minecraft:z

['...']                                 # to a list containing a string (in JSON rich text format) of

"data modify storage z x set value "    # (a literal part of the source code),

{"nbt":"x","storage":"z"}               # this variable (this will only be evaluated 
                                        # during the tellraw command when it is interpreted), and

"\\ntellraw @a {\\"storage\\":\\"z\\",
  \\"nbt\\":\\"x[0]\\",                 # the rest of the source code
  \\"interpret\\":true}"                # (\ and " must be escaped because this is part of a string).

tellraw @a {"storage":"z","nbt":"x[0]", # then interpret the JSON string and print it to the chat
 "interpret":true}                      # (this will place the variable inside)

The list is necessary so that when it is printed, it will contain the quotes and double backslashes.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Welcome to the site! Nice first answer. \$\endgroup\$
    – Wheat Wizard
    Jul 5, 2020 at 2:01
10
\$\begingroup\$

√ å ı ¥ ® Ï Ø ¿ , 9 (possibly 11) bytes

79 87  OW

Notice the double space between the 87 and the OW. This is necessary because of the way √ å ı ¥ ® Ï Ø ¿ outputs.

The O command outputs the whole of the stack as numbers

The W command outputs the whole stack as Unicode interpretations of the numbers

The 11 byte solution

The above code will output

===== OUTPUT =====

79 87  OW

==================

-----Program Execution Information-----

Code        : 79 87  OW
Inputs      : []
Stack       : (79,87)
G-Variable  : None
Byte Length : 9
Exit Status : 0
Error       : None

---------------------------------------

This is obviously not the code inputted but is outputted automatically by the interpreter. If this is disallowed, there is an 11 byte solution that only outputs the required output:

ł 79 87  OW

This will only output

ł 79 87  OW

I'm not sure if the 9 byte answer is acceptable, could someone please tell me in the comments?

\$\endgroup\$
4
  • 2
    \$\begingroup\$ This is a much less trivial quine than usual - nice! \$\endgroup\$
    – isaacg
    Mar 20, 2017 at 4:46
  • \$\begingroup\$ That looks valid (9 byte). I mean the other stuff is just interpreter items that are always there \$\endgroup\$
    – user63187
    May 21, 2017 at 12:29
  • \$\begingroup\$ this isn't non-competing because this is a catalogue and any language is fine \$\endgroup\$ May 21, 2017 at 23:17
  • \$\begingroup\$ Gesundheit! Wait... that's a language name? You didn't just sneeze bytes? How do you say that language name in a conversation haha! \$\endgroup\$ Sep 6, 2018 at 16:18
10
\$\begingroup\$

TypeScript Types, 149 bytes

//@ts-nocheck
type Q<A='`',B='$',C=Q<'${A}','${B}','${C}'>>=`//@ts-nocheck
type Q<A='${A}',B='${B}',C=Q<'${B}{A}','${B}{B}','${B}{C}'>>=${A}${C}${A}`

Try it online!

TypeScript Types, 209 197 bytes

Without @ts-nocheck to suppress compiler errors

type Q<X extends string[]=['`','$',Q<['${X[0]}','${X[1]}','${X[2]}']>]>=`type Q<X extends string[]=['${X[0]}','${X[1]}',Q<['${X[1]}{X[0]}','${X[1]}{X[1]}','${X[1]}{X[2]}']>]>=${X[0]}${X[2]}${X[0]}`

Try it online!

\$\endgroup\$
9
\$\begingroup\$

C, 78 chars

#define Q(S)char*q=#S;S
Q(main(){printf("#define Q(S)char*q=#S;S\nQ(%s)",q);})

This version is shorter than the familiar 79-character C quine and also doesn't assume ASCII. It does still assume that it's safe to not include stdio.h. (Adding an explicit declaration of printf() brings the length up to 103 chars.)

\$\endgroup\$
9
\$\begingroup\$

Java 6 - 138 110 106

Since the question says "golf you a quine", I took Steve P's quine and golfed it:

enum Q{X;{String s="enum Q{X;{String s=%c%s%1$c;System.out.printf(s,34,s);}}";System.out.printf(s,34,s);}}

With credits to Trixie Wolf and Volune.
Note: you need to ignore stderr (e.g. 2>/dev/null)

For great good (and justice)!

\$\endgroup\$
6
  • \$\begingroup\$ I can't get this to work. Did you actually try to compile it? I think you need a System.exit() gimmick or it will fail to run properly. I'll add an answer here with my implementation later if I don't hear back from you soon. \$\endgroup\$ Aug 16, 2014 at 4:00
  • \$\begingroup\$ Actually: given the "ignore stderr" comment obv. you did get it to work. I'm very curious how, though. \$\endgroup\$ Aug 16, 2014 at 4:19
  • \$\begingroup\$ @TrixieWolf It works fine here, there is absolutely no compile error. Did you think I would post it without trying it first? :p Anyway, you can only run it with java 6 (or 5), newer versions check for the main method first. \$\endgroup\$ Aug 16, 2014 at 7:52
  • \$\begingroup\$ I'd like to suggest this improvement: enum Q{X;{String s="enum Q{X;{String s=%c%s%1$c;System.out.printf(s,34,s);}}";System.out.printf(s,34,s);}} \$\endgroup\$
    – Volune
    Aug 17, 2014 at 11:47
  • \$\begingroup\$ @aditsu Ah, that makes perfect sense. I'm busy today, but tomorrow I will check to see if mine still functions correctly (I tested it recently but I'll bet it was on J6). It might still work due to the exit() trick. \$\endgroup\$ Aug 17, 2014 at 21:35
9
\$\begingroup\$

C, 77 chars

Maybe the easiest one in C.

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

34 is the ASCII decimal for ".

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I count 76 bytes. \$\endgroup\$
    – Lynn
    Jan 18, 2017 at 15:06
  • \$\begingroup\$ @Lynn He must have used wc and forgot to exclude the trailing newline :P \$\endgroup\$
    – MD XF
    May 26, 2017 at 16:32
9
\$\begingroup\$

MUMPS, 9 bytes

R w $T(R)

This may fall afoul of the "you can't just read the source file and print it" restriction. Let me explain why I say may.

The line of code you see above constitutes a complete MUMPS "routine" (named R), which is sort of like a single source file in a conventional C-like language... but not quite.

The way MUMPS stores its routines is peculiar among programming languages. Routines are not files living in a regular filesystem. Instead, they are data structures internal to the database itself. The line of code I've supplied above is actually stored as part of the MUMPS global named ^ROUTINE (globals are basically trees). The "R" subtree (in MUMPS parlance, "subscript") of that global would look something like this:

^ROUTINE("R",0)=1
^ROUTINE("R",1)="R w $T(R)"

The first entry is the number of lines of code in the routine. The subsequent entries are the lines of code in the routine itself.

Why do I bring this up? Well, this means that in MUMPS, the routines themselves are first-class entries in the database! One can edit routines by directly manipulating the contents of the ^ROUTINE global, just as one can edit any other global. (Indeed, at the most basic level, if your MUMPS environment doesn't come with an editor, you must invent one for yourself that will edit the ^ROUTINE global on your behalf.)

The ability to manipulate routines in MUMPS code is so important that the standard even defines a function whose explicit purpose is to tell you what code is found at a given line of a given routine. That function is named $T[EXT], and if you give it a pointer to a line of code, it will return the code present at that location.

And that's what we do here. We w[rite] the result of a call to $TEXT(R) - that is, the contents of the line at the first line of the routine R - to the output stream, and since R is only one line long, that makes the program a quine.

This program involves no file IO at all. The whole thing is internal to the MUMPS environment. I claim that this is interesting enough to count as a legitimate quine, despite the fact that this has a surface-level resemblance to a program that just reads and prints the source file.

\$\endgroup\$
9
+200
\$\begingroup\$

05AB1E, 14 bytes

Shortest proper 05AB1E quine?

0"D34çý"D34çý

With trailing newline.

Try it online!

Explanation:

0              # Push '0'
                   # Stack: ['0']
 "D34çý"       # Push 'D34çý'
                   # Stack: ['0', 'D34çý']
        D      # Duplicate
                   # Stack: ['0', 'D34çý', 'D34çý']
         34ç   # Push '"'
                   # Stack: ['0', 'D34çý', 'D34çý', '"']
            ý  # Join rest of the stack with '"'
                   # Stack: ['0"D34çý"D34çý']
               # Implicit print
\$\endgroup\$
2
  • \$\begingroup\$ Isn't 1 also a proper quine? \$\endgroup\$
    – ovs
    Jan 15, 2017 at 19:24
  • 3
    \$\begingroup\$ @ovs Not by our standard definition. \$\endgroup\$ Jan 25, 2017 at 16:37
9
\$\begingroup\$

Japt, 10 bytes

"iQ ²"iQ ²

Here's how this works:

"iQ ²"      // Take this string.        iQ ²
      iQ    // Insert a quote.          "iQ ²
         ²  // Double.                  "iQ ²"iQ ²
            // Implicitly output.

Test it online!

Of course, any number literal is also a quine because of implicit output.

\$\endgroup\$
2
  • \$\begingroup\$ Does Japt add a newline at the end of implicit output? \$\endgroup\$ Mar 23, 2016 at 4:28
  • \$\begingroup\$ @CalculatorFeline Nope. \$\endgroup\$ Sep 7, 2016 at 2:24
9
\$\begingroup\$

Befunge-93, 15 14 13 bytes

+9*5x:#,_:@#"

Works in this interpreter. x is an unrecognized command which reflects the instruction pointer.

Thanks to Jo King for saving 1 byte.

This 14 byte version works in FBBI:

+9*5<>:#,_:@#"

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ This almost works, but doesn't: "gx:#,_:@#/3: (also 13 bytes). \$\endgroup\$
    – jimmy23013
    May 25, 2019 at 4:37
9
\$\begingroup\$

JavaScript REPL, 21 bytes

(_=$=>`(_=${_})()`)()

It technically doesn't read its own file.

… kind of seems like 0 is also a quine for JavaScript the way this is evaluated, though.

\$\endgroup\$
6
  • 7
    \$\begingroup\$ It reads its own source, though. \$\endgroup\$
    – Joey
    May 12, 2011 at 21:15
  • 1
    \$\begingroup\$ ` Uncaught SyntaxError: Unexpected token =>` in Chrome \$\endgroup\$
    – Nakilon
    Jan 14, 2015 at 9:36
  • 7
    \$\begingroup\$ @Nakilon: Use Firefox. \$\endgroup\$
    – Ry-
    Jan 14, 2015 at 16:17
  • 2
    \$\begingroup\$ +1 for the +_+ in the shorter version \$\endgroup\$
    – user48538
    Jan 4, 2016 at 18:31
  • 3
    \$\begingroup\$ Umm... the first one is actually HTML5. \$\endgroup\$ Jun 15, 2016 at 8:07
9
\$\begingroup\$

05AB1E, 13 bytes

2096239D20BJ
    

Try it online!

Beats all the string-based 05AB1E quines.

Explanation:

2096239            # integer literal
       D           # duplicate
        20B        # convert the copy to base 20, yielding "D20BJ"
           J       # join with the original

Alternative 13 byter:

11959189D₃BJ
    
\$\endgroup\$
1
9
\$\begingroup\$

Ruby, 26 bytes

printf x="printf x=%p,x",x

Not the shortest Ruby quine, but I think it's quite cute so I'm posting it.

Ruby, 27 bytes

p S if$><<S="p S if$><<S="

Ruby, 28 bytes

printf *["printf *[%p]*2"]*2

Ruby 2.7, 34 bytes

".tap{puts p _1}"
.tap{puts p _1}

Ruby, 35 bytes

END{p$0};$><<$0="END{p$0};$><<$0="

\$\endgroup\$
8
\$\begingroup\$

Shell echo-sed quine:

echo sed -eh -es/[\\\(\\\\\\\\\\\)\\\&\\\|]/\\\\\\\\\\\&/g -es/^/echo\\ / -es/$/\\\|/ -eG|
sed -eh -es/[\(\\\\\)\&\|]/\\\\\&/g -es/^/echo\ / -es/$/\|/ -eG

I wanted to write a sed quine, but sed can only work on its input stream, not generate output spontaneously, so this is an echo-sed quine. This 154-character quine uses command-line sed, which automatically makes it hard to read, and uses three different sed commands, as well as two sequences of eleven backslashes in a row. This quine works in bash, ksh, and sh, but not csh or tcsh.

EDIT:

A blatant, and amusing, cheat: echo $BASH_COMMAND

Another, unreasonably silly, cheat: export PROMPT_COMMAND='echo $BASH_COMMAND';$PROMPT_COMMAND

\$\endgroup\$
0
8
\$\begingroup\$

Lua, 44 bytes

s="s=%qprint(s:format(s))"print(s:format(s))

Some other comical answers in Lua:

print(arg[0])

...so long as the file is named print(arg[0]) And...

Lua: quine.lua:1: function arguments expected near '.'

...so long as the file is named quine.lua

\$\endgroup\$
0
8
\$\begingroup\$

T-SQL 24

This statment reproduces itself in the EVENTINFO column of the output:

dbcc inputbuffer(@@spid)

Explanation:

  • dbcc inputbuffer() - Displays the last statement sent from the client with the specified process id to the current instance of Microsoft SQL Server
  • @@spid - Retrieves the current process id

tested with SQL Server 2008 R2 and 2012; probably working with other versions as well

Online demo: http://www.sqlfiddle.com/#!3/d41d8/2230

\$\endgroup\$
8
\$\begingroup\$

QBasic, 76 (110) 54 (72)

Tested with QB64 on Windows 7, with auto-formatting turned off.

READ a$:?a$;:WRITE a$:DATA"READ a$:?a$;:WRITE a$:DATA"

: is a statement separator, and ? is a shortcut for PRINT. The main trick here is using DATA and READ so we don't have to split the string up to add the quotes. Edit: I learned this week about the WRITE command, which outputs strings wrapped in double-quotes--a significant byte-saver here!

Since actual QBasic doesn't let you turn off auto-formatting, here's the same thing with proper formatting in 72 bytes:

READ x$: PRINT x$;: WRITE x$: DATA "READ x$: PRINT x$;: WRITE x$: DATA "

Original versions (76 bytes golfed, 110 formatted):

READ a$:q$=CHR$(34):?a$+q$+a$+q$:DATA"READ a$:q$=CHR$(34):?a$+q$+a$+q$:DATA"

or

READ a$: q$ = CHR$(34): PRINT a$ + q$ + a$ + q$: DATA "READ a$: q$ = CHR$(34): PRINT a$ + q$ + a$ + q$: DATA "
\$\endgroup\$
1
  • 2
    \$\begingroup\$ You can just load the non-formatted file directly though, right? This seems like a limitation of the editor rather than the language itself. \$\endgroup\$
    – 12Me21
    Apr 2, 2018 at 14:54
8
\$\begingroup\$

F#, 90 bytes

let q="let q=%A
printf(Printf.TextWriterFormat<_>q)q"
printf(Printf.TextWriterFormat<_>q)q

F#’s smart printf comes back to byte us! We can’t write let q="...";;printf q q, as the first parameter to printf isn’t actually a string:

printf : TextWriterFormat<'T> -> 'T

F# uses some compiler magic under the hood to guarantee type-safe printf calls. For example, "yay %d wow!" is a valid TextWriterFormat<int -> unit> literal, but not a valid TextWriterFormat<double -> unit> literal. But if we define the format string separately, the compiler will see it as a regular old string and complain. Instead, we have to convert q ourselves in the first argument.

What about let q:TextWriterFormat<_>="..."? First of all, that’s two bytes longer. But second of all, the second argument to printf really needs to be a string, otherwise the typechecker will infer that we’re formatting a formatter, which in turn formats a formatter, which formats a…

error FS0001: Type mismatch. Expecting a
    'a    
but given a
    Printf.TextWriterFormat<('a -> unit)>    
The resulting type would be infinite when unifying ''a' and
    'Printf.TextWriterFormat<('a -> unit)>'

Yep, an infinite type. Oops.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ +1 for emoticon in the code <_> \$\endgroup\$
    – user48538
    Aug 3, 2016 at 18:32
8
\$\begingroup\$

RProgN, 3 bytes

0
0

Try it online!

This exploits a potential flaw in our definition of proper quine:

It must be possible to identify a section of the program which encodes a different part of the program. ("Different" meaning that the two parts appear in different positions.)

Furthermore, a quine must not access its own source, directly or indirectly.

The stack of RProgN is printed backwards, so the first 0 encodes the second 0, and vice versa.

This can be verified empirically; the program

1
2

prints

2
1

Try it online!

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Oh my, it's actually getting usage. I feel like a proud father. \$\endgroup\$
    – ATaco
    Dec 16, 2016 at 5:26
8
\$\begingroup\$

Klein, 11 + 6 = 17 bytes

3 additional bytes for the topology argument 001 and another 3 for ASCII output -A.

:?/:2+@> "

Try it online!

Let's start with the topology. The 1 at the end indicates that the north and south edges of the code are mapped to each other in reverse. So if the IP leaves the code through the south edge in the leftmost column, it will re-enter through the north edge in the rightmost column. We use this to skip to the end of the program.

:             Duplicate the top of the stack (implicitly zero).
?             Skip the next command if that value is non-zero (which it isn't).
/             Reflect the IP north.
              The IP leaves through the north edge in the third column from
              the left, so it will re-enter from the south edge in the third
              column from the right.
>             Move east.
":?/:2+@> "   Push the code points of the program, except for the quote itself
              to the stack.
:             Duplicate the top of the stack, now a 32 (the space).
?             Skip the next command (the /).
:             Duplicate the top of the stack again.
2+            Add 2, to turn the space into a quote.
@             Terminate the program.
\$\endgroup\$
8
+100
\$\begingroup\$

Charcoal, 64 31 32 (because of newlines)

My first answer in charcoal ever!

Similar to /// and other languages, just straight up ascii would print itself. however that is not payload and also boring, so here is an actual quine.

taking a golfing tip from Ascii-only, and my realisation that the second looping is pointless, I have reduced by >50%

A´α´´´A´F´α´⁺´´´´´ι´αα´AFα⁺´´ια

Try it online!

Explanation

(thanks to ascii-only for making most of this.)

A                     α            Assign to a
 ´α´´´A´F´α´⁺´´´´´ι´α             "α´AFα⁺´´ια", but with ´ escape character with each
                                    character
                                    these are the variable being assigned to, and the
                                    rest of the program that is not the string.

                        ´A         Print A to the grid. current grid: "A"
                           Fα⁺´´ι  For each character in a, print ´ + character
                                    this results in the escaped version of the string
                                    which is the literal string that is assigned at the 
                                    start. current grid state: "A´α´´´A´F´α´⁺´´´´´ι´α"

                                  α Print a ("α´AFα⁺´´ια"), which is the commands after
                                    the string assignment. final grid state vvv:
                                                 "A´α´´´A´F´α´⁺´´´´´ι´αα´AFα⁺´´ια"

[implicitly print the grid: "A´α´´´A´F´α´⁺´´´´´ι´αα´AFα⁺´´ια", the source, with a trailing newline]
\$\endgroup\$
15
  • \$\begingroup\$ Wish I was better at reading Charcoal. Looking forward to that explanation :) \$\endgroup\$
    – Emigna
    May 19, 2017 at 10:11
  • 1
    \$\begingroup\$ I can hardly read this myself :P \$\endgroup\$ May 19, 2017 at 10:12
  • \$\begingroup\$ You can leave off the final closing double angle bracket, saving 3 bytes: A´α´´´A´F´L´α´«´´´´´§´α´ι´»´F´L´α´«´§´α´ια´AFLα«´´§αι»FL᫧αι \$\endgroup\$
    – ASCII-only
    May 19, 2017 at 10:33
  • \$\begingroup\$ Oh wait you can also iterate over the string directly. 37 bytes: A´α´´´A´F´α´⁺´´´´´ι´F´α´ια´AFα⁺´´ιFαι \$\endgroup\$
    – ASCII-only
    May 19, 2017 at 10:38
  • \$\begingroup\$ @ASCII-only couldn't this be one byte? f \$\endgroup\$
    – user63187
    May 19, 2017 at 14:11
8
\$\begingroup\$

///, 204 bytes

/<\>/<\\\\>\\\\\\//P1/<>/<<>\><>/<<>\<>\<>\<>\><>\<>\<>\<>\<>\<>\<>/<>/P<>1<>/P<>2<>/<>/P<<>\<>\><>\<>\<>2<>/P<>1<>/<>/<<>\><>/<<<>\<>\>><>\<>\<>/<>/<<>\<>\><>/<>/P<>1//P<\\>\\2/P1//<\>/<<\\>>\\//<\\>//P1

Try it online!

With some helpful whitespace inserted:

/<\>/<\\\\>\\\\\\/
/P1/
    <>/<<>\><>/<<>\<>\<>\<>\><>\<>\<>\<>\<>\<>\<>/<>/P<>1<>/P<>2<>/<>/P<<>\<>\><>\<>\<>2<>/P<>1<>/<>/<<>\><>/<<<>\<>\>><>\<>\<>/<>/<<>\<>\><>/<>/P<>1
/
/P<\\>\\2/P1/
/<\>/<<\\>>\\/
/<\\>//
P1

How it works

  • The long third line is the quining data. It is made from the entire rest of the program, with a P2 in the spot where the data itself would fit, and then with the string <> inserted before each character from the set \/12.
    • It would be harmless to put <> before all characters in the data, but only these are necessary - \/ because they need escaping to be copied, and 12 because it's vital to have a break inside P1 and P2 to prevent infinite loops when substituting them.
  • The first substitution changes all the <> prefixes into <\\>\\\. The \ in the source <\> is there to prevent its final printable form from being garbled by the other substitutions.
  • The second substitution includes the quining data, copying them to the other P1s in the program. The <\\>\\\ prefixes now become <\>\ in both copies.
  • The third substitution copies one of the quining data copies (in the substitution itself) into the middle of the other (at the end of the program), marked by the string P<\>\2. In the inner copy, the <\>\ prefix now becomes <> again.
  • The fourth substitution changes the inner copy's <> prefixes into <<\>>\. The change is needed to introduce the final backspace, protecting any following \s and /s that are to be printed. The inner <\> is necessary to prevent this substitution from infinitely looping – just a backslash here wouldn't do, as it would be garbled by the fifth substitution.
  • The fifth substitution removes all instances of the string <\>, both those remaining in the outer copy of the quining data, and those produced by the fourth substitution.
  • Finally, we reach the constructed copy of the program, with suitable backslashes prepended to some characters, ready for printing.
\$\endgroup\$
8
+200
\$\begingroup\$

Reflections, 4222 bytes

Since wastl out-golfed me by about... 1.810371 bytes through a vastly superior encoding system, I've decided to have another look at the problem. Since my program is still quite long, here's the main section (with SOHs replaced with spaces):

\0=0#_(4:(2(4(40\
      /# 0v\/(1v/
      \+#@~ > ~<
/#@#_#_#_1^1/
+
\#1)(2:2)4=/

Try It Online! (but have patience) (ASCII-only points out that unchecking the time between steps will make it go faster, but beware of the javascript freezing up your browser)

This uses the same encoding as wastl's answer, where each character with byte value n is represented by n newlines followed by

+
#

and the first character of the code is \ to change the pointer's direction down. Additionally, it also encodes the \ as well as the #,+ and newline in this process to save on doing them later

The main code is a more streamlined version of wastl's, where quite a few shortcuts have been made. I've also replaced all the spaces with SOHs (byte value 1) to save on bytes.

Detailed explanation

\0=0        Create a copy of the data in stack 0
    #_      Print the `\`
      (4:(2(4(4   Push the +, \n, # to stack 4, and a copy of the newline to stack 2
               0\ Switch back to the intact copy of the data

            /(1v/ Reverse the data
            > ~<
          ^1/


          v\
          ~   While the stack exists
          ^

          v\
              
           1  Move data to stack 1

         4=/  Copy #, \n, +
    (2:2)     Copy newline
\#1)          Get top of data

+
\#        Redefine origin and move up

/
+     Push -2

/#@   Print the newline the value of the top of data times
   #_#_#_   Print the +, \n, #
         1^ Switch back to the data and loop again


      /# 0v When the data stack is empty
      \+#@~
/#@#_#_#_1^

         0  Switch to the other copy of the data

      /#    Redefine the origin to push 1
      \+
        #@  Print the whole stack
          ~ >  And end
\$\endgroup\$
2
  • \$\begingroup\$ You should also say that unchecking the time between steps box shortens run time to like <5 seconds \$\endgroup\$
    – ASCII-only
    May 22, 2018 at 0:58
  • \$\begingroup\$ @ASCII-only Ehh, depends on the computer I guess. Mine freezes up and finishes in about 40 seconds \$\endgroup\$
    – Jo King
    May 22, 2018 at 1:51
8
\$\begingroup\$

J (REPL) - 20 (16?) char

Seems we're missing a J entry. Trivially, any sentence that doesn't evaluate gets itself printed in the REPL, so 1 or + or +/ % # are all quines in that sense. A non-trivial quine would be one that produces specifically a string containing the source code.

',~@,~u:39',~@,~u:39

u:39 is the ASCII character 39, i.e. the single quote, and ',~@,~u:39' is a string. , is the append verb. The main verb ,~@,~ evaluates as follows:

x ,~@,~ y      
y ,~@, x       NB. x f~ y => y f x       "Passive"
,~ (y , x)     NB. x f@g y => f (x g y)  "At"
(y,x) , (y,x)  NB. f~ y => y f y         "Reflex"

So the result is 'string'string when x is string and y is the single quote, and thus this is a quine when x is ,~@,~u:39.

If we're allowed the J standard library as well, then we can write the 16 character

(,quote)'(,quote)'

which appends the quote of the string (,quote) to itself.

\$\endgroup\$
8
\$\begingroup\$

Rust, 72 66 bytes

fn main(){print!("{}{0:?})}}","fn main(){print!(\"{}{0:?})}}\",")}

Try it online!

\$\endgroup\$
8
\$\begingroup\$

Whitespace, 338 bytes

-3 bytes thanks to Dorian pointing out a mistake

   	 		   		      	    	  			    	     		 	 	 	 		  				  	      	     		  	   				     			 		   						  	 		 		  					    			  					    	 	  				       				 	    	 	  	   		 	 				 	  	   		 	  					 	 					 
   	 

 	 

 	 

 	
   	
	   
  
 	  	
 	  	
	 	  
 
	 	
 	  	

 	
	 		 
 
	 	
   	   
	   	
  
	

  	
 


   
   	     
	
  
	

Try it online!

Not really much to see, but the code is there. This terminates with a 'Can't return from subroutine' error, which is only about 10 or so bytes extra to remove. Translated from whitespace, the tokens are:

push 213928514417226051472880134683878051755207959239232598316788086
push 2
call PRINT_SPACE
call PRINT_SPACE
call DIV_MOD_PRINT
push 1
add

label DIV_MOD_PRINT
    copy 2nd item in stack
    copy 2nd item in stack
    div
    jump if zero to POP_AND_PRINT_SPACE
    copy 2nd item in stack
    call DIV_MOD_PRINT
    mod
    dupe
    jump if zero to POP_AND_PRINT_SPACE
    push 8
    add
    print as character
    return

label POP_AND_PRINT_SPACE
    pop
    label PRINT_SPACE
        push 32
        print as character
        return

This starts off by pushing a rather large number in binary spaces and tabs. This number represents the rest of the program in trinary (since Whitespace has 3 valid characters), with space being 0, tab being 1 and newline as 2.

The main part of this code is the DIV_MOD_PRINT function, which assumes that the large number and the divisor is on top of the stack. This makes a copy of the two elements, then divides the number by the divisor and recursively calls the function again, returning once the result of the division is zero. On the tail call, this takes the two copied elements and gets the remainder after division. Then it maps it to the representation above.

This function is reused twice on the large number we pushed at the beginning, once with the divisor 2 to print the number itself in tabs and spaces, and again with 3 to print the rest of the program.

There are a couple of caveats; for example, we can't represent leading spaces with leading zeroes, so we with have to print those manually before we call the function the first time. This is partially mitigated by the fact that we stop the recursion by jumping to the POP_AND_PRINT_SPACE label, which means that we print a leading space anyway.

However, that causes one of the modulo pairs not to be evaluated, therefore the last character represented is not printed. This is actually a good thing, for a couple of reasons. First, since the binary number representation is terminated with a newline which would have had to have been printed (since we print a leading space), instead, if we ensure the last character of the binary number is a space, the newline is now the first character of the rest of the program. We can make the last character a space easily, since we aren't printing the last character of the program by adding a space or tab when encoding the number literal.

For reference, my encoding program, my commented program, and I used WhiteLips to debug the program.

\$\endgroup\$
0
8
\$\begingroup\$

APL, 22 bytes

1⌽22⍴11⍴'''1⌽22⍴11⍴'''

This is part of the FinnAPL Idiom Library.

        '''1⌽22⍴11⍴'''  ⍝ The string literal '1⌽22⍴11⍴' (quotes in string)
     11⍴                ⍝ Fill an 11-element array with these characters
                        ⍝ But the string has length 10, so we get '1⌽22⍴11⍴''
  22⍴                   ⍝ Do this again for 22 chars: '1⌽22⍴11⍴'''1⌽22⍴11⍴''
1⌽                      ⍝ Rotate left (puts quote at the back)

Try it on ngn/apl

\$\endgroup\$
8
\$\begingroup\$

Python 3, 34 Bytes

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

As far as I'm aware this is shorter than any other published Python 3 quine, mainly by virtue of having been written in the future with respect to most of them, so it can use :=.

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Mar 4, 2022 at 0:17
  • 2
    \$\begingroup\$ There is _='_=%r;print(_%%_)';print(_%_) (32 bytes w/newline), basically the Python 2 quine ported to Python3 \$\endgroup\$
    – SuperPizz
    Apr 17, 2022 at 17:46
7
\$\begingroup\$

Befunge 98 - 17 11 characters

<@,+1!',k9"

Or if using g is allowed:

Befunge 98 - 12 10

<@,g09,k8"
\$\endgroup\$
2
  • \$\begingroup\$ Explanation for why using g may not be allowed? \$\endgroup\$
    – MD XF
    Jun 9, 2017 at 23:56
  • \$\begingroup\$ @MDXF g is arguably reading the source code. Befunge copies the code to the execution space and g reads the character at the x, y position in the execution space \$\endgroup\$
    – Justin
    Jun 11, 2017 at 6:50
7
\$\begingroup\$

TECO, 20 bytes

<Tab>V27:^TJDV<Esc>V27:^TJDV

The <Esc> should be replaced with ASCII 0x1B, and the <Tab> with 0x09.

  • <Tab>V27:^TJDV<Esc> inserts the text <Tab>V27:^TJDV. This is not because there is a text insertion mode which TECO starts in by default. Instead, <Tab> text <Esc> is a special insertion command which inserts a tab, and then the text. A string whose own initial delimiter is part of the text -- very handy.
  • V prints the current line.
  • 27:^T prints the character with ASCII code 27 without the usual conversion to a printable representation.
  • J jumps to the beginning of the text.
  • D deletes the first character (the tab).
  • V prints the line again.
\$\endgroup\$
1
1 2
3
4 5
15

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.