246
\$\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\$ Commented May 3, 2011 at 2:49
  • 64
    \$\begingroup\$ @muntoo it's a play on "Learn you a Haskell for Great Good". \$\endgroup\$ Commented May 3, 2011 at 2:52
  • 28
    \$\begingroup\$ Did anybody notice that this is question 69? \$\endgroup\$
    – aidan0626
    Commented Oct 24, 2020 at 22:47

459 Answers 459

1
2 3 4 5
16
135
\$\begingroup\$

Hexagony, side-length 17 16, 816 705 bytes

180963109168843880558244491673953327577233938129339173058720504081484022549811402058271303887670710274969455065557883702369807148960608553223879503892017157337685576056512546932243594316638247597075423507937943819812664454190530214807032600083287129465751195839469777849740055584043374711363571711078781297231590606019313065042667406784753422844".".>.@.#.#.#.#.#.#.#.>.(...........................<.".......".".>./.4.Q.;.+.<.#.>...........................<.".....".".>.#.#.>.N.2.'.\.>.............=.=......._.<.".....".".>.>.;.'.=.:.\.>.......................<."...".".>.\.'.%.'.<.#.>..............._.....<."...".".>.#.#.>.<.#.>...............=.=.<.".".".>.#.\.'.R./.>.................<.".!.........../.>.

Try it online!

This is what it looks like unfolded:

                1 8 0 9 6 3 1 0 9 1 6 8 8 4 3 8
               8 0 5 5 8 2 4 4 4 9 1 6 7 3 9 5 3
              3 2 7 5 7 7 2 3 3 9 3 8 1 2 9 3 3 9
             1 7 3 0 5 8 7 2 0 5 0 4 0 8 1 4 8 4 0
            2 2 5 4 9 8 1 1 4 0 2 0 5 8 2 7 1 3 0 3
           8 8 7 6 7 0 7 1 0 2 7 4 9 6 9 4 5 5 0 6 5
          5 5 7 8 8 3 7 0 2 3 6 9 8 0 7 1 4 8 9 6 0 6
         0 8 5 5 3 2 2 3 8 7 9 5 0 3 8 9 2 0 1 7 1 5 7
        3 3 7 6 8 5 5 7 6 0 5 6 5 1 2 5 4 6 9 3 2 2 4 3
       5 9 4 3 1 6 6 3 8 2 4 7 5 9 7 0 7 5 4 2 3 5 0 7 9
      3 7 9 4 3 8 1 9 8 1 2 6 6 4 4 5 4 1 9 0 5 3 0 2 1 4
     8 0 7 0 3 2 6 0 0 0 8 3 2 8 7 1 2 9 4 6 5 7 5 1 1 9 5
    8 3 9 4 6 9 7 7 7 8 4 9 7 4 0 0 5 5 5 8 4 0 4 3 3 7 4 7
   1 1 3 6 3 5 7 1 7 1 1 0 7 8 7 8 1 2 9 7 2 3 1 5 9 0 6 0 6
  0 1 9 3 1 3 0 6 5 0 4 2 6 6 7 4 0 6 7 8 4 7 5 3 4 2 2 8 4 4
 " . " . > . @ . # . # . # . # . # . # . # . > . ( . . . . . .
  . . . . . . . . . . . . . . . . . . . . . < . " . . . . . .
   . " . " . > . / . 4 . Q . ; . + . < . # . > . . . . . . .
    . . . . . . . . . . . . . . . . . . . . < . " . . . . .
     " . " . > . # . # . > . N . 2 . ' . \ . > . . . . . .
      . . . . . . . = . = . . . . . . . _ . < . " . . . .
       . " . " . > . > . ; . ' . = . : . \ . > . . . . .
        . . . . . . . . . . . . . . . . . . < . " . . .
         " . " . > . \ . ' . % . ' . < . # . > . . . .
          . . . . . . . . . . . _ . . . . . < . " . .
           . " . " . > . # . # . > . < . # . > . . .
            . . . . . . . . . . . . = . = . < . " .
             " . " . > . # . \ . ' . R . / . > . .
              . . . . . . . . . . . . . . . < . "
               . ! . . . . . . . . . . . / . > .
                . . . . . . . . . . . . . . . .

Ah well, this was quite the emotional rollercoaster... I stopped counting the number of times I switched between "haha, this is madness" and "wait, if I do this it should actually be fairly doable". The constraints imposed on the code by Hexagony's layout rules were... severe.

It might be possible to reduce the side-length by 1 or 2 without changing the general approach, but it's going to be tough (only the cells with # are currently unused and available for the decoder). At the moment I also have absolutely no ideas left for how a more efficient approach, but I'm sure one exists. I'll give this some thought over the next few days and maybe try to golf off one side-length, before I add an explanation and everything.

Well at least, I've proven it's possible...

Some CJam scripts for my own future reference:

\$\endgroup\$
11
  • 71
    \$\begingroup\$ Dear pete what is this. \$\endgroup\$ Commented Feb 26, 2016 at 23:05
  • 2
    \$\begingroup\$ How long did it take to make this? \$\endgroup\$
    – Adnan
    Commented Feb 26, 2016 at 23:13
  • 3
    \$\begingroup\$ @AandN I've been playing around with concepts for a general "template" since yesterday now and then (that didn't involve any actual testing... just typing up some stuff on a 7x7 grid and seeing if it might work... I discarded probably half a dozen approaches already there). The actual coding then took this evening... maybe 3 hours, I'd say. \$\endgroup\$ Commented Feb 26, 2016 at 23:15
  • 14
    \$\begingroup\$ Words can't explain how astonished I am when seeing this in action with Esoteric IDE step by step... To whom may want to understand this, this Hexagon encodes the "decoder" part into an integer which is printed with ! and then with a mirror / on the 2nd last line it enters the decoder to print the decoder code to complete the quine. This has a miraculous use of < and > which reads the multiline very big integer and built the area for storing the decoder. I'd really love to know what "dozens of approaches" are being considered? \$\endgroup\$
    – Sunny Pun
    Commented Oct 24, 2016 at 5:48
  • 5
    \$\begingroup\$ Explanation? --- \$\endgroup\$
    – MD XF
    Commented Jun 16, 2017 at 4:21
93
+1050
\$\begingroup\$

Hexagony, side length 11, 314 bytes

164248894991581511673077637999211259627125600306858995725520485910920851569759793601722945695269172442124287874075294735023125483.....!/:;.........)%'=a':\....................\...................\..................\.................\................\...............\..............\..$@.........\$><>'?2='%.<\:;_;4Q

Try it online!


Note: Currently the shortest program is only 261 bytes long, using a similar technique.

Older version:

Hexagony, side length 11, 330 bytes

