245
\$\begingroup\$

Using your language of choice, golf a quine.

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

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

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

Points for:

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

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

var QUESTION_ID=69;
var OVERRIDE_USER=98;

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

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

455 Answers 455

1
4 5
6
7 8
16
5
\$\begingroup\$

C++, 117 bytes

#include<cstdio>
#define Q(S)char*q=#S;S
Q(int main(){printf("#include<cstdio>\n#define Q(S)char*q=#S;S\nQ(%s)",q);})

Try it online!

\$\endgroup\$
5
  • 1
    \$\begingroup\$ What compiler does this use? This does not appear to work on gcc. \$\endgroup\$
    – Wheat Wizard
    Jan 13, 2017 at 15:26
  • \$\begingroup\$ It works on my gcc 4.9.2. \$\endgroup\$ Jan 13, 2017 at 15:38
  • 2
    \$\begingroup\$ Ok. According to clang, this is not valid C++, since the return type of main() is missing. I fixed that now. \$\endgroup\$ Jan 13, 2017 at 15:40
  • \$\begingroup\$ My version of gcc was 4.2.1 (I should update some time). Now that main has a return type it works. \$\endgroup\$
    – Wheat Wizard
    Jan 13, 2017 at 15:47
  • \$\begingroup\$ Suggest using auto q to make it standards compliant \$\endgroup\$
    – c--
    Jun 6, 2022 at 17:26
5
\$\begingroup\$

PHP -r, 32 bytes

Saved 3 bytes thanks to Sisyphus' insight!

The content of this quine is mostly unprintable characters using the stringwise NOT operator so the test link is to Bash to rebuild the file from an xxd hexdump.

eval(~$_=.....................);

Try it online!

Explanation

In PHP it's possible to use the ~ operator to 'flip' all the bits in a byte to return a string that doesn't look anything like the original string, which works around the problem of having to encode, and then decode, things like quotes. This means it's possible to just call echo on the result.

Visual example of how ~ 'flips' the values.

This was built using the following approach:

$quine =
    // plain beginning 
    "eval(~\$_=".
    // flipped code with $_ interpolated
    ~'echo"eval(~\$_=$_);";' .
    // plain end
    ");"
;

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 32 bytes - Try it online! \$\endgroup\$
    – Sisyphus
    Feb 5, 2021 at 0:21
  • \$\begingroup\$ @Sisyphus Of course! I'll update this later. Thank you! It's quite a competitive quine now! \$\endgroup\$ Feb 5, 2021 at 7:19
5
\$\begingroup\$

Red, 21 bytes

do s: "prin{do }?? s"

Try it online!

Explanation

?? is usually used when debugging, but it's also great for quines. Take the following code:

s: "foo"
?? s

It outputs s: "foo". Let's see what happens when we combine this with a do:

do s: "?? s"

As expected, we get s: "?? s". Ignoring the do, it's pretty much already a quine. We can easily fix this by adding a prin{do } before the ?? s:

do s: "prin{do }?? s"
\$\endgroup\$
0
5
\$\begingroup\$

Knight, 22 bytes

E=s"O+'E=s'++A34sA34"

Includes trailing newline. Try it online!

Finally figured out how to do an EVAL quine, after definitely not adapting the Ruby quine example on Wikipedia.

It is pretty standard. Create a string containing code to print itself, and eval it. A34 is used to generate a double quote.

I am keeping my original idea here as well.


Knight, no eval, 56 45 bytes

O S S=p"O S S=p7F=qA34 7F+q p"7F=qA34 7F+q p

Try it online!

Updated for the new ASCII function.

Includes trailing newline.

Removing the quine string and expanding the keywords/variable names, this is basically the printf quine:

OUTPUT
  : SUBSTITUTE(
        # insert closing quote for quine_str
     : SUBSTITUTE(
        : (= quine_str "...")
        : 7
        : 0 # we use FALSE to save a space
        : (= quote ASCII(34))
     )
    # insert opening quote + quine string
    : 7
    : 0
    : (+ quote quine_str)
: )
\$\endgroup\$
5
\$\begingroup\$

Vyxal D, 12 bytes

`q\`:Ė\`+`:Ė

Try it Online!

What differences this from the other quine is an eval quine so is easily payload-capable - that is, all the processing code you need can go after the + and only needs to be iterated once.

Will be 9 bytes once parsing bugs get fixed.

`        `   # String of code to be executed
 q           # Quotify / uneval
  \`:Ė\`+    # Append a `:Ė`
          :  # Duplicate
           Ė # Run on itself
\$\endgroup\$
5
\$\begingroup\$

K (oK), 9 bytes

`0:"`0:"

Try it online!

Posted with permission from @Bubbler.

So, oK has this cursed bug feature where prettyprinting of the output still occurs even if you print something else. `0 is the output symbol, and calling print to it with : prints the string, but returns the string as well, which is implicitly prettyprinted, with quotes to show it's a string.

K (oK), 34 bytes

{a:"0x7b613a22,a,0x223b2e617d";.a}

Try it online!

My attempt.

In K, hexadecimal literals represent byte values. 0x7b613a22 is {a:", and 0x223b2e617d is ";.a}, both of which are added to the string. So we set the value a to a string that when evaluated, returns itself wrapped in the boilerplate, and evaluate it.

\$\endgroup\$
7
  • \$\begingroup\$ How is this not cheating? \$\endgroup\$
    – pxeger
    Oct 30, 2021 at 10:25
  • \$\begingroup\$ @pxeger All these seem to be valid... \$\endgroup\$
    – emanresu A
    Oct 30, 2021 at 12:00
  • \$\begingroup\$ All of those are invalid too IMO. Why are they accepted? \$\endgroup\$
    – pxeger
    Oct 30, 2021 at 13:30
  • \$\begingroup\$ Technically, it's not reading it's own file in any way - it's using a feature of the language to stringify a function, which happens to produce its source code, like the Befunge-93 quine. \$\endgroup\$
    – emanresu A
    Oct 30, 2021 at 19:41
  • 1
    \$\begingroup\$ @pxeger Fine, I'll add in a proper quine. Gimme a bit of time to make it work \$\endgroup\$
    – emanresu A
    Oct 31, 2021 at 8:00
5
\$\begingroup\$

Vyxal 2.6.0, 4 bytes

`I`I

Try it Online!

Posting this as a separate answer because it's using overloads not available at the time of the other answer.

Explained

`I`I
`I`   # The string "I"
   I  # prepend a quoted version of that to itself and implicitly print
\$\endgroup\$
3
  • \$\begingroup\$ The code-block in your Vyxal TIO doesn't seem to work. It does see it as 4 bytes and outputs correctly, but the code itself shows as a zero-width space.. Seems there is something wrong in the online compiler. (Your answer looks fine btw.) \$\endgroup\$ Nov 29, 2021 at 10:47
  • \$\begingroup\$ @KevinCruijssen it works perfectly fine on my end. Having said that, it wouldn't surprise me if there are issues with the site...we only launched it yesterday because we finished a language rewrite we've been working on for a few months. Hopefully a PR I'm working on will fix this :p \$\endgroup\$
    – lyxal
    Nov 29, 2021 at 10:53
  • 1
    \$\begingroup\$ Welp, this is what I see on my end (latest Chrome version), with these errors in the browser console, and the &ZeroWidthSpace; when I inspect element. 🤷 \$\endgroup\$ Nov 29, 2021 at 11:40
5
\$\begingroup\$

Insitux, 171 103 85 bytes

(#(join(char-code,34)[%,%(char-code,41)])"(#(join(char-code,34)[%,%(char-code,41)])")

Note: Commas are treated as whitespace.

Try it! (The Insitux REPL replaces commas with spaces, but it still works.)

Explanation:

(
  #(join ;Function to process string
    (char-code 34) ;Join the following with '"'
    [
      % ;String (first half)
      % ;String (second half)
      (char-code 41) ;Code for ')'
    ]
  )
  ;Same as above, but in a string
  "(#(join(char-code,34)[%,%(char-code,41)])"
)
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Feb 22, 2022 at 16:03
5
\$\begingroup\$

Whitespace, 333 330 bytes

   		 	   							 		  	  			   	 	 			    			 	 		 					 		       			 									 			   	   	  	   			 	 		 	  		  			    	 			  	 	 						  		      	   	 	 				 	 		  	 			   	  	 		       	 	  	          
   	     
 
 	
  	
   
    	 

 	
   		

  
 
	 	  	
	 	  
 
	  
 
  	  	 

 	

   
 
		 		  			   
	 		   	     
	   	
  
	

Try it online!
Try the 333B version online!

This is the same code as I posted to "Anarchy golf" ( http://golf.shinh.org/p.rb?Quine )

To be a bit more readable, substitute space,tab,newline to "s","t","n" like below;

sssttstssstttttttsttsstsstttssstststttsssstttststtstttttsttssssssstttstttttttttstttssstssstsstssstttststtstssttsstttsssststttsstststtttttssttsssssstssstststtttststtsststttssstsststtssssssststsstssssssssssnssstsssssnsnstnsstnsssnsssstsnnstnsssttnnssnsntstsstntstssnsntssnsnsstsstsnnstnnsssnsnttsttsstttsssntsttssstsssssntssstnssntn

or disassembled code with my original interpreter/disassembler;

push +2636263872820036273590233982665123397718151559108318308901888(201b)  # 0000: sssttstssstttttttsttsstsstttssstststttsssstttststtstttttsttssssssstttstttttttttstttssstssstsstssstttststtstssttsstttsssststttsstststtttttssttsssssstssstststtttststtsststttssstsststtssssssststsstssssssssssn
push +32(6b)  # 0205: ssstsssssn
dup           # 0215: sns
putc          # 0218: tnss
putc          # 0222: tnss
dup           # 0226: sns
push +2(2b)   # 0229: ssstsn
call null     # 0235: nstn
push +3(2b)   # 0239: sssttn
mark null     # 0245: nssn
swap          # 0249: snt
copy +1(1b)   # 0252: stsstn
div           # 0258: tsts
dup           # 0262: sns
jzero +0(0b)  # 0265: ntssn
dup           # 0270: sns
copy +2(2b)   # 0273: stsstsn
call null     # 0280: nstn
mark +0(0b)   # 0284: nsssn
swap          # 0289: snt
mod           # 0292: tstt
push -24(5b)  # 0296: sstttsssn
mod           # 0305: tstt
push +32(6b)  # 0309: ssstsssssn
add           # 0319: tsss
putc          # 0323: tnss
ret           # 0327: ntn

The key idea is to decode the same encoded number as binary digit for the 1st time, and as ternary digit for the next, with recursive operations like a Python code below;

def decode(x,b):               # b=2 or 3
  x //= b
  if x != 0:
    decode(x,b)
  print("stn"[x%b], end="")    # "s" for 0, "t" for 1, "n" for 2

This code decode a number as a binary or ternary digit, then add 0 at the top and remove the last digit, finally substitute 0,1,2 to "s","t","n" respectively.

For example, if you want to encode a Whitespace code "sstn", use an even number 502=200121(ternary)=111110110(binary). At the 1st decoding as binary, "stttttstt" is created, and the 2nd decoding as ternary, "snsstn" is created. Finally, concatenate "ss" and these, the decoded code will be "ssstttttsttsnsstn", which is "ssstttttsttsn" ( "push 502" in Whitespace ) + "sstn" and thus what you want.

In addition, the conversion from 0,1,2 to s,t,n ( ASCII 32,9,10 ) is implemented with a formula y=mod(x,-24)+32.

\$\endgroup\$
3
  • \$\begingroup\$ Nice answer! Pretty similar approach to this Whitespace answer by JoKing, but your formula to convert 0,1,2 to 32,9,10 seems to do the trick to make it slightly shorter. :) \$\endgroup\$ Dec 2, 2022 at 12:44
  • 1
    \$\begingroup\$ Thanks! Actually, this formula is a bit favorite part of the code. \$\endgroup\$
    – angel_p_57
    Dec 3, 2022 at 17:26
  • \$\begingroup\$ I think you can use log bytes with whitespace. \$\endgroup\$ May 3, 2023 at 12:40
5
+500
\$\begingroup\$

Positionally, 1551 Chars or \$1551\log_{256}(3)\approx\$ 307.28 Bytes (cheating)

    >v      >        v                                              >v                   /  >   
                /      \/      \/ 1            \/      \        /      \                        
                                        >              ^                                        
                                        ^+     <                                                
            :           > .   $        v        >     $     :  v    :                           
v                                                       v   {  <     }                          
     g          \ s     \      /\      /                \              /                        
\   ^>      ^        > /                                        \   ^>                      ^   
                                /     \                  /     \                /     \         
                                                / 1    \        /      \/ 1            \ 0      
                                                >   9          ^                                
                                                         +                      ^+     <        
                        >      v      $                         > .            v>   :          v
                        v  ~   <              ;<                                                
                                \         s    /       /                                        
                        \             /                  \             /\      /\     /  \     /

\$\log_{256}3\$ is because each character is a space, newline, or command. General outline (ignoring most control flow, represented in easy mode*):

g:s\.$1+$:{:}   >
   >~$s;19+.1+:0^

*Easy mode is a new test mode on my interpreter, using the s flag. It treats each instruction as what you tell it it is, rather than using the table and your coords.

Explanation

The stack is set up before each running of g as follows:

x
y
y
x

g: gets the char code at x,y and pushes it on the stack twice.
s\ will continue straight if the value pushed by g is non-zero (aka it's not yet at the end of that line), otherwise goes down to the next line.
. outputs the character gotten by g (if it wasn't null, otherwise control would have already moved).
$+1$ swaps the remaining y and x on the stack, increments x, and swaps them back.
:{:} first duplicates y, rotates x onto the top, dupes it, and rotates one copy back to the bottom, restoring the stack format.
> is just used to allow the second line to rejoin the first.

Now for the other line:

> is to make control go along the second line.
~ gets rid of the unoutputted extra g result.
$s; swaps x and y, checks if x is 0 (popping it in the process), and halting if so.
19+. outputs a newline (1+9=10, 10 is code for a newline).
1+: increments y and duplicates it.
0 pushes 0, resetting/setting x to 0.
^ merges back up to the first line.

\$\endgroup\$
5
  • \$\begingroup\$ I can't find a way to make this work? tinyurl.com/jfwnfjkdsjnkf on the official interpreter doesn't print the whole thing, and your interpreter doesn't even work? \$\endgroup\$
    – emanresu A
    Jul 26, 2023 at 0:29
  • \$\begingroup\$ @emanresuA in mine you need to press update first. Also can you tell me where it doesn’t work (using Step)? \$\endgroup\$
    – Dadsdy
    Jul 26, 2023 at 1:14
  • \$\begingroup\$ @emanresuA I figured it out. It’s a bug I patched on my interpreter where some things are treated as strings when adding \$\endgroup\$
    – Dadsdy
    Jul 26, 2023 at 1:22
  • \$\begingroup\$ Okay, would you mind making a PR to the repository so that it works on there? \$\endgroup\$
    – emanresu A
    Jul 26, 2023 at 1:32
  • \$\begingroup\$ @emanresuA I did \$\endgroup\$
    – Dadsdy
    Jul 26, 2023 at 2:20
5
\$\begingroup\$

CoffeeScript, 36 bytes

console.log s='console.log s=%o,s',s

Try it online!

This was intended to be a Civet quine, but it turns out it's a polyglot with CoffeeScript and there isn't a CoffeeScript quine here yet.

This uses the %o formatting directive of JavaScript to print a value as JSON, wrapping the string s in single quotes. This would also make a 38 byte JS quine.

\$\endgroup\$
4
\$\begingroup\$

SWI-Prolog, 22 bytes

a :-
        listing(a).
 

A surprisingly short and elegant solution.

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

\$\endgroup\$
4
\$\begingroup\$

TeaScript, 1 byte

1

Nothing too interesting. But if that's too boring...

TeaScript, 3 bytes

[q|

and if that's to boring...

TeaScript, 15 bytes

(ƒ`(${f})()`)()
\$\endgroup\$
4
\$\begingroup\$

Python, 104 bytes

Uses eval and repr

a = "print 'a','=', repr(eval('a'))\nprint eval('a'),\n"
print 'a','=', repr(eval('a'))
print eval('a'),
\$\endgroup\$
2
  • 4
    \$\begingroup\$ Since this is code-golf, you might want to include a byte count. \$\endgroup\$ Apr 28, 2014 at 12:33
  • 2
    \$\begingroup\$ repr(x)==`x` \$\endgroup\$ Mar 10, 2016 at 23:58
4
\$\begingroup\$

J 4 bytes

I know this competition is probably dead but I wanted to put my answer in.

Just found this by accident

1 b.

J 1 bytes

0
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Nice... I think you found the shortest possible quine once again! \$\endgroup\$ Sep 14, 2016 at 13:32
  • 3
    \$\begingroup\$ These basically rely on the repl state of J, and are rather trivial. But, if it's happening like this, 1& is shorter than 1 b.. \$\endgroup\$ Oct 14, 2016 at 22:58
  • \$\begingroup\$ 28 Bytes for a full program: (echo@,quote)'(echo@,quote)' \$\endgroup\$ Apr 2, 2018 at 2:29
4
\$\begingroup\$

Rust, 173 158 152 144 137 102 bytes

Tuples plus Rust's debug printing mechanism ( {:?} in a format string ) let me cut it down 30+ characters!

fn main(){let t=("fn main(){let t=", ";print!(\"{}{:?}{}\",t.0,t,t.1)}");print!("{}{:?}{}",t.0,t,t.1)}

Pretty-printed. It's so small there's little left to explain!

fn main() {
    // The space after the comma is necessary, because that's how
    // debug-print formats tuples
    let t=("fn main(){let t=", ";print!(\"{}{:?}{}\",t.0,t,t.1)}");
    print!("{}{:?}{}",t.0,t,t.1)
}
\$\endgroup\$
4
\$\begingroup\$

BotEngine, 4x1=4 bytes

TRUE

The T instruction deletes the active bot and prints TRUE.

\$\endgroup\$
4
\$\begingroup\$

><>, 9 bytes

":1-or>o#

Try it online! Exits with an error. Since the top answer reads from its source code, I present this program.

":1-or>o#
"........   capture these characters
 :          duplicate last character (`#`)
  1-        decrement it (`"`)
    o       output it
     r      reverse the stack
      > #   loop inner
       o    output