362003511553420961423766261426252539048636523959468260999944549820033581478284471415809677091006384959302453627348235790194699306179..../:{;+'=1P'%'a{:..\.....................\...................\..................\.................\................\...............\..............\.............\!$><........\..@>{?2'%<......:;;4Q/

Try it online!

Encoder: Try it online!

The program is roughly equivalent to this Python code: Try it online!

Unfolded code:

           3 6 2 0 0 3 5 1 1 5 5
          3 4 2 0 9 6 1 4 2 3 7 6
         6 2 6 1 4 2 6 2 5 2 5 3 9
        0 4 8 6 3 6 5 2 3 9 5 9 4 6
       8 2 6 0 9 9 9 9 4 4 5 4 9 8 2
      0 0 3 3 5 8 1 4 7 8 2 8 4 4 7 1
     4 1 5 8 0 9 6 7 7 0 9 1 0 0 6 3 8
    4 9 5 9 3 0 2 4 5 3 6 2 7 3 4 8 2 3
   5 7 9 0 1 9 4 6 9 9 3 0 6 1 7 9 . . .
  . / : { ; + ' = 1 P ' % ' a { : . . \ .
 . . . . . . . . . . . . . . . . . . . . \
  . . . . . . . . . . . . . . . . . . . \ 
   . . . . . . . . . . . . . . . . . . \  
    . . . . . . . . . . . . . . . . . \   
     . . . . . . . . . . . . . . . . \    
      . . . . . . . . . . . . . . . \     
       . . . . . . . . . . . . . . \      
        . . . . . . . . . . . . . \       
         ! $ > < . . . . . . . . \        
          . . @ > { ? 2 ' % < . .         
           . . . . : ; ; 4 Q / .          

Two .s takes 1 bit. Any other characters take 1 bit and a base-97 digit.

Explanation

Click at the images for larger size. Each explanation part has corresponding Python code to help understanding.

Data part

Instead of the complex structure used in some other answers (with <, " and some other things), I just let the IP pass through the lower half.

Data

First, the IP runs through a lot of numbers and no-op's (.) and mirrors (\). Each digit appends to the number in the memory, so in the end the memory value is equal to the number at the start of the program.

mem = 362003511...99306179

! prints it,

stdout.write(str(mem))

and $ jumps through the next >.

Starting from the <. If the memory value mem is falsy (<= 0, i.e., the condition mem > 0 is not satisfied), we have done printing the program, and should exit. The IP would follow the upper path.

Exit

(let the IP runs around the world for about 33 commands before hitting the @ (which terminates the program) because putting it anywhere else incurs some additional bytes)

If it's true, we follow the lower path, get redirected a few times and execute some more commands before hitting another conditional.

# Python                    # Hexagony
# go to memory cell (a)     # {
a = 2                       # ?2
# go to memory cell (b)     # '
b = mem % a                 # %

Now the memory looks like this:

Mem1

If the value is truthy:

if b > 0:

the following code is executed:

# Python                    # Hexagony
b = ord('Q')                # Q
b = b*10+4                  # 4
# Note: now b == ord('.')+256*3
stdout.write(chr(b%256))    # ;
stdout.write(chr(b%256))    # ;

See detailed explanation of the Q4 at MartinEnder's HelloWorld Hexagony answer. In short, this code prints . twice.

Originally I planned for this to print . once. When I came up with this (print . twice) and implement it, about 10 digits were saved.

Then,

b = mem // a                # :

Here is a important fact I realized that saved me about 14 digits: You don't need to be at where you started.


To understand what I'm saying, let's have a BF analogy. (skip this if you already understood)

Given the code

while a != 0:
    b, a = a * 2, 0
    a, b = b, 0
    print(a)

Assuming we let a be the value of the current cell and b be the value of the right cell, a straightforward translation of this to BF is:

[             # while a != 0:
    [->++<]       # b, a = a * 2, 0
    >[-<+>]       # a, b = b, 0
    <.            # print(a)
]

However, note that we don't need to be at the same position all the time during the program. We can let the value of a be whatever we are at the start of each iteration, then we have this code:

[             # while a != 0:
    [->++<]       # b, a = a * 2, 0
                  # implicitly let (a) be at the position of (b) now
    .             # print(a)
]

which is several bytes shorter.


Also, the corner wrapping behavior also saves me from having a \ mirror there - without it I would not be able to fit the digits (+2 digits for the \ itself and +2 digits for an unpaired . to the right of it, not to mention the flags)

(details:

  • The IP enters the lower-left corner, heading left
  • It get warped to the right corner, still heads left
  • It encounters a \ which reflects it, now it heads right-up
  • It goes into the corner and get warped again to the lower-left corner

)


If the value (of the mod 2 operation above) is falsy (zero), then we follow this path:

# Python                 # Hexagony   # Memory visualization after execution
b = mem // a             # :          # click here
base = ord('a') # 97     # a
y = b % base             # '%
offset = 33              # P1
z = y + offset           # ='+
stdout.write(chr(z))     # ;          # click here
mem = b // base          # {:         # click here

I won't explain too detailed here, but the offset is actually not exactly 33, but is congruent to 33 mod 256. And chr has an implicit % 256.

\$\endgroup\$
13
  • 3
    \$\begingroup\$ Man, that is a lot of no-ops \$\endgroup\$
    – Jo King
    Commented Feb 21, 2018 at 8:02
  • 40
    \$\begingroup\$ I laughed at "To understand what I'm saying, let's have a [BrainFuck] analogy." Only on PPCG... :) \$\endgroup\$
    – lynn
    Commented Feb 23, 2018 at 16:52
  • 2
    \$\begingroup\$ I scrolled like 3 times to the top of the answer to upvote it, only to find out that I did it already... \$\endgroup\$
    – Maya
    Commented Feb 23, 2018 at 16:56
  • 3
    \$\begingroup\$ 310 bytes by taking advantage of the new space from shortening the number \$\endgroup\$
    – Jo King
    Commented Sep 19, 2019 at 11:22
  • 5
    \$\begingroup\$ 308 bytes by taking out even more space \$\endgroup\$
    – Jo King
    Commented Sep 19, 2019 at 12:38
91
\$\begingroup\$

MySQL, 167 characters

SELECT REPLACE(@v:='SELECT REPLACE(@v:=\'2\',1+1,REPLACE(REPLACE(@v,\'\\\\\',\'\\\\\\\\\'),\'\\\'\',\'\\\\\\\'\'));',1+1,REPLACE(REPLACE(@v,'\\','\\\\'),'\'','\\\''));

That's right. :-)

I really did write this one myself. It was originally posted at my site.

\$\endgroup\$
85
+500
\$\begingroup\$

Brain-Flak, 9.8e580 1.3e562 9.3e516 12818 11024 4452 4332 4240 4200 4180 3852 3656 3616 3540 2485 + 3 = 2488 bytes

Now fits in the observable universe!

(())(()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(()()()()())(())(())(())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(()()()()())(())(())(())(())(())(())(()())(())(())(())(()())(()()()())(())(()()()()())(()())(()())(()())(()()())(())(()())(())(()()()()())(()())(()()()()())(())(())(())(())(())(()())(())(())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(()())(()())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(()()())(()())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(())(())(()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(()()())(())(()()())(())(())(())(()())(()()())(()())(())(()()()()())(()())(())(()()())(())(()()()()())(())(())(())(()()())(())(())(())(()())(())(()())(()()()())(())(())(()()()()())(()())(()())(())(()()())(())(())(())(())(()()())(()())(())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()())(())(()()()()())(()()()()())(())(()()())(())(())(()())(())(()()()()())(())(()()()()())(())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(()()()()())(())(()()()()())(())(())(())(()())(())(()()()()())(())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()()()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(())(()())(()()()())(())(())(()())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(()()())(())(())(()())(())(())(()()()()())(()()()())(()())(()())(()()())(())(()())(())(()()()()())(()())(()()()()())(())(())(())(()()()())(()()()())(()())([[]]){({}()<(([{}]())<{({}())<>(((((()()()()()){}){}){}())[()])<>{({}())<>{}({}(((()()()){}())){}{})<>{({}())<>({}(((()()()()()){})){}{}())<>{{}<>({}(((()()()()){}){}){})(<>)}}<>(({})[()()])<>}}{}<>({}(<()>)<><{({}<>)<>}<>>){({}<>)<>}{}(<>)<>{({}<>)<>}{}(((((((()()()()()){}){}){}))()))>){({}()<((({}[()])()))>)}{}<>{({}<>)<>}{}>)}{}<>{({}<>)<>}<>

Try it online!


Explanation

This Quine works like most Quines in esoteric languages; it has two parts an encoder and a decoder. The encoder is all of the parentheses at the beginning and the decoder is the more complex part at the very end.

A naive way of encoding the program would be to put the ASCII value of every character in the decoder to the stack. This is not a very good idea because Brain-Flak only uses 8 characters (()<>[]{}) so you end up paying quite a few bytes to encode very little information. A smarter idea, and the one used up until now is to assign each of the 8 braces to an much smaller number (1-8) and convert these to the ASCII values with our decoder. This is nice because it costs no more than 18 bytes to encode a character as opposed to the prior 252.

However this program does neither. It relies on the fact that Brain-Flak programs are all balanced to encode the 8 braces with the numbers up to 5. It encodes them as follows.

(       -> 2
<       -> 3
[       -> 4
{       -> 5
),>,],} -> 1

All the close braces are assigned 1 because we can use context to determine which of them we need to use in a particular scenario. This may sound like a daunting task for a Brain-Flak program, but it really is not. Take for example the following encodings with the open braces decoded and the close braces replaced with a .:

(.
((..
<([.{...

Hopefully you can see that the algorithm is pretty simple, we read left to right, each time we encounter a open brace we push its close brace to an imaginary stack and when we encounter a . we pop the top value and put it in place of the .. This new encoding saves us an enormous number of bytes in the encoder while only losing us a handful of bytes on the decoder.

Low level explanation

Work in progress

\$\endgroup\$
12
  • 31
    \$\begingroup\$ I think you win for longest solution to a code-golf challenge... \$\endgroup\$
    – user45941
    Commented Oct 4, 2016 at 10:40
  • 24
    \$\begingroup\$ Just made the largest single golf in the history of PPCG Nope. 9.8e580 is still impressive though. \$\endgroup\$
    – Dennis
    Commented Oct 4, 2016 at 17:15
  • 24
    \$\begingroup\$ +1 for fitting into the observable universe. Also, with TIO Nexus, the permalink should fit in the answer. tio.run/nexus/… \$\endgroup\$
    – Dennis
    Commented Dec 7, 2016 at 6:48
  • 5
    \$\begingroup\$ ... very big golf ... \$\endgroup\$ Commented Dec 9, 2016 at 23:21
  • 5
    \$\begingroup\$ I think you win for most bytes cut off \$\endgroup\$
    – user63187
    Commented Feb 25, 2017 at 2:18
77
\$\begingroup\$

GolfScript, 2 bytes

1

(note trailing newline) This pushes the number 1 onto the stack. At the end of the program, GolfScript prints out all items in the stack (with no spaces in between), then prints a newline.

This is a true quine (as listed in the question), because it actually executes the code; it doesn't just "read the source file and print it" (unlike the PHP submission).


For another example, here's a GolfScript program to print 12345678:

9,(;
  1. 9: push 9 to the stack
  2. ,: consume the 9 as an argument, push the array [0 1 2 3 4 5 6 7 8] to the stack
  3. (: consume the array as an argument, push the array [1 2 3 4 5 6 7 8] and the item 0 to the stack
  4. ;: discard the top item of the stack

The stack now contains the array [1 2 3 4 5 6 7 8]. This gets written to standard output with no spaces between the elements, followed by a newline.

\$\endgroup\$
12
  • 20
    \$\begingroup\$ Or PowerShell, or PHP :-) \$\endgroup\$
    – Joey
    Commented Jan 28, 2011 at 9:54
  • 8
    \$\begingroup\$ You didn't go back in time and give the inventor the idea to invent GolfScript, did you? \$\endgroup\$ Commented May 3, 2011 at 2:38
  • 82
    \$\begingroup\$ Technically, 1 is not a quine in GolfScript: it outputs 1\n, where \n denotes a newline. However, the two-char program 1\n is a quine. \$\endgroup\$ Commented Feb 3, 2012 at 8:27
  • 23
    \$\begingroup\$ The one-char program \n probably also is? \$\endgroup\$
    – lynn
    Commented Aug 23, 2013 at 14:51
  • 12
    \$\begingroup\$ @Pseudonym a quine is literally a program which prints its own source. I don't think there are any arbitrary restrictions on "structure". \$\endgroup\$
    – user23597
    Commented Sep 24, 2015 at 11:07
74
+50
\$\begingroup\$

Prelude, 5157 4514 2348 1761 1537 664 569 535 423 241 214 184 178 175 169 148 142 136 133 bytes

Thanks to Sp3000 for saving 3 bytes.

This is rather long... (okay, it's still long ... at least it's beating the shortest known Brainfuck C# quine on this challenge now) but it's the first quine I discovered myself (my Lua and Julia submissions are really just translations of standard quine techniques into other languages) and as far as I'm aware no one has written a quine in Prelude so far, so I'm actually quite proud of this. :)

7( -^^^2+8+2-!( 6+ !
  ((#^#(1- )#)8(1-)8)#)4337435843475142584337433447514237963742423434123534455634423547524558455296969647344257)

That large number of digits is just an encoding of the core code, which is why the quine is so long.

The digits encoding the quine have been generated with this CJam script.

This requires a standard-compliant interpreter, which prints characters (using the values as character codes). So if you're using the Python interpreter you'll need to set NUMERIC_OUTPUT = False.

Explanation

First, a few words about Prelude: each line in Prelude is a separate "voice" which manipulates its own stack. These stacks are initialised to an infinite number of 0s. The program is executed column by column, where all commands in the column are executed "simultaneously" based on the previous stack states. Digits are pushed onto the stack individually, so 42 will push a 4, then a 2. There's no way to push larger numbers directly, you'll have to add them up. Values can be copied from adjacent stacks with v and ^. Brainfuck-style loops can be introduced with parentheses. See the link in the headline for more information.

Here is the basic idea of the quine: first we push loads of digits onto the stack which encode the core of the quine. Said core then takes those digits,decodes them to print itself and then prints the digits as they appear in the code (and the trailing )).

This is slightly complicated by the fact that I had to split the core over multiple lines. Originally I had the encoding at the start, but then needed to pad the other lines with the same number of spaces. This is why the initial scores were all so large. Now I've put the encoding at the end, but this means that I first need to skip the core, then push the digits, and jump back to the start and do the printing.

The Encoding

Since the code only has two voices, and and adjacency is cyclic, ^ and v are synonymous. That's good because v has by far the largest character code, so avoiding it by always using ^ makes encoding simpler. Now all character codes are in the range 10 to 94, inclusive. This means I can encode each character with exactly two decimal digits. There is one problem though: some characters, notably the linefeed, have a zero in their decimal representation. That's a problem because zeroes aren't easily distinguishable from the bottom of the stack. Luckily there's a simple fix to that: we offset the character codes by 2, so we have a range from 12 to 96, inclusive, that still comfortably fits in two decimal digits. Now of all the characters that can appear in the Prelude program, only 0 has a 0 in its representation (50), but we really don't need 0 at all. So that's the encoding I'm using, pushing each digit individually.

However, since we're working with a stack, the representations are pushed in reverse. So if you look at the end of the encoding:

...9647344257

Split into pairs and reverse, then subtract two, and then look up the character codes:

57 42 34 47 96
55 40 32 45 94
 7  (     -  ^

where 32 is corresponds to spaces. The core does exactly this transformation, and then prints the characters.

The Core

So let's look at how these numbers are actually processed. First, it's important to note that matching parentheses don't have to be on the same line in Prelude. There can only be one parenthesis per column, so there is no ambiguity in which parentheses belong together. In particular, the vertical position of the closing parenthesis is always irrelevant - the stack which is checked to determine whether the loop terminates (or is skipped entirely) will always be the one which has the (.

We want to run the code exactly twice - the first time, we skip the core and push all the numbers at the end, the second time we run the core. In fact, after we've run the core, we'll push all those numbers again, but since the loop terminates afterwards, this is irrelevant. This gives the following skeleton:

7(
  (                   )43... encoding ...57)

First, we push a 7 onto the first voice - if we don't do this, we'd never enter the loop (for the skeleton it's only important that this is non-zero... why it's specifically 7 we'll see later). Then we enter the main loop. Now, the second voice contains another loop. On the first pass, this loop will be skipped because the second stack is empty/contains only 0s. So we jump straight to the encoding and push all those digits onto the stack. The 7 we pushed onto the first stack is still there, so the loop repeats.

This time, there is also a 7 on the second stack, so we do enter loop on the second voice. The loop on the second voice is designed such that the stack is empty again at the end, so it only runs once. It will also deplete the first stack... So when we leave the loop on the second voice, we push all the digits again, but now the 7 on the first stack has been discarded, so the main loop ends and the program terminates.

Next, let's look at the first loop in the actual core. Doing things simultaneously with a ( or ) is quite interesting. I've marked the loop body here with =:

-^^^2+8+2-!
(#^#(1- )#)
 ==========

That means the column containing ( is not considered part of the loop (the characters there are only executed once, and even if the loop is skipped). But the column containing the ) is part of the loop and is ran once on each iteration.

So we start with a single -, which turns the 7 on the first stack into a -7... again, more on that later. As for the actual loop...

The loop continues while the stack of digits hasn't been emptied. It processes two digits at a time,. The purpose of this loop is to decode the encoding, print the character, and at the same time shift the stack of digits to the first voice. So this part first:

^^^
#^#

The first column moves the 1-digit over to the first voice. The second column copies the 10-digit to the first voice while also copying the 1-digit back to the second voice. The third column moves that copy back to the first voice. That means the first voice now has the 1-digit twice and the 10-digit in between. The second voice has only another copy of the 10-digit. That means we can work with the values on the tops of the stacks and be sure there's two copies left on the first stack for later.

Now we recover the character code from the two digits:

2+8+2-!
(1- )#

The bottom is a small loop that just decrements the 10-digit to zero. For each iteration we want to add 10 to the top. Remember that the first 2 is not part of the loop, so the loop body is actually +8+2 which adds 10 (using the 2 pushed previously) and the pushes another 2. So when we're done with the loop, the first stack actually has the base-10 value and another 2. We subtract that 2 with - to account for the offset in the encoding and print the character with !. The # just discards the zero at the end of the bottom loop.

Once this loop completes, the second stack is empty and the first stack holds all the digits in reverse order (and a -7 at the bottom). The rest is fairly simple:

( 6+ !
8(1-)8)#

This is the second loop of the core, which now prints back all the digits. To do so we need to 48 to each digit to get its correct character code. We do this with a simple loop that runs 8 times and adds 6 each time. The result is printed with ! and the 8 at the end is for the next iteration.

So what about the -7? Yeah, 48 - 7 = 41 which is the character code of ). Magic!

Finally, when we're done with that loop we discard the 8 we just pushed with # in order to ensure that we leave the outer loop on the second voice. We push all the digits again and the program terminates.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Listening to Hello World in Fugue right now... pretty catchy. \$\endgroup\$ Commented Apr 29, 2015 at 3:29
  • 20
    \$\begingroup\$ Martin, you gotta stop somewhere. \$\endgroup\$
    – seequ
    Commented Feb 25, 2016 at 21:12
  • 8
    \$\begingroup\$ I love that this has over 5000 bytes golfed overall, plus an acknowledgement to Sp3000 for saving 3 of them. \$\endgroup\$ Commented May 2, 2018 at 2:44
  • 4
    \$\begingroup\$ @KamilDrakari Those were the last 3 bytes though, so it's quite a big deal. ;) \$\endgroup\$ Commented May 2, 2018 at 6:58
57
\$\begingroup\$

Javascript ES6 - 21 bytes

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

I call this quine "The Bling Quine."

Sometimes, you gotta golf in style.

\$\endgroup\$
13
  • 1
    \$\begingroup\$ @TùxCräftîñg eliminating parentheses around template literals only works on native prototype functions, like Array.prototype.join. \$\endgroup\$ Commented Oct 21, 2016 at 3:44
  • 1
    \$\begingroup\$ I love this one so much. I don't think it's quite correct, though - the REPL environments I run it in all enclose the output in quotes, and evaluating it with node.js doesn't output anything. Needs a console.log somewhere. \$\endgroup\$
    – TehShrike
    Commented Jan 12, 2017 at 21:16
  • 2
    \$\begingroup\$ Hmm, not sure. I wrote this over a year ago (it was considered valid then), and I haven't been following quine rule changes too closely. However, adding alert or console.log after the arrow function and wrapping the template string in parentheses would work. \$\endgroup\$ Commented Jan 12, 2017 at 22:12
  • 8
    \$\begingroup\$ Also if You run this in the concole, it overwrites $ ( jQuery function ) on this site, and the upvote function won't work anymore. :) \$\endgroup\$ Commented May 19, 2017 at 11:09
  • 1
    \$\begingroup\$ If this is a quine, 0 is too. \$\endgroup\$ Commented May 26, 2019 at 5:41
53
+250
\$\begingroup\$

Vim, 11 bytes

q"iq"qP<Esc>hqP
  • iq"qP<Esc>: Manually insert a duplicate of the text that has to be outside the recording.
  • q" and hqP: Record the inside directly into the unnamed "" register, so it can be pasted in the middle. The h is the only repositioning required; if you put it inside the macro, it will be pasted into the result.

Edit

A note about recording with q": The unnamed register "" is a funny thing. It's not really a true register like the others, since text isn't stored there. It's actually a pointer to some other register (usually "- for deletes with no newline, "0 for yanks, or "1 for deletes with a newline). q" breaks the rules; it actually writes to "0. If your "" was already pointing to some register other than "0, q" will overwrite "0 but leave "" unchanged. When you start a fresh Vim, "" automatically points to "0, so you're fine in that case.

Basically, Vim is weird and buggy.

\$\endgroup\$
7
  • \$\begingroup\$ wait why doesn't this work for me \$\endgroup\$ Commented Oct 14, 2016 at 7:32
  • \$\begingroup\$ @DestructibleWatermelon Can't say for sure, but one explanation is most likely. Probably should have had it in the write-up before, since it can throw people off. Read the edit. \$\endgroup\$
    – udioica
    Commented Oct 14, 2016 at 8:19
  • \$\begingroup\$ you should probably put something about how pressing y or something before running can help \$\endgroup\$ Commented Oct 14, 2016 at 8:25
  • 7
    \$\begingroup\$ @mbomb007 The <Esc> notation is standard in Vim mappings (:help <>) and that's what vimgolf.com uses. Any experienced vimgolfer will be used to reading it. As for the unicode, I have to squint to read the little letters, and they obscure the method of typing them and searching the help file. \$\endgroup\$
    – udioica
    Commented Oct 15, 2016 at 21:44
  • 1
    \$\begingroup\$ This doesn't work for me if I already had something on the clipboard -- the final P pastes what was originally on the clipboard. \$\endgroup\$
    – Bbrk24
    Commented Nov 4, 2021 at 14:36
49
+500
\$\begingroup\$

Hexagony, side length 15 14 13 12, 616 533 456 383 bytes

After several days of careful golfing, rearranging loops and starting over, I've finally managed to get it down to a side 12 hexagon.

1845711724004994017660745324800783542810548755533855003470320302321248615173041097895645488030498537186418612923408209003405383437728326777573965676397524751468186829816614632962096935858"">./<$;-<.....>,.........==.........<"......."">'....>+'\.>.........==........<"......"">:>)<$=<..>..............$..<"...."">\'Q4;="/@>...............<"....."">P='%<.>.............<"..!'<.\=6,'/>

Try it online!

Unfolded:

            1 8 4 5 7 1 1 7 2 4 0 0
           4 9 9 4 0 1 7 6 6 0 7 4 5
          3 2 4 8 0 0 7 8 3 5 4 2 8 1
         0 5 4 8 7 5 5 5 3 3 8 5 5 0 0
        3 4 7 0 3 2 0 3 0 2 3 2 1 2 4 8
       6 1 5 1 7 3 0 4 1 0 9 7 8 9 5 6 4
      5 4 8 8 0 3 0 4 9 8 5 3 7 1 8 6 4 1
     8 6 1 2 9 2 3 4 0 8 2 0 9 0 0 3 4 0 5
    3 8 3 4 3 7 7 2 8 3 2 6 7 7 7 5 7 3 9 6
   5 6 7 6 3 9 7 5 2 4 7 5 1 4 6 8 1 8 6 8 2
  9 8 1 6 6 1 4 6 3 2 9 6 2 0 9 6 9 3 5 8 5 8
 " " > . / < $ ; - < . . . . . > , . . . . . .
  . . . = = . . . . . . . . . < " . . . . . .
   . " " > ' . . . . > + ' \ . > . . . . . .
    . . . = = . . . . . . . . < " . . . . .
     . " " > : > ) < $ = < . . > . . . . .
      . . . . . . . . . $ . . < " . . . .
       " " > \ ' Q 4 ; = " / @ > . . . .
        . . . . . . . . . . . < " . . .
         . . " " > P = ' % < . > . . .
          . . . . . . . . . . < " . .
           ! ' < . \ = 6 , ' / > . .
            . . . . . . . . . . . .

While it doesn't look like the most golfed of Hexagony code, the type of encoding I used is optimised for longer runs of no-ops, which is something you would otherwise avoid.

Explanation

This beats the previous Hexagony answer by encoding the no-ops (.) in a different way. While that answer saves space by making every other character a ., mine encodes the number of no-ops. It also means the source doesn't have to be so restricted.

Here I use a base 80 encoding, where numbers below 16 indicate runs of no-ops, and numbers between 16 and 79 represent the range 32 (!) to 95 (_) (I'm just now realising I golfed all the _s out of my code lol). Some Pythonic pseudocode:

i = absurdly long number
print(i)
base = 80
n = i%base
while n:
    if n < 16:
        print("."*(16-n))
    else:
        print(ASCII(n+16))
    i = i//base
    n = i%base

The number is encoded in the first half of the hexagon, with all the

" " > 
 " " > 
  ... etc

on the left side and the

 > ,
< "
 >
< "
... etc

on the right side redirecting the pointer to encode the number into one cell. This is taken from Martin Ender's answer (thanks), because I couldn't figure out a more efficient way.

It then enters the bottom section through the ->:

       " " > \ ' Q 4 ; = " / @ > . . . .
        . . . . . . . . . . . < " . . .
         . . " " > P = ' % < . > . . .
          . . . . . . . . . . < " . .
     ->    ! ' < . \ = 6 , ' / > . .

! prints the number and ' navigates to the right memory cell before starting the loop. P='% mods the current number by 80. If the result is 0, go up to the terminating @, else go down and create a cell next to the mod result with the value -16.

   . " " > ' . . . . > + ' \ . > . . . . . .
    . . . = = . . . . . . . . < " . . . . .
     . " " > : > ) < $ = < . . > . . . . .
      . . . . . . . . . $ . . < " . . . .
       " " > \ ' Q 4 ; = " / @ > . . . .
                      /
                     /

Set the cell to (mod value + -16). If that value is negative, go up at the branching >+'\, otherwise go down.

If the value is positive:

 " " > . / < $ ; - < . . . . . > , . . . . . .
  . . . = = . . . . . . . . . < " . . . . . .
   . " " > ' . . . . > + ' \ . > . . . . . .

The pointer ends up at the ;-< which sets the cell to (mod value - -16) and print it.

The the value is negative:

   . " " > ' . . . . > + ' \ . > . . . . . .
    . . . = = . . . . . . . . < " . . . . .
     . " " > : > ) < $ = < . . > . . . . .

Go down to the > ) < section which starts the loop. Here it is isolated:

     . . > ) < $ = < . .
      . . . . . . . . .
       \ ' Q 4 ; = " /

Which executes the code 'Q4;="= which prints a . (thanks again to Martin Ender, who wrote a program to find the letter-number combinations for characters) and moves back to the starting cell. It then increments ()) the mod value cell and loops again, until the mod value is positive.

When that is done, it moves up and joins with the other section at:

 " " > . / < $ ; - < . . .
            \
             \

The pointer then travels back to the start of the larger loop again

 " " > . / <--
  . . . = =
   . " " > ' 
    . . . = = 
     . " " > :
      . . . . .
       " " > \ ' . .
        . . . . . . .
         . . " " > P = ' % < . > . . .

This executes ='=:' which divides the current number by 80 and navigates to the correct cell.

Old version (Side length 13)

343492224739614249922260393321622160373961419962223434213460086222642247615159528192623434203460066247203920342162343419346017616112622045226041621962343418346002622192616220391962343417346001406218603959366061583947623434"">/':=<$;'<.....>(......................<"......"">....'...>=\..>.....................<"....."">....>)<.-...>...........==......<"...."">.."...'.../>.................<"..."">\Q4;3=/.@.>...............<".."".>c)='%<..>..!'<.\1*='/.\""

Try it online!

I can most definitely golf another side length off this, but I'll have to leave it til' tomorrow because it's getting late. Turns out I'm impatient and can't wait until tomorrow. Maybe another side can be golfed? :( ahhhhhhhhh i did it!

I even golfed off a couple of extra digits with a base 77 encoding, but it doesn't really matter, since it has the same bytecount.

\$\endgroup\$
1
  • 15
    \$\begingroup\$ This is amazing. The idea for this hybrid run-length encoding is really neat. :) Remind me to give you a bounty if I forget. \$\endgroup\$ Commented Feb 10, 2018 at 12:03
47
+500
\$\begingroup\$

Cubix, 20 bytes

3434Qu$v@!<"OOw\o;/"

Almost got the \o/...

Net:

    3 4
    3 4
Q u $ v @ ! < "
O O w \ o ; / "
    . .
    . .

Try it online

Try it here!

Additional notes

Background story

After being impressed by reading this great answer by @ais523, I started thinking about further golfing the quine. After all, there were quite a few no-ops in there, and that didn't feel very compressed. However, as the technique his answer (and mine as well) uses, requires the code to span full lines, a saving of at least 12 bytes was needed. There was one remark in his explanation that really got me thinking:

On the subject of golfing down this quine further, [...] it'd need [...] some other way to represent the top face of the cube [...]

Then, suddenly, as I stood up and walked away to get something to drink, it struck me: What if the program didn't use character codes, but rather numbers to represent the top face? This is especially short if the number we're printing has 2 digits. Cubix has 3 one-byte instructions for pushing double-digit numbers: N, S and Q, which push 10, 32 and 34 respectively, so this should be pretty golfy, I thought.

The first complication with this idea is that the top face is now filled with useless numbers, so we can't use that anymore. The second complication is that the top face has a size which is the cube size squared, and it needed to have an even size, otherwise one number would also end up on the starting position of the instruction pointer, leading to a polluted stack. Because of these complications, my code needed to fit on a cube of size 2 (which can contain 'only' 24 bytes, so I had to golf off at least 21 bytes). Also, because the top and bottom faces are unusable, I only had 16 effective bytes.

So I started by choosing the number that would become half of the top face. I started out with N (10), but that didn't quite work out because of the approach I was taking to print everything. Either way, I started anew and used S (32) for some reason. That did result in a proper quine, or so I thought. It all worked very well, but the quotes were missing. Then, it occured to me that the Q (34) would be really useful. After all, 34 is the character code of the double quote, which enables us to keep it on the stack, saving (2, in the layout I used then) precious bytes. After I changed the IP route a bit, all that was left was an excercise to fill in the blanks.

How it works

The code can be split up into 5 parts. I'll go over them one by one. Note that we are encoding the middle faces in reverse order because the stack model is first-in-last-out.

Step 1: Printing the top face

The irrelevant instructions have been replaced by no-ops (.). The IP starts the the third line, on the very left, pointing east. The stack is (obviously) empty.

    . .
    . .
Q u . . . . . .
O O . . . . . .
    . .
    . .

The IP ends at the leftmost position on the fourth line, pointing west, about to wrap around to the rightmost position on that same line. The instructions executed are (without the control flow character):

QOO
Q   # Push 34 (double quotes) to the stack
 OO # Output twice as number (the top face)

The stack contains just 34, representlng the last character of the source.

Step 2: Encode the fourth line

This bit pretty much does what you expect it to do: encode the fourth line. The IP starts on the double quote at the end of that line, and goes west while pushing the character codes of every character it lands on until it finds a matching double quote. This matching double quote is also the last character on the fourth line, because the IP wraps again when it reaches the left edge.

Effectively, the IP has moved one position to the left, and the stack now contains the representation of the fourth line in character codes and reverse order.

Step 3: Push another quote

We need to push another quote, and what better way than to recycle the Q at the start of the program by approaching it from the right? This has the added bonus that the IP directly runs into the quote that encodes the third line.

Here's the net version for this step. Irrelevant intructions have been replaced by no-ops again, the no-ops that are executed have been replaced by hashtags (#) for illustration purposes and the IP starts at the last character on the fourth line.

    . .
    . .
Q u $ . . . . .
. . w \ . . / .
    . #
    . #

The IP ends on the third line at the first instruction, about to wrap to the end of that line because it's pointing west. The following instructions (excluding control flow) are excecuted:

$uQ
$u  # Don't do anthing
  Q # Push the double quote

This double quote represents the one at the end of the third line.

Step 4: Encoding the third line

This works exactly the same as step 2, so please look there for an explanation.

Step 5: Print the stack

The stack now contains the fourth and third lines, in reverse order, so all we need to do now, it print it. The IP starts at the penultimate instruction on the third line, moving west. Here's the relevant part of the cube (again, irrelevant parts have been replaced by no-ops).

    . .
    . .
. . . v @ ! < .
. . . \ o ; / .
    . .
    . .

This is a loop, as you might have seen/expected. The main body is:

o;
o  # Print top of stack as character
 ; # Delete top of stack

The loop ends if the top item is 0, which only happens when the stack is empty. If the loop ends, the @ is executed, ending the program.

\$\endgroup\$
2
  • \$\begingroup\$ wish I could upvote this more \$\endgroup\$
    – MickyT
    Commented Apr 27, 2017 at 2:00
  • \$\begingroup\$ Bounties are always welcome ;-) \$\endgroup\$
    – Luke
    Commented Apr 27, 2017 at 7:23
45
\$\begingroup\$

Brainf*ck (755 characters)

This is based off of a technique developed by Erik Bosman (ejbosman at cs.vu.nl). Note that the "ESultanik's Quine!" text is actually necessary for it to be a quine!

->++>+++>+>+>++>>+>+>+++>>+>+>++>+++>+++>+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+>+>++>>>+++>>>>>+++>+>>>>>>>>>>>>>>>>>>>>>>+++>>>>>>>++>+++>+++>+>>+++>>>+++>+>+++>+>++>+++>>>+>+>+>+>++>+++>+>+>>+++>>>>>>>+>+>>>+>+>++>+++>+++>+>>+++>+++>+>+++>+>++>+++>++>>+>+>++>+++>+>+>>+++>>>+++>+>>>++>+++>+++>+>>+++>>>+++>+>+++>+>>+++>>+++>>>+++++++++++++++>+++++++++++++>++++++>+++++++++++++++>++++++++++>+++>+++>++++>++++++++++++++>+++>++++++++++>++++>++++++>++>+++++>+++++++++++++++>++++++++>++++>++++++++++++>+++++++++++++++>>++++>++++++++++++++>+++>+++>++++>++++++>+++>+++++++++>++++>+>++++>++++++++++>++++>++++++++>++>++++++++++>+>+++++++++++++++>+++++++++++++
ESultanik's Quine!
+[[>>+[>]+>+[<]<-]>>[>]<+<+++[<]<<+]>>+[>]+++[++++++++++>++[-<++++++++++++++++>]<.<-<]
\$\endgroup\$
8
  • 15
    \$\begingroup\$ That's a clever way to do it. \$\endgroup\$ Commented Jun 22, 2011 at 16:48
  • 14
    \$\begingroup\$ How does it work? \$\endgroup\$ Commented Sep 13, 2014 at 16:21
  • 4
    \$\begingroup\$ @proudhaskeller IIRC, the part before ESultanik's Quine! sets up the memory as a stack encoding ESultanik's Quine! and onward, with two bytes of memory for each character (ASCII value offsets from 0x1F). The final bit of code loops through the memory, first programmatically reproducing the ++>+++… codes for each character, then actually printing the characters. \$\endgroup\$
    – ESultanik
    Commented Feb 9, 2016 at 15:48
  • 4
    \$\begingroup\$ @CatsAreFluffy They are required for it to be a quine! While it is true that they could be removed, one would also have to change the preceding code to maintain the quine property. \$\endgroup\$
    – ESultanik
    Commented Mar 7, 2016 at 12:05
  • 1
    \$\begingroup\$ That's true. Also the newlines are necessary. \$\endgroup\$ Commented Mar 7, 2016 at 16:39
39
\$\begingroup\$

Vim, 17, 14 keystrokes

Someone randomly upvoted this, so I remembered that it exists. When I re-read it, I thought "Hey, I can do better than that!", so I golfed two bytes off. It's still not the shortest, but at least it's an improvement.


For a long time, I've been wondering if a vim quine is possible. On one hand, it must be possible, since vim is turing complete. But after looking for a vim quine for a really long time, I was unable to find one. I did find this PPCG challenge, but it's closed and not exactly about literal quines. So I decided to make one, since I couldn't find one.

I'm really proud of this answer, because of two firsts:

  1. This is the first quine I have ever made, and

  2. As far as I know, this is the worlds first vim-quine to ever be published! I could be wrong about this, so if you know of one, please let me know.

So, after that long introduction, here it is:

qqX"qpAq@q<esc>q@q

Try it online!

Note that when you type this out, it will display the <esc> keystroke as ^[. This is still accurate, since ^[ represents 0x1B, which is escape in ASCII, and the way vim internally represents the <esc> key.

Also note, that testing this might fail if you load an existing vim session. I wrote a answer explaining that here, if you want more information, but basically you need to launch vim with

vim -u NONE -N -i NONE

or type qqq before running this.

Explanation:

qq                  " Start recording into register 'q'
  X                 " Delete one character before the cursor (Once we play this back, it will delete the '@')
   "qp              " Paste register 'q'
      Aq@q<esc>     " Append 'q@q' to this line
               q    " Stop recording
                @q  " Playback register 'q'

On a side note, this answer is probably a world record for most 'q's in a PPCG answer, or something.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ 2i2i<esc> is so close. I feel like there must be something I can do to make this work. \$\endgroup\$
    – Zwei
    Commented Oct 1, 2016 at 20:41
  • \$\begingroup\$ @zwei I know, it's close it hurts! Actually, <Esc> is implicit in V, so that works. Unfortunately it also adds a newline, which is why I haven't posted it yet. \$\endgroup\$
    – DJMcMayhem
    Commented Oct 1, 2016 at 20:43
  • \$\begingroup\$ q"iq"qbP<Esc>qbP is 11. After you put this on reddit, I investigated the vimgolfing here and decided to make an account. This is the answer I posted there. \$\endgroup\$
    – udioica
    Commented Oct 11, 2016 at 12:49
  • 2
    \$\begingroup\$ @udioica Can you post that as an answer? \$\endgroup\$
    – DJMcMayhem
    Commented Oct 11, 2016 at 12:59
36
\$\begingroup\$

PostScript, 20 chars

Short and legit. 20 chars including trailing newline.

(dup == =)
dup == =
\$\endgroup\$
35
+250
\$\begingroup\$

Cubix, 45 bytes

.....>...R$R....W..^".<R.!'.\)!'"R@>>o;?/o'u"

You can test this code here.

This program is fairly hard to follow, but to have any chance to do so, we need to start by expanding it into a cube, like the Cubix interpreter does:

      . . .
      . . >
      . . .
R $ R . . . . W . . ^ "
. < R . ! ' . \ ) ! ' "
R @ > > o ; ? / o ' u "
      . . .
      . . .
      . . .

This is a Befunge-style quine, which works via exploiting wrapping to make string literals "wrap around" executable code (with only one " mark, the code is both inside and outside the quote at the same time, something that becomes possible when you have programs that are nonlinear and nonplanar). Note that this fits our definition of a proper quine, because two of the double quotes don't encode themselves, but rather are calculated later via use of arithmetic.

Unlike Befunge, though, we're using four strings here, rather than one. Here's how they get pushed onto the stack;

  1. The program starts at the top of the left edge, going rightwards; it turns right twice (R), making it go leftwards along the third and last of the lines that wrap around the whole cube. The double quote matches itself, so we push the entire third line onto the stack backwards. Then execution continues after the double quote.

  2. The u command does a U-turn to the right, so the next thing we're running is from '" onwards on the middle line. That pushes a " onto the stack. Continuing to wrap around, we hit the < near the left hand side of the cube and bounce back. When approaching from this direction, we see a plain " command, not '", so the entire second line is pushed onto the stack backwards above the third line and the double quote.

  3. We start by pushing a ! onto the stack ('!) and incrementing it ()); this produces a double quote without needing a double quote in our source code (which would terminate the string). A mirror (\) reflects the execution direction up northwards; then the W command sidesteps to the left. This leaves us going upwards on the seventh column, which because this is a cube, wraps to leftwards on the third row, then downwards on the third column. We hit an R, to turn right and go leftwards along the top row; then the $ skips the R via which we entered the program, so execution wraps round to the " at the end of the line, and we capture the first line in a string the same way that we did for the second and third.

  4. The ^ command sends us northwards up the eleventh column, which is (allowing for cube wrapping) southwards on the fifth. The only thing we encounter there is ! (skip if nonzero; the top of the stack is indeed nonzero), which skips over the o command, effectively making the fifth column entirely empty. So we wrap back to the u command, which once again U-turns, but this time we're left on the final column southwards, which wraps to the fourth column northwards. We hit a double quote during the U-turn, though, so we capture the entire fourth column in a string, from bottom to top. Unlike most double quotes in the program, this one doesn't close itself; rather, it's closed by the " in the top-right corner, meaning that we capture the nine-character string ...>......

So the stack layout is now, from top to bottom: fourth column; top row; "; middle row; "; bottom row. Each of these are represented on the stack with the first character nearest the top of the stack (Cubix pushes strings in the reverse of this order, like Befunge does, but each time the IP was moving in the opposite direction to the natural reading direction, so it effectively got reversed twice). It can be noted that the stack contents are almost identical to the original program (because the fourth column, and the north/top face of the cube, contain the same characters in the same order; obviously, it was designed like that intentionally).

The next step is to print the contents of the stack. After all the pushes, the IP is going northwards on the fourth column, so it hits the > there and enters a tight loop >>o;? (i.e. "turn east, turn east, output as character, pop, turn right if positive"). Because the seventh line is full of NOPs, the ? is going to wrap back to the first >, so this effectively pushes the entire contents of the stack (? is a no-op on an empty stack). We almost printed the entire program! Unfortunately, it's not quite done yet; we're missing the double-quote at the end.

Once the loop ends, we reflect onto the central line, moving west, via a pair of mirrors. (We used the "other side" of the \ mirror earlier; now we're using the southwest side. The / mirror hasn't been used before.) We encounter '!, so we push an exclamation mark (i.e. 33; we're using ASCII and Cubix doesn't distinguish between integers and characters) onto the stack. (Conveniently, this is the same ! which was used to skip over the o command earlier.) We encounter a pair of R commands and use them to make a "manual" U-turn (the second R command here was used earlier in order to reach the first row, so it seemed most natural to fit another R command alongside it.) The execution continues along a series of NOPs until it reaches the W command, to sidestep to the left. The sidestep crashes right into the > command on the second line, bouncing execution back exactly where it was. So we sidestep to the left again, but this time we're going southwards, so the next command to execute is the ) (incrementing the exclamation mark into a double quote), followed by an o (to output it). Finally, execution wraps along the eighth line to the second column, where it finds a @ to exit the program.

I apologise for the stray apostrophe on the third line. It doesn't do anything in this version of the program; it was part of an earlier idea I had but which turned out not to be necessary. However, once I'd got a working quine, I just wanted to submit it rather than mess around with it further, especially as removing it wouldn't change the byte count. On the subject of golfing down this quine further, it wouldn't surprise me if this were possible at 3×3 by only using the first five lines, but I can't see an obvious way to do that, and it'd need even tighter packing of all the control flow together with some other way to represent the top face of the cube (or else modifying the algorithm so that it can continue to use the fourth column even though it'd now be ten or eleven characters long).

\$\endgroup\$
5
  • \$\begingroup\$ Nice work, this is a really impressive score. I love how you encoded the top face. :) \$\endgroup\$ Commented Dec 18, 2016 at 8:45
  • \$\begingroup\$ This is just incredible! If it would help any, another way to push " is Q. \$\endgroup\$ Commented Dec 18, 2016 at 12:24
  • 1
    \$\begingroup\$ Wow! I never though I'd see a cubix quine! \$\endgroup\$
    – FlipTack
    Commented Dec 19, 2016 at 15:28
  • 3
    \$\begingroup\$ I didn't have time to read the explanation yesterday, but now that I have... Just... WOW. I can't believe how many characters are used for two or even three completely different purposes. This is probably the coolest Cubix program I've ever seen. \$\endgroup\$ Commented Dec 19, 2016 at 16:47
  • \$\begingroup\$ Good explanation. \$\endgroup\$ Commented Mar 22, 2017 at 3:28
34
\$\begingroup\$

Python 2, 30 bytes

_='_=%r;print _%%_';print _%_


Taken from here

\$\endgroup\$
6
  • 2
    \$\begingroup\$ +1, you beat my similar solution so I deleted it. It should be noted that this only works in Python 2. \$\endgroup\$
    – user344
    Commented Apr 28, 2014 at 12:32
  • 2
    \$\begingroup\$ It looks weird with the variable name as _, but reads better if you assign it to any letter, i.e. s: s='s=%r;print s%%s';print s%s \$\endgroup\$ Commented Oct 14, 2015 at 16:20
  • 6
    \$\begingroup\$ If this solution is not your own creation, you should make it Community Wiki. Also, the link is dead. \$\endgroup\$
    – mbomb007
    Commented Apr 27, 2016 at 20:12
  • 1
    \$\begingroup\$ I'm a bit late to the party, but can someone explain how this works? \$\endgroup\$
    – MadTux
    Commented Oct 12, 2016 at 15:31
  • 10
    \$\begingroup\$ This requires a trailing linefeed to be valid. As it is, the source code doesn't match the output. \$\endgroup\$
    – Dennis
    Commented Jan 5, 2017 at 17:10
33
+500
\$\begingroup\$

Hexagony, 261 bytes, side length 10

113009344778658560261693601386118648881408495353228771273368412312382314076924170567897137624629445942109467..../....%'=g':..\..................\.................\................\...............\..............\.............\............\!$/'?))='%<\..>:;/$;4Q/

Try it online!

Uses the same encoding user202729's answer, but terminates in a divide by zero error.

Formatted, this looks like:

          1 1 3 0 0 9 3 4 4 7
         7 8 6 5 8 5 6 0 2 6 1
        6 9 3 6 0 1 3 8 6 1 1 8
       6 4 8 8 8 1 4 0 8 4 9 5 3
      5 3 2 2 8 7 7 1 2 7 3 3 6 8
     4 1 2 3 1 2 3 8 2 3 1 4 0 7 6
    9 2 4 1 7 0 5 6 7 8 9 7 1 3 7 6
   2 4 6 2 9 4 4 5 9 4 2 1 0 9 4 6 7
  . . . . / . . . . % ' = g ' : . . \
 . . . . . . . . . . . . . . . . . . \
  . . . . . . . . . . . . . . . . . \
   . . . . . . . . . . . . . . . . \  
    . . . . . . . . . . . . . . . \   
     . . . . . . . . . . . . . . \    
      . . . . . . . . . . . . . \
       . . . . . . . . . . . . \
        ! $ / ' ? ) ) = ' % < \
         . . > : ; / $ ; 4 Q /
          . . . . . . . . . .

Try it online!

Some python-like psuedo-code to explain:

n = ridiculously long number
base = 103
print(n)
while n > 0:
    b = 2
    if n%b == 1:
        c = '.'
        print(c)
    else:
        n = n//b
        b = base
        c = chr(n%b + 1)
    print(c)
    n = n//b

I'm using base 103 rather than the optimal base 97 just to make sure the number fully fits the top half of the hexagon and doesn't leave an extra . to encode.

Here's a link to user202729's encoder that I used to get the large number and check that the number actually fit in the hexagon.

\$\endgroup\$
3
  • \$\begingroup\$ What a shame this doesn't fit in 108 digits. \$\endgroup\$
    – Maya
    Commented Sep 22, 2019 at 9:51
  • \$\begingroup\$ Another disappointing almost golf is this for 107 digits needing 106 \$\endgroup\$
    – Jo King
    Commented Aug 6, 2020 at 8:43
  • 3
    \$\begingroup\$ 259 bytes, packs ?)) into chr(2), which grants enough space to expand the modulo and use a smaller mod (93), saving a couple bytes in the encoding \$\endgroup\$
    – je je
    Commented Jun 23, 2021 at 6:21
30
\$\begingroup\$

C, 64 60 bytes

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

This may segfault on 64-bit systems with some compilers, such as newest Clang, due to the type of s being interpreted as 32-bit int instead of a pointer.

So far, this is the shortest known C quine. There's an extended bounty if you find a shorter one.

This works in GCC, Clang, and TCC in a POSIX environment. It invokes an excessive amount of undefined behavior with all of them.

Just for fun, here's a repo that contains all the C quines I know of. Feel free to fork/PR if you find or write a different one that adds something new and creative over the existing ones.

Note that it only works in an ASCII environment. This works for EBCDIC, but still requires POSIX. Good luck finding a POSIX/EBCDIC environment anyway :P


How it works:

  1. main(s) abuses main's arguments, declaring a virtually untyped variable s. (Note that s is not actually untyped, but since listed compilers auto-cast it as necessary, it might as well be*.)
  2. printf(s="..." sets s to the provided string and passes the first argument to printf.
  3. s is set to main(s){printf(s=%c%s%1$c,34,s);}.
  4. The %c is set to ASCII 34, ". This makes the quine possible. Now s looks like this:
    main(s){printf(s="%s%1$c,34,s);}.
  5. The %s is set to s itself, which is possible due to #2. Now s looks like this:
    main(s){printf(s="main(s){printf(s=%c%s%1$c,34,s);}%1$c,34,s);}.
  6. The %1$c is set to ASCII 34 ", printf's first** argument. Now s looks like this:
    main(s){printf(s="main(s){printf(s=%c%s%1$c,34,s);}",34,s);}
    ... which just so happens to be the original source code.

* Example thanks to @Pavel
** first argument after the format specifier - in this case, s. It's impossible to reference the format specifier.


I think it's impossible that this will get any shorter with the same approach. If printf's format specifier was accessible via $, this would work for 52 bytes:

main(){printf("main(){printf(%c%0$s%1$c,34);}",34);}

Also here's a longer 64-byte version that will work on all combinations of compilers and ASCII environments that support the POSIX printf $ extension:

*s;main(){printf(s="*s;main(){printf(s=%c%s%1$c,34,s);}",34,s);}
\$\endgroup\$
11
  • 1
    \$\begingroup\$ Although it certainly shouldn't count as competing, the winner of "Worst abuse of the rules" from the 1994 International Obfuscated C Code Contest, 1994_smr.c, is definitely shorter. \$\endgroup\$
    – Ray
    Commented May 31, 2017 at 19:59
  • 1
    \$\begingroup\$ @Ray It's not allowed. It's not a proper quine by any definition. The quien rules were changed because of that program :P \$\endgroup\$
    – MD XF
    Commented May 31, 2017 at 20:00
  • \$\begingroup\$ I agree entirely, but it's an interesting enough hack that it's worth mentioning any time someone mentions a smallest known quine, if only for historical reasons. \$\endgroup\$
    – Ray
    Commented May 31, 2017 at 20:10
  • 4
    \$\begingroup\$ s is of type int, not an "untyped variable". \$\endgroup\$
    – feersum
    Commented Jul 22, 2017 at 5:32
  • 2
    \$\begingroup\$ These compilers all apparently allow implicit conversion of a pointer to an int. s=3 obviously wouldn't work because you need to pass the string twice to printf. \$\endgroup\$
    – feersum
    Commented Jul 22, 2017 at 19:09
29
+600
\$\begingroup\$

Lost, 120 116 98 96 76 70 66 bytes

Edit: yay, under 100

Edit: Saved a bunch o' bytes by switching to all /s on the bottom line

:2+52*95*2+>::1?:[:[[[[@^%?>([ "
////////////////////////////////

Try it online! + verification it's deterministic for all possible states

Lost is a 2D language in which the starting position and direction are completely random. This means there has to be a lot of error-checking at every stage to make sure you've got the correct instruction pointer, and it isn't one that has just wandered in randomly.

Explanation:

All the /s on the bottom line are there to make sure that all the pointers that spawn in a vertical direction or on the bottom line get funneled in the right direction. From there, they end up at several different places, but all of them end up going right into the

 ^%?>
 ////

Which clears out all the non-zero numbers in the stack. The ([ after that clears out any extra 0s as well.

In the middle of the clear, it hits the %, which turns the 'safety' off, which allows the program to end when it hits the @ (without this, the program could end immediately if a pointer started at the @).

From there it does a pretty simple 2D language quine, by wrapping a string literal (") around the first line, pushing a " character by duping a space (:2+) and then a newline (52*). For the second line, it creates a / character (95*2+) and duplicates it a bunch (>::1?:[:[[[[), before finally ending at the @ and printing the stack implicitly. The ?1 is to stop the process from creating too many 0s if the pointer enters early, saving on having to clear them later.

I saved 20 bytes here by making the last line all the same character, meaning I could go straight from the duping process into the ending @.

Explanation about the duping process:

[ is a character known as a 'Door'. If the pointer hits the flat side of a [ or a ] , it reflects, else it passes through it. Each time the pointer interacts with a Door, it switches to the opposite type. Using this knowledge we can construct a simple formula for how many times an instruction will execute in a >:[ block.

Add the initial amount of instructions. For each [, add 2 times the amount of instructions to the left of it. For the example >::::[:[[[, we start with 5 as the initial amount. The first Door has 4 dupe instructions, so we add 4*2=8 to 5 to get 13. The other three Doors have 5 dupes to their left, so we add 3*(5*2)=30 to 13 to get 43 dupe instructions executed, and have 44 >s on the stack. The same process can be applied to other instructions, such as ( to push a large amount of items from the stack to the scope, or as used here, to clear items from the stack.

A trick I've used here to avoid duping too many 0s is the 1?. If the character is 0, the ? doesn't skip the 1, which means it duplicates 1 for the remainder of the dupe. This makes it much easier to clear the stack later on.

\$\endgroup\$
27
\$\begingroup\$

Chicken, 7

chicken

No, this is not directly echoed :)

\$\endgroup\$
6
  • \$\begingroup\$ Damnit, you beat me to it :) \$\endgroup\$
    – Taconut
    Commented Feb 1, 2014 at 22:42
  • \$\begingroup\$ It's not echoed, it's the string chicken! \$\endgroup\$ Commented Jun 28, 2016 at 21:45
  • \$\begingroup\$ No code/data separation, and therefore invalid. \$\endgroup\$ Commented Jan 5, 2017 at 2:25
  • 11
    \$\begingroup\$ @CalculatorFeline Did you read the rules? \$\endgroup\$
    – Timtech
    Commented Jan 5, 2017 at 15:36
  • 1
    \$\begingroup\$ @JoKing I don't think this is invalid, because the rules of the challenge only prohibit zero-length and cheating (reading your own source file) quines. The only thing that prohibits improper quines is a standard loophole -- except standard loopholes aren't generally considered to apply to answers that predate them. \$\endgroup\$ Commented Aug 25, 2019 at 1:36
26
\$\begingroup\$

Cross-browser JavaScript (41 characters)

It works in the top 5 web browsers (IE >= 8, Mozilla Firefox, Google Chrome, Safari, Opera). Enter it into the developer's console in any one of those:

eval(I="'eval(I='+JSON.stringify(I)+')'")

It's not "cheating" — unlike Chris Jester-Young's single-byte quine, as it could easily be modified to use the alert() function (costing 14 characters):

alert(eval(I="'alert(eval(I='+JSON.stringify(I)+'))'"))

Or converted to a bookmarklet (costing 22 characters):

javascript:eval(I="'javascript:eval(I='+JSON.stringify(I)+')'")
\$\endgroup\$
0
26
\$\begingroup\$

Fission, 6 bytes

It appears this is now the shortest "proper" quine among these answers.

'!+OR"

Explanation

Control flow starts at R with a single right-going (1,0) atom. It hits " toggling print mode and then wraps around the line, printing '!+OR before hitting the same " again and exiting print mode.

That leaves the " itself to be printed. The shortest way is '"O (where '" sets the atom's mass to the character code of " and O prints the character and destroys the atom), but if we did this the " would interfere with print mode. So instead we set the atom's value to '! (one less than "), then increment with + and then print the result with O.

Alternatives

Here are a couple of alternatives, which are longer, but maybe their techniques inspire someone to find a shorter version using them (or maybe they'll be more useful in certain generalised quines).

8 bytes using Jump

' |R@JO"

Again, the code starts at R. The @ swaps mass and energy to give (0,1). Therefore the J makes the atom jump over the O straight onto the ". Then, as before, all but the " are printed in string mode. Afterwards, the atom hits | to reverse its direction, and then passes through '"O printing ". The space is a bit annoying, but it seems necessary, because otherwise the ' would make the atom treat the | as a character instead of a mirror.

8 bytes using two atoms

"'L;R@JO

This has two atoms, starting left-going from L and right-going from R. The left-going atom gets its value set by '" which is then immediately printed with O (and the atom destroyed). For the right-going atom, we swap mass and energy again, jump over the O to print the rest of the code in print mode. Afterwards its value is set by 'L but that doesn't matter because the atom is then discarded with ;.

\$\endgroup\$
4
  • \$\begingroup\$ Technically invalid due to lack of code/data separation in the source. \$\endgroup\$ Commented Jan 5, 2017 at 2:24
  • 5
    \$\begingroup\$ @CalculatorFeline '!+ encodes ". \$\endgroup\$ Commented Jan 5, 2017 at 8:51
  • \$\begingroup\$ I'm not familiar with Fission, but would |R@JO"' work, or would you still need that space after the '? \$\endgroup\$ Commented Mar 6, 2017 at 1:34
  • 1
    \$\begingroup\$ @MistahFiggins I think so, but more importantly you'd print the ' first. \$\endgroup\$ Commented Mar 6, 2017 at 7:06
25
\$\begingroup\$

Java, 528 bytes:

A Java solution with an original approach:

import java.math.*;class a{public static void main(String[]a){BigInteger b=new BigInteger("90ygts9hiey66o0uh2kqadro71r14x0ucr5v33k1pe27jqk7mywnd5m54uypfrnt6r8aks1g5e080mua80mgw3bybkp904cxfcf4whcz9ckkecz8kr3huuui5gbr27vpsw9vc0m36tadcg7uxsl8p9hfnphqgksttq1wlolm2c3he9fdd25v0gsqfcx9vl4002dil6a00bh7kqn0301cvq3ghdu7fhwf231r43aes2a6018svioyy0lz1gpm3ma5yrspbh2j85dhwdn5sem4d9nyswvx4wmx25ulwnd3drwatvbn6a4jb000gbh8e2lshp",36);int i=0;for(byte c:b.toByteArray()){if(++i==92)System.out.print(b.toString(36));System.out.print((char)c);}}}

in readable form:

import java.math.*;
class a
{
    public static void main (String [] a)
    {
        BigInteger b=new BigInteger ("90ygts9hiey66o0uh2kqadro71r14x0ucr5v33k1pe27jqk7mywnd5m54uypfrnt6r8aks1g5e080mua80mgw3bybkp904cxfcf4whcz9ckkecz8kr3huuui5gbr27vpsw9vc0m36tadcg7uxsl8p9hfnphqgksttq1wlolm2c3he9fdd25v0gsqfcx9vl4002dil6a00bh7kqn0301cvq3ghdu7fhwf231r43aes2a6018svioyy0lz1gpm3ma5yrspbh2j85dhwdn5sem4d9nyswvx4wmx25ulwnd3drwatvbn6a4jb000gbh8e2lshp", 36); 
        int i=0; 
        for (byte c:b.toByteArray ())
        {
            if (++i==92) 
                System.out.print (b.toString (36)); 
            System.out.print ((char) c);
        }
    }
}
\$\endgroup\$
7
  • \$\begingroup\$ How does it work? \$\endgroup\$
    – xenia
    Commented May 23, 2015 at 13:02
  • 1
    \$\begingroup\$ @Loovjo: Similar as other solutions which cut the code in two parts and inserts the whole String which reprensents the code inside again, but the whole code is not just a String but encoded as the long number in base 36 (26 alphabetical characters + 10 digits). \$\endgroup\$ Commented May 24, 2015 at 9:38
  • 1
    \$\begingroup\$ This could be shortened if you put if(++i==92), \$\endgroup\$
    – tuskiomi
    Commented Jun 12, 2017 at 14:00
  • 2
    \$\begingroup\$ @tuskiomi: Thanks, shortened for two characters \$\endgroup\$ Commented Jun 12, 2017 at 14:20
  • 1
    \$\begingroup\$ @userunknown Actually, a* as array doesn't exit in Java, that's C. Some other parts to golf: import java.math.*;class a{public static void main(String[]a){BigInteger b=new BigInteger("abc",36);int i=0;for(int c:b.toByteArray())System.out.printf("%s%c",++i==92?b.toString(36):"",c);}}, where abc would be the newly computed magic number String. In java 8+ it's also possible to change class a{public static void main to interface a{static void main, and in Java 10+ it's also possible to change import java.math.*; and BigInteger b=new BigInteger( to var b=new java.math.BigInteger(. \$\endgroup\$ Commented Mar 23, 2018 at 13:57
24
\$\begingroup\$

These are the two shortest Ruby quines from SO:

_="_=%p;puts _%%_";puts _%_

and

puts <<2*2,2
puts <<2*2,2
2

Don't ask me how the second works...

\$\endgroup\$
3
  • 9
    \$\begingroup\$ The second one uses heredoc, <<2 starts a string on the next line, and *2 repeats the string \$\endgroup\$
    – Ming-Tang
    Commented Jan 28, 2011 at 2:52
  • \$\begingroup\$ Why do you need the 2? \$\endgroup\$ Commented Mar 7, 2016 at 5:27
  • 1
    \$\begingroup\$ @CalculatorFeline It's the terminator of the heredoc string (which has to appear on its own line). It doesn't actually have to be a 2 though: tio.run/##KypNqvz/v6C0pFjBxsZAy0jHgAuFY8D1/z8A \$\endgroup\$ Commented Mar 2, 2018 at 8:47
23
\$\begingroup\$

Retina, 20 14 9 7 bytes

Before we get started, I'd like to mention the trivial solution of a file which contains a single 0. In that case Retina will try to count the 0s in the empty input, the result of which is also 0. I wouldn't consider that a proper quine though.

So here is a proper one:

>\`
>\`

Try it online!

Alternatively, we could use ; instead of >.

Explanation

The program consists of a single replacement which we print twice.

In the first line, the ` separates the configuration from the regex, so the regex is empty. Therefore the empty string (i.e. the non-existent input) is replaced with the second line, verbatim.

To print the result twice, we wrap it in two output stages. The inner one, \ prints the result with a trailing linefeed, and the outer one, >, prints it without one.

If you're a bit familiar with Retina, you might be wondering what happened to Retina's implicit output. Retina's implicit output works by wrapping the final stage of a program in an output stage. However, Retina doesn't do this, if the final stage is already an output stage. The reason for that is that in a normal program it's more useful to be able to replace the implicit output stage with special one like \ or ; for a single byte (instead of having to get rid of the implicit one with the . flag as well). Unfortunately, this behaviour ends up costing us two bytes for the quine.

\$\endgroup\$
0
23
\$\begingroup\$

Amazon Alexa, 31 words

Alexa, Simon Says Alexa, Simon Says
Alexa, Repeat That
Alexa, Simon Says Alexa, Repeat That Alexa, Simon Says, Alexa, Repeat That Alexa, Simon Says
Alexa, Repeat That
Alexa, Simon Says quiet

(each command is on a newline)

When said out loud to a device with the Amazon Alexa digital assistant enabled (I've only tested this on the Echo Dot though), it should say the same words back to you. There will be some different lengths of pauses between words, as you wait for Alexa to reply, and it says everything without breaks, but the sequence of words are the same.

Explanation:

Each line is a new Alexa command, one of either:

  • Alexa, Simon Says ..., which will prompt Alexa to say everything afterward the command
  • Alexa, Repeat That, which repeats the last thing Alexa said

(neither of these appear on most lists of Alexa commands, so I hope someone has actually learned something from this)

We can simplify this to the commands S and R respectively, separated by spaces. For example, SR will represent Alexa, Simon Says Alexa, Repeat That. The translation of our program would be:

SS R SRSRS R SQ

Where Q is quiet (but can be anything. I chose quiet because that's what Alexa produced when I tried to give it quine, and it fit, so I kept it). Step by step, we can map each command to the output of each command:

Commands: SS
Output:   S
Commands: SS R
Output:   S  S
Commands: SS R SRSRS
Output:   S  S RSRS
Commands: SS R SRSRS R
Output:   S  S RSRS  RSRS
Commands: SS R SRSRS R    SQ
Output:   S  S RSRS  RSRS Q
Total Commands: SSRSRSRSRSQ
Total Output:   SSRSRSRSRSQ

The general approach for this was to get the output ahead of the input commands. This happens on the second to last command, which gets an extra S command. First we have to get behind on output though. The first two commands SS R only produce SS, leaving us to make up the R. However, this allows us to start a S command with an R, which means we can repeat a section (RSRS) multiple times, which allows us to get the spare S leftover. After that, all we had to do was use it to say whatever we wanted.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Can Alexa do addition and primality checks? If so, then Alexa is a programming language according to PPCG \$\endgroup\$
    – MilkyWay90
    Commented Mar 26, 2019 at 0:27
  • 2
    \$\begingroup\$ @MilkyWay90 Yes, Alexa can do both those things, but I still hesitate to call it a programming language since those are both "built-ins", and Alexa is incapable of basic data storage and input. \$\endgroup\$
    – Jo King
    Commented Apr 15, 2019 at 5:49
  • 2
    \$\begingroup\$ This is really a nice idea, but i don't think that it would be a valid quine if it is a valid programming language. In a valid quine, the spaces (or pauses) must also be the same, so if you had a second Alexa which only hears the output of the first Alexa, it should say the same as the first Alexa for a valid quine. The different pauses lead to different commands. You enter S("S"); R(); S("RSRS"); R(); S(); and you get S(); S(); R("SRS"); R("SRS"); \$\endgroup\$
    – Dorian
    Commented Jun 3, 2019 at 11:00
  • \$\begingroup\$ I disagree. Each line of a quine isn't required to output itself. In an arbitrary scripting language, A\nB\n would be a valid quine even if A output nothing then B output A\nB\n. most multi-instruction quines don't output anything until the last line [of each loop]. \$\endgroup\$
    – Sparr
    Commented Sep 24, 2019 at 18:49
22
\$\begingroup\$

GolfScript, 8 bytes

I always thought the shortest (true) GolfScript quine was 9 bytes:

{'.~'}.~

Where the trailing linefeed is necessary because GolfScript prints a trailing linefeed by default.

But I just found an 8-byte quine, which works exactly around that linefeed restriction:

":n`":n`

Try it online!

So the catch is that GolfScript doesn't print a trailing linefeed, but it prints the contents of n at the end of the program. It's just that n contains a linefeed to begin with. So the idea is to replace that with the string ":n`", and then stringifying it, such that the copy on the stack prints with quotes and copy stored in n prints without.

As pointed out by Thomas Kwa, the 7-byte CJam quine can also be adapted to an 8-byte solution:

".p"
.p

Again, we need the trailing linefeed.

\$\endgroup\$
1
  • 7
    \$\begingroup\$ Golfscript is weird. \$\endgroup\$ Commented Mar 23, 2016 at 4:27
22
\$\begingroup\$

Fueue, 423 bytes

Fueue is a queue-based esolang in which the running program is the queue.

)$$4255%%1(~):[)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]](H-):~:[)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:](106328966328112328136317639696111819119696281563139628116326221310190661962811611211962861109696289611619628116111612896281115421063633063961111116163963011632811111819159628151213262722151522061361613096119619190661966311961128966130281807072220060611612811961019070723232022060611

Try it online!

How it works

This explanation may or may not have got way out of hand. On the other hand I don't know how to explain it much shorter in a way I hope people can follow.

Fueue cheat sheet

See esolang wiki article for details, including the few features not used in this program.

  • The initial program is the initial state of the queue, which can contain the following elements:

    • Integer literals (only non-negative in the source, but negative ones can be calculated), executing them prints a character.
    • Square-bracket delimited nested blocks, inert (preserved intact unless some function acts upon them).
    • Functions, their arguments are the elements following them immediately in the queue:
      • +*/-%: integer arithmetic (- is unary, % logical negation). Inert if not given number arguments.
      • ()<: put element in brackets, remove brackets from block, add final element to block. The latter two are inert unless followed by a block.
      • ~:: swap, duplicate.
      • $: copy (takes number + element). Inert before non-number.
      • H: halt program.

    Note that while [] nest, () don't - the latter are simply separate functions.

Execution trace syntax

Whitespace is optional in Fueue, except between numerals. In the following execution traces it will be used to suggest program structure, in particular:

  • When a function executes, it and its arguments will be set off from the surrounding elements with spaces. If some of the arguments are complicated, there may be a space between them as well.
  • Many execution traces are divided into a "delay blob" on the left, separated from a part to the right that does the substantial data manipulation. See next section.

Curly brackets {} (not used in Fueue) are used in the traces to represent the integer result of mathematical expressions. This includes negative numbers, as Fueue has only non-negative literals – - is the negation function.

Various metavariable names and ... are used to denote values and abbreviations.

Delaying tactics

Intuitively, execution cycles around the queue, partially modifying what it passes through. The results of a function cannot be acted on again until the next cycle. Different parts of the program effectively evolve in parallel as long as they don't interact.

As a result, a lot of the code is devoted to synchronization, in particular to delaying execution of parts of the program until the right time. There are a lot of options for golfing this, which tends to turn those parts into unreadable blobs that can only be understood by tracing their execution cycle by cycle.

These tactics won't always be individually mentioned in the below:

  • )[A] delays A for a cycle. (Probably the easiest and most readable method.)
  • ~ef swaps the elements e and f which also delays their execution. (Probably the least readable, but often shortest for minor delays.)
  • $1e delays a single element e.
  • - and % are useful for delaying numbers (the latter for 0 and 1.)
  • When delaying several equal elements in a row, : or $ can be used to create them from a single one.
  • (n wraps n in brackets, which may later be removed at convenience. This is particularly vital for numeric calculations, since numbers are too unstable to even be copied without first putting them in a block.

Overall structure

The rest of the explanation is divided into seven parts, each for a section of the running program. The larger cycles after which most of them repeat themselves will be called "iterations" to distinguish them from the "cycles" of single passes through the entire queue.

Here is how the initial program is divided between them:

A:  )$$4255%%1(~
B:  ):[)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]
C:  
D:  (H-
E:  
F:  
G:  ):~:[)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:](106328966328112328136317639696111819119696281563139628116326221310190661962811611211962861109696289611619628116111612896281115421063633063961111116163963011632811111819159628151213262722151522061361613096119619190661966311961128966130281807072220060611612811961019070723232022060611

The big numeral at the end of the program encodes the rest in reverse, two digits per character, with 30 subtracted from each ASCII value (so e.g. 10 encodes a (.)

On a higher level you can think of the data in this program (starting with the bignum) as flowing from right to left, but control flowing from left to right. However, at a lower level Fueue muddles the distinction between code and data all the time.

  • Section G decodes the bignum into ASCII digits (e.g. digit 0 as the integer 48), splitting off the least significant digits first. It produces one digit every 15 cycles.
  • Section F contains the produced digit ASCII values (each inside a block) until section E can consume them.
  • Section E handles the produced digits two at a time, pairing them up into blocks of the form [x[y]], also printing the encoded character of each pair.
  • Section D consists of a deeply nested block gradually constructed from the [x[y]] blocks in such a way that once it contains all digits, it can be run to print all of them, then halt the entire program.
  • Section C handles the construction of section D, and also recreates section E.
  • Section B recreates section C as well as itself every 30 cycles.
  • Section A counts down cycles until the last iteration of the other sections. Then it aborts section B and runs section D.

Section A

Section A handles scheduling the end of the program. It takes 4258 cycles to reduce to a single swap function ~, which then makes an adjustment to section B that stops its main loop and starts running section D instead.

)$ $4255% %1 (~
)$%%%...%% %0 [~]
)$%%%...% %1 [~]
⋮
)$ %0 [~]
) $1[~]
)[~]
~
  • A $ function creates 4255 copies of the following % while the ( wraps the ~ in brackets.
  • Each cycle the last % is used up to toggle the following number between 0 and 1.
  • When all %s are used up, the $1 creates 1 copy of the [~] (effectively a NOP), and on the next cycle the ) removes the brackets.

Section B

Section B handles regenerating itself as well as a new iteration of section C every 30 cycles.

) : [)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]
) [)$$24%%0:<[~:)~)]~[$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]            [BkB]
)$ $24%     %0  :<  [~:)~)]    ~ [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<] [BkB]
)$ %...%%% %1   < < [~:)~)] [BkB]   [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]
)$ %...%% %0      < [~:)~)[BkB]] [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]
)$ %...% %1         [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]
⋮
) $1 [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]
) [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]                    (1)
~:) ~)[BkB]                 [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]
) : [BkB]                 ) [$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]      (2)
) [BkB] [BkB]               $11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<
  • A : duplicates the big block following (one copy abbreviated as [BkB]), then ) removes the brackets from the first copy.
  • $$24%%0 sets up a countdown similar to the one in section A.
  • While this counts down, :< turns into <<, and a ~ swaps two of the blocks, placing the code for a new section C last.
  • The two < functions pack the two final blocks into the first one - this is redundant in normal iterations, but will allow the ~ from section A to do its job at the end.
  • (1) When the countdown is finished, the ) removes the outer brackets. Next ~:) turns into ): and ~) swaps a ) to the beginning of the section C code.
  • (2) Section B is now back at its initial cycle, while a ) is just about to remove the brackets to start running a new iteration of section C.

In the final iteration, the ~ from section A appears at point (1) above:

~ ) [~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]                  (1)
[~:)~)[BkB][$11~)~<[[+$4--498+*-:~-10)):])<~][)))~]<]]              )