The # is a very repulsive mirror--anything that touches it will go the other way. In this case, it is functionally the same as <.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ # is the same as #! \$\endgroup\$
    – user63187
    May 21, 2017 at 12:30
  • \$\begingroup\$ No problem. I figured that something was up :P \$\endgroup\$
    – user63187
    May 21, 2017 at 18:39
  • \$\begingroup\$ I like the trick of decrementing #. +1 \$\endgroup\$ Jun 1, 2017 at 15:42
4
\$\begingroup\$

Turtlèd, 68 63 53 54 bytes (newlines)

rewrote

@##'@r,r,r-{ +.r_}r{ +.r_}'#'@r,r,r-{ +.r_}r{ +.r_}'f

Try it online!

Explanation

@#         Set character variable to #. Useful because this cannot occur in string var     
  #                        #  Set the string var to...
   '@r,r,r-{ +.r_}r{ +.r_}'   This string (quotes included. coincidental)
                            '@r,r,r            Write out first three chars of program: @##
                                   -{ +.r_}r   Write out the string var, then #, move right
                                            { +.r_} Write out the string var again, write #
                                                   'f   overwrite last # with f
\$\endgroup\$
4
\$\begingroup\$

Alice, 45 bytes

Credit to Martin Ender for the use of %, r, and y to obtain the characters "/\ without escaping.