The ~ swaps the ) across the block and into section C, preventing section B from being run again.

Section C

Section C handles merging new digit character pairs into section D's block, and also creating new iterations of section E.

The below shows a typical iteration with x and y representing the digits' ASCII codes. In the very first iteration, the incoming "D" and "E" elements are the initial [H] and - instead, as no previous section E has run to produce any digit character pairs.

C                                               D             E
$11~ )  ~<[[+$4--498+*-:~-10)):])<~]  [)))~]  < [)))~[...]]   [x[y]]
~~~ ~~~ ~~~ ~~) [[+$4--498+*-:~-10)):])<~]  < [)))~] [)))~[...][x[y]]]
~~~ ~~~     )  ~ [[+$4--498+*-:~-10)):])<~] [)))~[)))~[...][x[y]]]]
~~~       ~ )   [)))~[....]]                                  [[+$4--498+*-:~-10)):])<~]
                                              ~~[)))~[....]] )[[+$4--498+*-:~-10)):])<~]
                                                [)))~[....]]  ~[+$4--498+*-:~-10)):])<~
  • This uses a different method of synchronization which I discovered for this answer. When you have several swap functions ~ in a row, the row will shrink to approximately 2/3 each cycle (because one ~ swaps two following), but occasionally with a remainder of ~s that wreaks havoc on carefully manipulates what follows.
  • $11~ produces such a row. The next ~ swaps a < across the following block. Another < at the end appends a new digit pair block (digits x and y as ASCII codes) into the section D block.
  • Next cycle, the ~ row has a ~~ remainder, which swaps a ~ over the following ). The other < appends section D to a [)))~] block.
  • Next the swapped ~ itself swaps the following block with new section E code across the section D block. Then a new leftover ~ swaps a ) across, and finally the last ~~ in the ~ row swap one of them across to section E just as the ) has removed its brackets.

In the final iteration, section A's ~ has swapped a ) across section B and into section C. However, section C is so short-lived that it already has disappeared, and the ) ends up at the beginning of section D.

Section D

Section D handles printing the final big numeral and halting the program. During most of the program run, it is an inert block that sections B–G cooperate on building.

    (H -
    [H]-
    ⋮
    [)))~[H-]]                  After one iteration of section C
    ⋮
    [)))~[)))~[H-][49[49]]]]    Second iteration, after E has also run
    ⋮
)   [)))~[...]]     [49[48]]    Final printing starts as ) is swapped in
    ))) ~[...][49[48]]
    )) )[49[48]] [...]
    )) 49 [48][...]             Print first 1
    ) )[48] [...]
    ) 48 [...]                  Print 0
    )[...]                      Recurse to inner block
    ...
    ⋮
    )[H-]                       Innermost block reached
    H -                         Program halts
  • In the first cycle of the program, a ( wraps the halting function H in brackets. A - follows, it will be used as a dummy element for the first iteration instead of a digit pair.
  • The first real digit pair incorporated is [49[49]], corresponding to the final 11 in the numeral.
  • The very last digit pair [49[48]] (corresponding to the 10 at the beginning of the numeral) is not actually incorporated into the block, but this makes no difference as )[A[B]] and )[A][B] are equivalent, both turning into A[B].