/?.!eO%?.*y1?@~mtz!!4\
\"Y!Z1hrZRoY@*m*h%1Y{/

Try it online!

This program runs entirely in ordinal mode. Because of how ordinal mode programs need to be formatted, this is significantly longer than Martin Ender's cardinal mode quine.

In ordinal mode, the instruction pointer moves diagonally, and commands work on strings instead of integers. The diagonal movement is what makes this tricky: there is even a challenge specifically about formatting a program for ordinal mode. While it's possible to sidestep the entire issue by putting the same string on both lines, this approach ends up slightly longer at 52 bytes.

\".!e1%r.Ryh?*.Ooo1m@z1!{
\".!e1%r.Ryh?*.Ooo1m@z1!{/

Try it online!

Explanation

This is a standard template for ordinal mode, with an additional mirror to allow the program to loop back to the beginning. Linearized, the code is as follows:

".!e1%r.RyY?*~*t%!Y4?Y!ZOh?Z*o1@@mmhz1!{

As with many Fungeoid quines, the " wraps around to itself and puts this entire program in a string literal. Since string mode treats mirrors as mirrors (instead of literals), the string that gets pushed is exactly the linearized code, excluding the ".

.!     Duplicate the string, and move the copy to tape
e1%    Split on "1", placing "@@mmhz" and "!{" on top of the stack.
       The other two parts are irrelevant.