After the final iteration, the ) swapped rightwards from section B arrives and the section D block is deblocked. The )))~ at the beginning of each sub-block makes sure that all parts are executed in the right order. Finally the innermost block contains an H halting the program.

Section E

Section E handles combining pairs of ASCII digits produced by section G, and both prints the corresponding encoded character and sends a block with the combined pair leftwards to sections C and D.

Again the below shows a typical iteration with x and y representing the digits' ASCII codes.

E                                                   F
~ [+$4--498+*-:~-10)):] )              <  ~         [y] [x]
) [+$4--498+*-:~-10)):]                   < [x] [y]
+ $4-  - 498  +*- :~ -10 ) )              : [x[y]]
+---  -{-498} +*- ~~{-10} )       ) [x[y]]  [x[y]]
+--    - 498  +*   -{-10}       ~ ) x  [y]  [x[y]]
+-    -{-498} +               * 10 x  )[y]  [x[y]]
+      - 498                    + {10*x} y  [x[y]]
                         + {-498} {10*x+y}  [x[y]]
{10*x+y-498}  [x[y]]
[x[y]]
  • The incoming digit blocks are swapped, then the y block is appended to the x block, and the whole pair block is copied. One copy will be left until the end for sections C and D.
  • The other copy is deblocked again, then a sequence of arithmetic functions are applied to calculate 10*x+y-498, the ASCII value of the encoded character. 498 = 10*48+48-30, the 48s undo the ASCII encoding of x and y while the 30 shifts the encoding from 00–99 to 30–129, which includes all printable ASCII.
  • The resulting number is then left to execute, which prints its character.

Section F

Section F consists of inert blocks containing ASCII codes of digits. For most of the program run there will be at most two here, since section E consumes them at the same speed that G produces them with. However, in the final printing phase some redundant 0 digits will collect here.

[y] [x] ...

Section G

Section G handles splitting up the big number at the end of the program, least significant digits first, and sending blocks with their ASCII codes leftward to the other sections.

As it has no halting check, it will actually continue producing 0 digits when the number has whittled down to 0, until section D halts the entire program with the H function.

[BkG] abbreviates a copy of the big starting code block, which is used for self-replication to start new iterations.

Initialization in the first cycles:

) :~  : [)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:]  ( 106328966328112328136317639696111819119696281563139628116326221310190661962811611211962861109696289611619628116111612896281115421063633063961111116163963011632811111819159628151213262722151522061361613096119619190661966311961128966130281807072220060611612811961019070723232022060611
)  ~ ~ [)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:]  [BkG] [10...11]
) [)[):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]~:]     ~ [BkG] [10...11]
) [):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]       ~ : [10...11]  [BkG]

Typical iteration, N denotes the number to split:

) [):~[)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+:5):]        ~ : [N]  [BkG]
) :~ [)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]+ :5 )         : [N]  : [BkG]
)  ~ ~ [)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]  +5 5     ) [N]  [N] [BkG] [BkG]
) [)~:~~([:~)*[):~[$1(+48]):~+]-:~~)10)~~]/]               ~ 10 N  [N] [BkG] [BkG]
) ~:~  ~ ( [:~)*[):~[$1(+48]):~+]-:~~)10)~~]               / N 10  [N] [BkG] [BkG]
)  ~ : [:~)*[):~[$1(+48]):~+]-:~~)10)~~]                 ( {N/10}  [N] [BkG] [BkG]
) [:~)*[):~[$1(+48]):~+]-:~~)10)~~]                    : [{N/10}]  [N] [BkG] [BkG]
:~ )*[):~[$1(+48]):~+]- :~ ~)10 )           ~ ~ [{N/10}]  [{N/10}] [N] [BkG] [BkG]
~~) *[):~[$1(+48]):~+]- ~~10 )             ) [{N/10}]  ~ [{N/10}] [N]  [BkG] [BkG]
)  ~ * [):~[$1(+48]):~+]  -10            ~ ) {N/10}  [N] [{N/10}] [BkG] [BkG]
) [):~[$1(+48]):~+]               * {-10} {N/10}  ) [N]  [{N/10}] [BkG] [BkG]
) :~ [$1(+48]) :~                 + {-10*(N/10)} N  [{N/10}] [BkG] [BkG]
)  ~ ~ [$1(+48]  )                 ~ ~ {N%10}  [{N/10}] [BkG] [BkG]
) [$1(+48]                 ~ ) {N%10}  ~ [{N/10}] [BkG]  [BkG]
$1(                     + 48 {N%10}    ) [BkG]  [{N/10}] [BkG]
                        ( {48+N%10}   BkG [{N/10}] [BkG]            New iteration starts
                        [{48+N%10}]   ....
  • The delay blob here is particularly hairy. However, the only new delaying trick is to use +:5 instead of --10 to delay a 10 two cycles. Alas only one of the 10s in the program was helped by this.
  • The [N] and [BkG] blocks are duplicated, then one copy of N is divided by 10.
  • [{N/10}] is duplicated, then more arithmetic functions are used to calculate the ASCII code of the last digit of N as 48+((-10)*(N/10)+N). The block with this ASCII code is left for section F.
  • The other copy of [{N/10}] gets swapped between the [BkG] blocks to set up the start of a new iteration.

Bonus quine (540 bytes)

)$$3371%%1[~!~~!)!]):[)$$20%%0[):]~)~~[)$$12%%0[<$$7%~~0):~[+----48+*-~~10))]<]<~!:~)~~[40~[:~))~:~[)~(~~/[+--48):]~10]+30])):]]][)[H]](11(06(06(21(21(25(19(07(07(19(61(96(03(96(96(03(11(03(63(11(28(61(11(06(06(20(18(07(07(18(61(11(28(63(96(11(96(96(61(11(06(06(19(20(07(07(18(61(30(06(06(25(07(96(96(18(11(28(96(61(13(15(15(15(15(22(26(13(12(15(96(96(19(18(11(11(63(30(63(30(96(03(28(96(11(96(96(61(22(18(96(61(28(96(11(11(96(28(96(61(11(96(10(96(96(17(61(13(15(15(22(26(11(28(63(96(19(18(63(13(21(18(63(11(11(28(63(63(63(61(11(61(42(63(63

Try it online!

Since I wasn't sure which method would be shortest, I first tried encoding characters as two-digit numbers separated by (s. The core code is a bit shorter, but the 50% larger data representation makes up for it. Not as golfed as the other one, as I stopped when I realized it wouldn't beat it. It has one advantage: It doesn't require an implementation with bignum support.

Its overall structure is somewhat similar to the main one. Section G is missing since the data representation fills in section F directly. However, section E must do a similar divmod calculation to reconstruct the digits of the two-digit numbers.

\$\endgroup\$
2
  • 3
    \$\begingroup\$ You should golf the explanation XD \$\endgroup\$
    – Luvexina
    Commented May 24, 2019 at 19:03
  • 2
    \$\begingroup\$ )$n[)]( is a byte shorter for the delay counter. \$\endgroup\$
    – jimmy23013
    Commented May 25, 2019 at 7:36
21
\$\begingroup\$

Javascript (36 char)

(function a(){alert("("+a+")()")})()

This is, AFAICT, the shortest javascript quine posted so far.

\$\endgroup\$
14
  • 1
    \$\begingroup\$ That... is impressive. You should explain how it works for me 8-| \$\endgroup\$
    – TehShrike
    Commented Sep 27, 2011 at 19:18
  • 3
    \$\begingroup\$ @TehShrike Hint: you can view the contents a function by coercing it to a string. For example, if you have a function a, you can access its contents by calling a.toString. \$\endgroup\$ Commented Sep 27, 2011 at 19:22
  • 7
    \$\begingroup\$ To be pedantic, though, this is only a quine if your JavaScript implementation stringifies the function a exactly the same way as it's been written above. However, the output of this code is likely to be a quine on any JavaScript implementation. \$\endgroup\$ Commented Feb 3, 2012 at 18:55
  • 1
    \$\begingroup\$ Here is the same quine, 1 byte shorter: !function a(){alert("!"+a+"()")}(). \$\endgroup\$ Commented Feb 27, 2015 at 1:22
  • 1
    \$\begingroup\$ (a=()=>alert((${a})))() \$\endgroup\$
    – Dennis C
    Commented May 22, 2017 at 5:40
21
\$\begingroup\$

Labyrinth, 124 110 53 bytes

Thanks to Sp3000 for golfing off 9 bytes, which allowed me to golf off another 7.

44660535853919556129637653276602333!
1
:_98
/8 %
@9_.

Try it online!

Explanation

Labyrinth 101:

  • Labyrinth is a stack-based 2D language. The stack is bottomless and filled with zeroes, so popping from an empty stack is not an error.
  • Execution starts from the first valid character (here the top left). At each junction, where there are two or more possible paths for the instruction pointer (IP) to take, the top of the stack is checked to determine where to go next. Negative is turn left, zero is go forward and positive is turn right.
  • Digits in the source code don't push the corresponding number – instead, they pop the top of the stack and push n*10 + <digit>. This allows the easy building up of large numbers. To start a new number, use _, which pushes zero.
  • " are no-ops.

First, I'll explain a slightly simpler version that is a byte longer, but a bit less magical:

395852936437949826992796242020587432!
"
:_96
/6 %
@9_.

Try it online!

The main idea is to encode the main body of the source in a single number, using some large base. That number can then itself easily be printed back before it's decoded to print the remainder of the source code. The decoding is simply the repeated application of divmod base, where print the mod and continue working with the div until its zero.

By avoiding {}, the highest character code we'll need is _ (95) such that base 96 is sufficient (by keeping the base low, the number at the beginning is shorter). So what we want to encode is this:

!
"
:_96
/6 %
@9_.

Turning those characters into their code points and treating the result as a base-96 number (with the least-significant digit corresponding to ! and the most-significant one to ., because that's the order in which we'll disassemble the number), we get

234785020242697299628949734639258593

Now the code starts with a pretty cool trick (if I may say so) that allows us to print back the encoding and keep another copy for decoding with very little overhead: we put the number into the code in reverse. I computed the result with this CJam script So let's move on to the actual code. Here's the start:

395852936437949826992796242020587432!
"

The IP starts in the top left corner, going east. While it runs over those digits, it simply builds up that number on top of the stack. The number itself is entirely meaningless, because it's the reverse of what we want. When the IP hits the !, that pops this number from the stack and prints it. That's all there is to reproducing the encoding in the output.

But now the IP has hit a dead end. That means it turns around and now moves back west (without executing ! again). This time, conveniently, the IP reads the number from back to front, so that now the number on top of the stack does encode the remainder of the source.

When the IP now hits the top left corner again, this is not a dead end because the IP can take a left turn, so it does and now moves south. The " is a no-op, that we need here to separate the number from the code's main loop. Speaking of which:

...
"
:_96
/6 %
@9_.

As long as the top of the stack is not zero yet, the IP will run through this rather dense code in the following loop:

"
>>>v
^< v
 ^<<

Or laid out linearly:

:_96%._96/

The reason it takes those turns is because of Labyrinth's control flow semantics. When there are at least three neighbours to the current cell, the IP will turn left on a negative stack value, go ahead on a zero and turn right on a positive stack value. If the chosen direction is not possible because there's a wall, the IP will take the opposite direction instead (which is why there are two left turns in the code although the top of the stack is never negative).

The loop code itself is actually pretty straightforward (compressing it this tightly wasn't and is where Sp3000's main contribution is):

:    # Duplicate the remaining encoding number N.
_96  # Push 96, the base.
%.   # Take modulo and print as a character.
_96  # Push 96 again.
/    # Divide N by 96 to move to the next digit.

Once N hits zero, control flow changes. Now the IP would like to move straight ahead after the / (i.e. west), but there's a wall there. So instead if turns around (east), executes the 6 again. That makes the top of the stack positive, so the IP turns right (south) and executes the 9. The top of the stack is now 69, but all we care about is that it's positive. The IP takes another right turn (west) and moves onto the @ which terminates the code.

All in all, pretty simple actually.

Okay, now how do we shave off that additional byte. Clearly, that no-op seems wasteful, but we need that additional row: if the loop was adjacent to the number, the IP would already move there immediately instead of traversing the entire number. So can we do something useful with that no-op.

Well, in principle we can use that to add the last digit onto the encoding. The encoding doesn't really need to be all on the first line... the ! just ensures that whatever is there also gets printed there.

There is a catch though, we can't just do this:

95852936437949826992796242020587432!
3
:_96
/6 %
@9_.

The problem is that now we've changed the " to a 3, which also changes the actual number we want to have. And sure enough that number doesn't end in 3. Since the number is completely determined by the code starting from ! we can't do a lot about that.

But maybe we can choose another digit? We don't really care whether there's a 3 in that spot as long as we end up with a number that correctly encodes the source. Well, unfortunately, none of the 10 digits yields an encoding whose least-significant digit matches the chosen one. Luckily, there's some leeway in the remainder of the code such that we can try a few more encodings without increasing the byte count. I've found three options:

  1. We can change @ to /. In that case we can use any digit from 1357 and get a matching encoding. However, this would mean that the program then terminates with an error, which is allowed but doesn't seem very clean.
  2. Spaces aren't the only "wall" characters. Every unused character is, notably all letters. If we use an upper case letter, then we don't even need to increase the base to accommodate it (since those code points are below _). 26 choices gives plenty of possibilities. E.g. for A any odd digit works. This is a bit nicer, but it still doesn't seem all that elegant, since you'd never use a letter there in real code.
  3. We can use a greater base. As long as we don't increase the base significantly, the number of decimal digits in the encoding will remain the same (specifically, any base up to 104 is fine, although bases beyond 99 would actually require additional characters in the code itself). Luckily, base 98 gives a single matching solution: when we use the digit 1, the encoding also ends in 1. This is the only solution among bases 96, 97, 98, 99, so this is indeed very lucky. And that's how we end up with the code at the top of this answer.
\$\endgroup\$
21
\$\begingroup\$

Lost, 293 262 249 bytes

>:2+52*:6*:(84*+75*):>:::::[[[[[[[:[(52*)>::::[[[[[[:[84*+@>%?!<((((((((((([[[[[[[[[[[[[[ "
\#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\

Try it online!

Explanation

This entire project has been an up and down. I kept thinking it was impossible and then coming up with a crazy idea that just might work.

Why is a Lost Quine so hard?

As you may know Lost is a 2D programming language where the start location and direction are entirely random. This makes writing any lost program about as difficult as writing radiation hardened code. You have to consider every possible location and direction.

That being said there are some standard ways to do things. For example here is the standard way of printing a string.

>%?"Stringv"(@
^<<<<<<<<<<<<<

This has a collection stream at the bottom that grabs the most of the ips and pulls them to the start location. Once they reach are start location (upper left) we sanitize them with a loop getting rid of all the values on the stack then turn the safety of push the string and exit. (safety is a concept unique to Lost every program must hit a % before exiting, this prevents the possibility of the program terminating upon start). Now my idea would be to extend this form into a full fledged quine.

The first thing that had to be done was to rework the loop a bit, the existing loop was specific to the String format.

>%?!<"Stringv"(@
^<<<<<<<<<<<<<<<
^<<<<<<<<<<<<<<<

We need to add a second stream to avoid the possibility of the ! jumping over the stream and creating a loop.

Now we want to mix this with the standard Quine format. Since Lost is based very much on Klein I've basically stolen borrowed the Klien Quine for Martin Ender.

:2+@>%?!< "
<<<<^<<<<<<
<<<<^<<<<<<

This quite conveniently prints the first line of the quine. Now all we need to do is hard-code the streams. Well this is easier said than done. I tried approximately four different methods of doing this. I'll just describe the one that worked.

The idea here is to use doors to get the desired number of arrows. A Door is a special type of mirror that changes every time it is hit. [ reflects ips coming from the left and ] from the right. When they are hit by an ip from either of these sides the switch orientation. We can make a line of these doors and a static reflector to repeatedly perform an operation.

>:[[[

Will perform : three times. This way if we push a < to the stack before hand we can make a lot of them with less bytes. We make 2 of these, one for each line, and in between them we lay down a newline, however the second one needs only go until it covers the ! we added it for, anything else can be left empty saving us a few bytes. Ok now we need to add the vertical arrows to our streams. This is where the key optimization comes in. Instead of redirecting all the ips to the "start" of the program directly we will instead redirect them to the far left, because we already know that the ips starting in far left must work (or at least will work in the final version) we can also just redirect the other ips. This not only makes it cheaper in bytes, I think this optimization is what makes the quine possible.

However there are still some problems, the most important one being ips starting after the > has been pushed but before we start making copies of it. Such ips will enter the copier and make a bunch of copies of 0. This is bad because our stack clearing mechanism uses zeros to determine the bottom of the stack, leaving a whole bunch of zeros at the bottom. We need to add a stronger stack sanitation method. Since there is no real way of telling if the stack is empty, we will simply have to attempt to destroy as many items on the stack as possible. Here we will once again use the door method described earlier. We will add ((((((((((([[[[[[[[[[[[[[ to the end of the first line right after the sanitizor to get rid of the zeros.

Now there is one more problem, since we redirected our streams to the upper left ips starting at the % and moving down will already have turned the safety off and will exit prematurely. So we need to turn the safety off. We do this by adding a # to the stream, that way ips flowing through the stream will be turned off but ips that have already been sanitized will not. The # must also be hard coded into the first line as well.

That's it, hopefully you understand how this works now.

\$\endgroup\$
1
  • \$\begingroup\$ :/ so many typos and missing links \$\endgroup\$
    – ASCII-only
    Commented Aug 22, 2017 at 7:28
1
2 3 4 5
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.