r      Expand !{ into the entire range from code point 33 to 123.
.R     Duplicate and reverse this range
y      Modify the string @@mmhz by changing every character in the range 33-123 
       with the corresponding character in the reversed range.
       The result of this transformation is \\//4" .
       This allows us to get these characters without escaping them.
Y?*~*  Split this string in half by unzipping, and put the halves on either
       side of the original string.  The new string is \/"sourcecode\/4 .
t%     Extract the newly added 4 at the end, and use it to split on the single 4 in the code.

At this point, we have two strings corresponding to approximately half of the code. The top of the stack has the second half of the program and the right side mirrors, and corresponds to these output bytes:

 ? ! O ? * 1 @ m z ! \
  Y Z h Z o @ m h 1 {/

The string below that has the first half of the program, along with the left side mirrors and quote:

/ . e % . y ? ~ t !
\" ! 1 r R Y * * % Y

Neither string currently contains the 4 that was used to split the string.

!      Move second half string to the tape.
Y      Unzip first half: the top of the stack now contains the characters
       from the first half that will end up in the first row of the output.
4      Append the digit 4 to this string.
?Y     Copy second half back from tape and unzip: the top of the stack contains
       characters from the second half that will end up in the second row
!      Move this onto the tape.
Z      Zip the two halves of the first row together.
O      Output this with a linefeed.
h      Temporarily remove the initial \ so the next zip will work right.
?Z     Copy the string back from the tape, and zip the second row together.
       This Z isn't the exact inverse of Y since the second half is longer.
       The resulting behavior is exactly what we want.
*o     Join with the previously removed \ and output.
1      Append 1 to the irrelevant string on the top of the stack.
@      Terminate.

The 52-byte quine works on exactly the same principle, except that it doesn't need the ordinal formatting section of the 45-byte quine.

\$\endgroup\$
4
\$\begingroup\$

Awk, 64 bytes

BEGIN{c="BEGIN{c=%c%s%c;printf c,34,c,34}";printf c,34,c,34}
\$\endgroup\$
4
\$\begingroup\$

><>, 8 bytes

#o<}-1:"

Try It Online

Copied the trick of copying and decrementing the # to get " from the other ><> answer, but uses both sides of the # to avoid needing to reverse the stack.

Edit: A much cleaner solution of the same length:

'rd3*>o<

Try it online!

Everyone forgets that a ' acts exactly the same as a ", but has usable divisors. Another 8 byte solution, but considered cheaty by some, 'r00g>o<

\$\endgroup\$
3
  • 1
    \$\begingroup\$ This is the same approach I used in the comments of the Original ><> answer: Funnily enough my comment and your post were 1 day off being exactly a year apart. \$\endgroup\$ Jan 9, 2018 at 16:11
  • 1
    \$\begingroup\$ @Tealpelican. Wait, why didn’t we just use a single quote? \$\endgroup\$
    – Jo King
    Jan 19, 2018 at 4:40
  • \$\begingroup\$ I always forget ><> can use ' or " but ' is so much more useful with having some usable divisors. \$\endgroup\$ Jan 19, 2018 at 9:39
4
\$\begingroup\$

Operation Flashpoint scripting language,  22  15 bytes

q={"q={"+q+"}"}

Call with:

hint call q

Output:

q={"q={"+q+"}"}

Old version (22 bytes):

q={format["q={%1}",q]}
\$\endgroup\$
4
\$\begingroup\$

Swift 4, 63 bytes

let s=[";print(\"let s=\\(s)\"+s[0])"];print("let s=\(s)"+s[0])

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ ChatGPT roughly gave me a 84 characters solution: let s="let s=%c%@%c;print(String(format:s,34,s,34))";print(String(format:s,34,s,34)). So congrats, you're better than it. :) \$\endgroup\$
    – Cœur
    Dec 19, 2022 at 13:19
4
+400
\$\begingroup\$

Pain-Flak, 2009 bytes

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

Try it online!

(Trailing newline because the interpreter outputs a newline.)

-176 bytes by improving the Brain-Flak quine

Basically a straight port of my Brain-Flak quine. The only major difference is the >< at the beginning, which is required in order to keep the data section out of the output.

><                 switch to right stack; effectively does nothing since both stacks are empty
))((...))()()((    data, same format as the Brain-Flak quine
}main loop{        same as the Brain-Flak quine, but with different constants
}}{{               clear current stack; this does nothing
)))))()()()((}{)((}{)(><)}{(()()((   push opening >< at beginning of code

Since this is Pain-Flak, the code also goes backward after it is finished going forward. As such, I had to ensure that this does not mess up the output.

))()())}{(><)(}{))(}{))()()()(((((   push 70, 68, 5, 4 on right stack
}}{{               clear right stack
}pool niam{        do nothing because top of stack is zero
))()()((...))((    push constants on right stack in reverse order
><                 switch to left stack and implicitly output
\$\endgroup\$
5
  • 1
    \$\begingroup\$ The only Pain-Flak solutions I've seen are ones directly translated from Brain-Flak... \$\endgroup\$
    – Jo King
    Apr 10, 2018 at 5:21
  • \$\begingroup\$ I will give the bounty but kinda lame that it is just a port \$\endgroup\$
    – user63187
    Apr 25, 2018 at 10:39
  • \$\begingroup\$ @Christopher it is your fault that you made Pain-Flak so similar to Brain-Flak :P \$\endgroup\$
    – ASCII-only
    Apr 30, 2018 at 22:13
  • \$\begingroup\$ @ascii painflak update is removing swap stack \$\endgroup\$
    – user63187
    Apr 30, 2018 at 22:47
  • \$\begingroup\$ @Christopher then it'll just be translated Mini-flak? \$\endgroup\$
    – ASCII-only
    Apr 30, 2018 at 23:09
4
\$\begingroup\$

Reflections, 9228 bytes

As the program has 8620 lines, I won't put it here completely.

First line:

\

Then, for each character in the last part (below), there are n newlines for ASCII character n, followed by:

+
#

After it, the last part is (the # is actually already covered by the previous section):

#  /  \          /+\  /#_=0v\
>~ <       /(1:1)#@/       ~
\(0/      2)     \3)(2:2)(3^ 0#+#@
           \:(24):(4#_#_#_  /
      +               \*             (4\
      \*(1(2                          +/

Test it!

Working on explanation.

I had to fix a bug in the interpreter for this one. Does that count as adding a feature just for a challenge?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ :| the URL encoding format is terrible \$\endgroup\$
    – ASCII-only
    May 22, 2018 at 0:57
4
\$\begingroup\$

2DFuck, 1352 1289 bytes

!xv>>>>x>x>>>>>>x>x>x>x>>x>x>x>>x>x>>x>x>x>x>x>>x>x>>x>x>>x>x>x>x>x>>x>x>x>x>x>>x>x>x>x>>x>x>>x>x>x>>x>x>>x>>>x>>>>>>x>>>>>x>>x>>>x>x>>x>>>x>>>>>>x>x>x>>>>>x>>>x>>>x>x>>x>x>x>x>x>>x>x>x>x>>>x>x>x>x>>x>x>x>x>x>x>>x>x>>>>>>>>>>x>x>>>>>x>>x>>>x>x>>x>>>x>>>>>>x>>>>>x>>x>>>x>x>>x>>>x>>>>>>x>x>x>>>>>x>>>x>>>x>x>x>>x>x>>x>x>>x>x>x>x>>x>x>>>x>x>>>>x>>x>>>x>>>>>>>>>>x>>>x>>>x>x>x>>x>x>>x>x>x>x>x>>x>x>>x>>>x>x>>>>x>>x>>>x>>>>>>>>>>x>>>x>>>>>>>>>>x>>>x>>>x>x>>x>x>>x>x>>x>x>x>x>>x>x>>x>x>>x>>>x>x>>>>x>>x>>>x>>>x>x>>x>x>>x>x>>x>x>x>>x>x>>x>x>x>>x>>>x>x>>>>>x>>>>x>x>>>>x>>x>>>x>>>>>>>>>>x>>>x>>>x>x>>x>x>x>x>>x>x>x>>x>x>>x>x>>>x>x>>>>x>>x>>>x>>>>>>>>>>x>>x>>>x>>>x>x>x>>x>x>x>x>x>x>>x>x>>>x>x>>>>x>>>x>>>>>>>>>>x>>x>>>x>>>x>x>x>>x>x>x>x>x>>x>x>x>>>x>x>>>>x>>>x>>>>>>>>>>x>>x>>>x>>>x>x>>x>x>>x>x>>x>x>x>x>x>>x>x>>>x>x>>>>x>>>x>>>>>>>>>>x>>>x>>>x>x>>x>x>x>x>x>>x>x>x>x>>>x>x>>>>x>>x>>>x>>>x>x>>x>x>x>x>>x>x>>x>x>x>>x>x>>>x>x>>>x>x>>>x>x>>>x>x>>>x>x>>>>>x>>>>x>x>>>>>>>>x>x>>>x>x>>>>>>>>>>x>x>>>>>x>>x>>>x>x>^x!..!.!....!.!.!....!....!...!.!..!.![<r!]![vr[!.!....!...]..!.....!.>^r!]![<r!]![vr[!..!.!.!...!.]r![>r[!..!.!....!.!]r![>r[>r[!.!.!.!...!.!.!]r![!.!.!.!..!.!..!]<]r![>r[!.!...!..!.!.]r![>r![!..!.....!.]r[>r![!..!....!..]r[>r![!.!.!.!....!.]r[>r[!.!....!...]r![!.!...!.!..!.]]]]]<]>]]>^r!]

Try it online!

Shaved off 63 bytes with Huffman coding! New explanation in progress.

\$\endgroup\$
1
  • \$\begingroup\$ Some thoughts; you can reverse the data encoding to avoid the second ![<r!], and you can save some bytes through reusing .s (for example all characters have a leading zero). 1131 bytes. I think you might get better huffman encoding through multiple or partial characters \$\endgroup\$
    – Jo King
    Sep 18, 2020 at 7:51
4
\$\begingroup\$

Z80Golf, 120 bytes

00000000: 21f5 76e5 2180 10e5 21cd 00e5 2180 7ce5  !.v.!...!...!.|.
00000010: 21cd 00e5 21e1 7de5 2106 14e5 2110 e8e5  !...!.}.!...!...
00000020: 2100 80e5 21e5 cde5 211b 3ee5 2100 80e5  !...!...!.>.!...
00000030: 211a cde5 2180 13e5 21cd 00e5 211b 1ae5  !...!...!...!...
00000040: 2180 1be5 21cd 00e5 213e 21e5 2106 14e5  !...!...!>!.!...
00000050: 0614 3e21 cd00 801b 1b1a cd00 8013 1acd  ..>!............
00000060: 0080 1b3e e5cd 0080 10e8 0614 e17d cd00  ...>.........}..
00000070: 807c cd00 8010 f576                      .|.....v

Try it online!

Verification:

$ ./z80golf a.bin | xxd
00000000: 21f5 76e5 2180 10e5 21cd 00e5 2180 7ce5  !.v.!...!...!.|.
00000010: 21cd 00e5 21e1 7de5 2106 14e5 2110 e8e5  !...!.}.!...!...
00000020: 2100 80e5 21e5 cde5 211b 3ee5 2100 80e5  !...!...!.>.!...
00000030: 211a cde5 2180 13e5 21cd 00e5 211b 1ae5  !...!...!...!...
00000040: 2180 1be5 21cd 00e5 213e 21e5 2106 14e5  !...!...!>!.!...
00000050: 0614 3e21 cd00 801b 1b1a cd00 8013 1acd  ..>!............
00000060: 0080 1b3e e5cd 0080 10e8 0614 e17d cd00  ...>.........}..
00000070: 807c cd00 8010 f576                      .|.....v

$ ./z80golf a.bin | diff -s a.bin -
Files a.bin and - are identical

Looks like no one tried to make a proper quine in machine code yet, so here is one.

Although the machine code is loaded to memory, it does NOT read any address occupied by the code. Instead, it uses the stack space to setup required data.

Disassembly

start:
  ld hl, $76f5
  push hl
  ld hl, $1080
  push hl
  ld hl, $00cd
  push hl
  ld hl, $7c80
  push hl
  ld hl, $00cd
  push hl
  ld hl, $7de1
  push hl
  ld hl, $1406
  push hl
  ld hl, $e810
  push hl
  ld hl, $8000
  push hl
  ld hl, $cde5
  push hl
  ld hl, $3e1b
  push hl
  ld hl, $8000
  push hl
  ld hl, $cd1a
  push hl
  ld hl, $1380
  push hl
  ld hl, $00cd
  push hl
  ld hl, $1a1b
  push hl
  ld hl, $1b80
  push hl
  ld hl, $00cd
  push hl
  ld hl, $213e
  push hl
  ld hl, $1406
  push hl

  ld b, 20
loop1:
  ld a, $21
  call $8000
  dec de
  dec de
  ld a, (de)
  call $8000
  inc de
  ld a, (de)
  call $8000
  dec de
  ld a, $e5
  call $8000
  djnz loop1

  ld b, 20
loop2:
  pop hl
  ld a, l
  call $8000
  ld a, h
  call $8000
  djnz loop2

  halt

At start, the stack pointer sp is zero, just like other registers. Pushing some values causes sp to decrease, so the values are stacked in the memory region $ffxx.

The combination ld hl, $xxxx and push hl seems like the best option to dump predefined values into some memory space. It takes 4 bytes to store 2 bytes; any other option I could think of uses 3 or more bytes to store only one byte.

The first loop prints the ld hl, $xxxx (21 xx xx) and push hl (e5) instructions for the data, from the bottom of the stack (the address, represented by de, is decreased starting from $0000).

ld b, $xx and djnz label combined forms a fixed-times looping construct. It is only 4 bytes, which is optimal in Z80 (unless the loop count is already saved in another register).

But there is an endianness problem here, so simply sweeping the memory addresses in decreasing order does not work. So I had to add a pair of dec de and inc de at the cost of 2 bytes (plus 4 bytes to push the 2 bytes into the stack).

The second loop prints the main code by popping data from the stack.

Possible improvement ideas

Since the code is longer than $38 or 56 bytes, we can't use rst $38 in place of call $8000. Having call $8000 6 times in total, it's a great opportunity for golf. I considered placing call $8000; ret at address $38, but then I have to reduce the main code into 26 bytes or lower.

I also thought of moving the code to the front by adding some jr, so that I can embed the call $8000; ret in the code part. But then I can't use the efficient "pop and print" loop. It prints the data in reverse order of pushing, so it can't be used to print the push part; the "print" overwrites the stack with the return address, so it can't be used to print the first part either.

Finally, there is room for alternative encoding since some bytes frequently appear in the code. But Z80 itself is severely limited in arithmetic...

\$\endgroup\$
4
\$\begingroup\$

Elixir, 44 bytes

q=:'q=:~p;:io.format q,[q]';:io.format q,[q]

Try it online!

This is basically an existing quine taken from here, but I managed to save another 2 bytes by declaring q as an atom instead of a binary.

\$\endgroup\$
4
\$\begingroup\$

MathGolf, 9 bytes

ÿ_'ÿ¬_'ÿ¬

Try it online!

Explanation:

ÿ_'ÿ¬_'ÿ¬
ÿ          Start string of length 4
 _'ÿ¬      Push "_'ÿ¬"
     _     Duplicate it
      'ÿ   Push the character "ÿ"
        ¬  Rotate stack so the "ÿ" is at the bottom
           Implicitly output "ÿ", "_'ÿ¬", "_'ÿ¬" join together
\$\endgroup\$
1
  • \$\begingroup\$ ÿ'ÿ¬_'ÿ¬_ is another 9-byter. \$\endgroup\$
    – maxb
    Jan 7, 2019 at 11:56
1
4 5
6
7 8
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.