Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Using your language of choice, golf a quine.

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.

Points for:

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

Also, sorry about the title. I was just going to make it quine but it has to be at least 15 characters.

Scoreboard of true quines by language1

1 Answers were omitted which involved direct or indirect reading of the source code, which depend on a REPL environment and just print what was entered as well as error quines.

share|improve this question
3  
Do you not mean, "Golf you a quine for greater good!"? And, yes, I'm a 'Grammar Nazi'. – Mateen Ulhaq May 3 '11 at 2:49
27  
@muntoo it's a play on "Learn you a Haskell for Great Good". – Rafe Kettler May 3 '11 at 2:52
7  
what about random text generator quines (a probability that the program will print itself) – Ming-Tang May 14 '11 at 0:01
3  
@muntoo Evidently a British English 'Grammar Nazi', judging by the positioning of your quotes and punctuation. – daviewales Jun 18 '14 at 9:13
1  
I like how 10% of the high scores are Martin Büttner – Cyoce Mar 22 at 15:16

126 Answers 126

GolfScript, 2 bytes

1

(with newline following). This pushes the number 1 onto the stack, then 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.

share|improve this answer
12  
Or PowerShell, or PHP :-) – Joey Jan 28 '11 at 9:54
3  
You didn't go back in time and give the inventor the idea to invent GolfScript, did you? – Mateen Ulhaq May 3 '11 at 2:38
59  
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. – Ilmari Karonen Feb 3 '12 at 8:27
11  
The one-char program \n probably also is? – Lynn Aug 23 '13 at 14:51
3  
@Pseudonym a quine is literally a program which prints its own source. I don't think there are any arbitrary restrictions on "structure". – Hugo Zink Sep 24 '15 at 11:07

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.

share|improve this answer

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.

share|improve this answer
1  
Listening to Hello World in Fugue right now... pretty catchy. – Robert Fraser Apr 29 '15 at 3:29
3  
Martin, you gotta stop somewhere. – Seeq Feb 25 at 21:12

HQ9+ (1 character)

Not quite as short as the 0 char one, but here it is anyway:

Q
share|improve this answer
11  
This one is legit... – st0le Feb 6 '11 at 11:51
2  
What's great about this one is unlike others (like the 1 in golfscript or php) is that you can have any arbitrary HQ9+ program (e.g., H+9+H9) and the quine of that program is always 1 more character than the program itself (in this case H+9+H9Q). – Casey Apr 23 '11 at 21:17
12  
@Casey that's not entirely true: you can never have an HQ9+ Quine that doesn't involve exactly 1 Q and some sequence of +s (it is a stretch to say that the second program you have there "is a quine of" the first - they are different, and the "Quine" you suggested outputs too much - the lyrics to 99 bottles occur twice in the programs output, but not in the source) – tobyodavies Apr 24 '11 at 16:31
    
Quine in some HQ9+s: Hello World – CalculatorFeline Mar 11 at 0:00
    
-1, reads its own source code. – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ Jun 30 at 8:32

PHP, 32

Probably not an optimal solution, but it makes me smile.

HAHA THIS IS TECHNICALLY A QUINE

Give it a shot, works like a charm.

share|improve this answer
2  
+1 just because I laughed. :P – user1354557 Dec 11 '13 at 23:33
2  
+1 for "give it a shot" :-DD – Tomas Feb 1 '14 at 14:51
    
Also works with HTML, though that's actually a markup language. – nyuszika7h Apr 26 '14 at 15:31
1  
Give him his 32 points :) – YoYoYonnY Feb 26 '15 at 21:35
    
Wait, how does this work? – addison Jul 18 '15 at 23:27

Raw .exe, 247 bytes

Quine.exe:

The version of this file is not compatible with the version of Windows you're running. Check you computer's system information to see whether you need an x86 (32-bit) or x64 (64-bit) version of the program, and then contact the software publisher.

The source code is the Windows 7 error message for an invalid exe file.

share|improve this answer
    
error quines not allowed, -1. – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ Jun 30 at 8:31

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!
+[[>>+[>]+>+[<]<-]>>[>]<+<+++[<]<<+]>>+[>]+++[++++++++++>++[-<++++++++++++++++>]<.<-<]
share|improve this answer
7  
That's a clever way to do it. – Peter Olson Jun 22 '11 at 16:48
10  
How does it work? – proud haskeller Sep 13 '14 at 16:21
1  
@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. – ESultanik Feb 9 at 15:48
1  
@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. – ESultanik Mar 7 at 12:05
1  
That's true. Also the newlines are necessary. – CalculatorFeline Mar 7 at 16:39

PostScript, 20 chars

Short and legit. 20 chars including trailing newline.

(dup == =)
dup == =
share|improve this answer

If we're going for short quines:

0 characters. xD

share|improve this answer
20  
Points for originality, but I'm adding this to the list of "ways to cheat". – Rafe Kettler Jan 28 '11 at 0:39
36  
@Rafe: it's not very original. This was one of the winners of the 1994 International Obfuscated C Code Contest: the smallest self reproducing program: de.ioccc.org/years-spoiler.html#1994_smr – R. Martinho Fernandes Jan 28 '11 at 2:18
11  
Can we avoid up-voting silly answers? – marcog Jan 28 '11 at 11:26
23  
@marcog what is code golf but answering silly questions with ridiculous (or ridiculously complex) answers ;) – tobyodavies Jan 28 '11 at 12:01
13  
@toby It's called common sense. If we don't apply it, this site will devolve into a rather stupid one. Up-vote the clever, but still short questions not the ones that required half a brain cell to come up with. – marcog Jan 28 '11 at 12:09

Unix script (11 chars)

I am not exactly sure if this disqualifies as You can't just read the source file and print it, but it certainly is a nice one. Taken from http://research.swtch.com/zip.

#!/bin/cat
share|improve this answer
3  
+1 well technically "you" don't read the source, cat does – Tim Seguine Feb 1 '14 at 15:24
    
You don't count the hashbang in code golf score, as technically it's a cat script. – nyuszika7h Apr 26 '14 at 15:30
1  
That raises the question though, is it 0 characters then? – nyuszika7h Apr 27 '14 at 17:51
13  
The manpage for cat should be modified to "cat - Take a file and execute it as a quine". – Kritzefitz Aug 29 '15 at 15:12
1  

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:

share|improve this answer
5  
Dear pete what is this. – Cᴏɴᴏʀ O'Bʀɪᴇɴ Feb 26 at 23:05
1  
How long did it take to make this? – Adnan Feb 26 at 23:13
1  
@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. – Martin Ender Feb 26 at 23:15
    
Well, my guess of 23 was a bit off... :P – Eᴀsᴛᴇʀʟʏ Iʀᴋ Feb 26 at 23:23
    
@RikerW Hey, I'm not done yet! (That said, yes it was.) – Martin Ender Feb 26 at 23:23

Python 2 (29)

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

from en.literateprograms.org

share|improve this answer
1  
+1, you beat my similar solution so I deleted it. It should be noted that this only works in Python 2. – nyuszika7h Apr 28 '14 at 12:32
    
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 – Ehtesh Choudhury Oct 14 '15 at 16:20
1  
If this solution is not your own creation, you should make it Community Wiki. Also, the link is dead. – mbomb007 Apr 27 at 20:12

Fission, 6 bytes

It appears this is now the shortest "proper" quine among these answers. However, Fission is only a bit over a year old, so this answer is technically not eligible for being accepted. Then again, I highly doubt that Fission was specifically written to make quining easy.

'!+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 ;.

share|improve this answer

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...

share|improve this answer
8  
The second one uses heredoc, <<2 starts a string on the next line, and *2 repeats the string – Ming-Tang Jan 28 '11 at 2:52
    
Why do you need the 2? – CalculatorFeline Mar 7 at 5:27
1  
Wow number 1 looks like Python 2's quine!!! – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ Jun 15 at 8:00
1  
You must do CW, because you took it from another source. – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ Jun 30 at 9:11
    
Look at the comments please, especially the one about Community Wiki. (And I would not call a graduated site a failed community!) – wizzwizz4 Jul 19 at 6:26

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)+')'")
share|improve this answer

java, 530 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()){++i;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 ())
        {
            ++i; 
            if (i==92) 
                System.out.print (b.toString (36)); 
            System.out.print ((char) c);
        }
    }
}
share|improve this answer
    
How does it work? – Loovjo May 23 '15 at 13:02
    
@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). – user unknown May 24 '15 at 9:38

Chicken, 7

chicken

No, this is not directly echoed :)

share|improve this answer
    
Damnit, you beat me to it :) – Taconut Feb 1 '14 at 22:42
    
It's not echoed, it's the string chicken! – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ Jun 28 at 21:45

Fob (135)

If Fob, a language of my own creation some time ago, I present a rather interesting 135 byte quine:

$$#<&$::#<&$:#<&#<&$:#<=#<&$&//%<//<.&%<<%.%<&>/////%<<%.<&.%<.%/////<&.%<<&/.%%<&>%</%<////<&.%<<%/<&.%%<&>/%//<&.%<</&.%%%<&>>/>>#<=
share|improve this answer
    
Error on line 1: If Fob, a... (Fob is not defined) – CalculatorFeline Mar 11 at 0:01

Javascript (36 char)

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

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

share|improve this answer
    
That... is impressive. You should explain how it works for me 8-| – TehShrike Sep 27 '11 at 19:18
3  
@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. – Peter Olson Sep 27 '11 at 19:22
6  
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. – Ilmari Karonen Feb 3 '12 at 18:55
    
@IlmariKaronen not exactly. If an other implementation chooses to add a space between the arguments and the body, the output is not a quine in an implementation that doesn't add a space between the arguments and body. – Johannes Kuhn Dec 21 '13 at 20:59
1  
Here is the same quine, 1 byte shorter: !function a(){alert("!"+a+"()")}(). – Ismael Miguel Feb 27 '15 at 1:22

Javascript ES6 - 21 bytes

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

I call this quine "The Bling Quine."

Sometimes, you gotta golf in style.

share|improve this answer
    
Does !$=_=>`!$=${$}()`() save you 2 bytes? – Downgoat Feb 17 at 6:20
    
Invalid assignment left hand side. Wish it worked :( – Mama Fun Roll Feb 17 at 14:21
    
Does !_=>`!$=${$}()`() work ? – Downgoat Feb 17 at 16:36
    
Declaration of quine is missing. Nope. – Mama Fun Roll Feb 18 at 1:15
    
$=_=>eval(`$=${$};$()`);$() is a rather amusing quine to crash your browser. – Patrick Roberts 2 hours ago

><> (Fish) - 8 chars

Prints itself but throws an error

"r0:g>o<

13 For no error (old Fish)

"r0:g!;>?o?|;

15 if you think g is cheating

"r1b3*+!;>?o?|;
share|improve this answer
    
Last two ones don't work for me. They output rg>? and r3!?|, respectively. They seem to skip two characters every time... – tomsmeding Apr 22 '13 at 5:55
    
@tomsmeding I think the interpreter changed some point after this answer, hence the (old fish) in parentheses. Though I honestly can't remember it was 2 years ago. I know they worked when i posted my answer. – cthom06 Apr 22 '13 at 13:19
    
In old fish the ? command did not pop the stack, new fish does – JNF May 27 '15 at 18:53
    
I would suggest, for new ><>, "r0:g>o_!~l?!;!_|, or "r13b*+>o_!~l?!;!_| for no g version (which I don't view as cheating anyway...). But then you're not better off from "r00g!;oooooooo| (16) – JNF May 27 '15 at 20:57

JavaScript 2688!!

Any awards for the most abysmal quine? My first go, it builds a little html interface which lets your run it again to build another interface which lets you... you get it, try it here

var a = [47, 42, 32, 90, 108, 97, 116, 97, 110, 39, 115, 32,
        115, 101, 108, 102, 32, 114, 117, 110, 110, 105, 110,
        103, 32, 113, 117, 105, 110, 101, 32, 42, 47, 10,
        118, 97, 114, 32, 116, 97, 59, 10, 10, 102, 117,
        110, 99, 116, 105, 111, 110, 32, 102, 119, 114, 105,
        116, 101, 40, 97, 114, 114, 41, 32, 123, 10, 9,
        118, 97, 114, 32, 107, 32, 61, 32, 39, 39, 59,
        10, 9, 118, 97, 114, 32, 98, 117, 116, 32, 61,
        32, 100, 111, 99, 117, 109, 101, 110, 116, 46, 99,
        114, 101, 97, 116, 101, 69, 108, 101, 109, 101, 110,
        116, 40, 39, 73, 78, 80, 85, 84, 39, 41, 59,
        10, 9, 118, 97, 114, 32, 98, 111, 32, 61, 32,
        100, 111, 99, 117, 109, 101, 110, 116, 46, 103, 101,
        116, 69, 108, 101, 109, 101, 110, 116, 115, 66, 121,
        84, 97, 103, 78, 97, 109, 101, 40, 39, 66, 79,
        68, 89, 39, 41, 91, 48, 93, 10, 9, 116, 97,
        46, 114, 111, 119, 115, 32, 61, 32, 39, 57, 39,
        59, 10, 9, 116, 97, 46, 99, 111, 108, 115, 32,
        61, 32, 39, 57, 48, 39, 59, 10, 9, 102, 111,
        114, 40, 118, 97, 114, 32, 122, 61, 45, 49, 59,
        32, 43, 43, 122, 60, 97, 114, 114, 46, 108, 101,
        110, 103, 116, 104, 59, 41, 32, 123, 10, 9, 9,
        107, 43, 61, 83, 116, 114, 105, 110, 103, 46, 102,
        114, 111, 109, 67, 104, 97, 114, 67, 111, 100, 101,
        40, 97, 114, 114, 91, 122, 93, 41, 59, 10, 9,
        125, 10, 9, 116, 97, 46, 118, 97, 108, 117, 101,
        32, 43, 61, 32, 107, 59, 10, 9, 98, 111, 46,
        97, 112, 112, 101, 110, 100, 67, 104, 105, 108, 100,
        40, 116, 97, 41, 59, 10, 9, 98, 117, 116, 46,
        116, 121, 112, 101, 32, 61, 32, 39, 98, 117, 116,
        116, 111, 110, 39, 59, 10, 9, 98, 117, 116, 46,
        118, 97, 108, 117, 101, 32, 61, 32, 39, 82, 117,
        110, 33, 39, 10, 9, 98, 117, 116, 46, 111, 110,
        99, 108, 105, 99, 107, 32, 61, 32, 119, 105, 110,
        100, 111, 119, 46, 111, 110, 108, 111, 97, 100, 59,
        10, 9, 98, 111, 46, 97, 112, 112, 101, 110, 100,
        67, 104, 105, 108, 100, 40, 98, 117, 116, 41, 59,
        10, 125, 10, 10, 119, 105, 110, 100, 111, 119, 46,
        111, 110, 108, 111, 97, 100, 32, 61, 32, 102, 117,
        110, 99, 116, 105, 111, 110, 40, 41, 32, 123, 10,
        9, 116, 97, 32, 61, 32, 100, 111, 99, 117, 109,
        101, 110, 116, 46, 99, 114, 101, 97, 116, 101, 69,
        108, 101, 109, 101, 110, 116, 40, 39, 84, 69, 88,
        84, 65, 82, 69, 65, 39, 41, 59, 10, 9, 116,
        97, 46, 118, 97, 108, 117, 101, 32, 43, 61, 32,
        39, 118, 97, 114, 32, 97, 32, 61, 32, 91, 39,
        59, 10, 9, 102, 111, 114, 40, 118, 97, 114, 32,
        122, 32, 61, 32, 48, 59, 32, 122, 60, 97, 46,
        108, 101, 110, 103, 116, 104, 59, 32, 122, 43, 43,
        41, 32, 123, 10, 9, 9, 116, 97, 46, 118, 97,
        108, 117, 101, 32, 43, 61, 32, 97, 91, 122, 93,
        43, 40, 40, 33, 122, 124, 124, 40, 122, 37, 49,
        49, 41, 41, 63, 39, 44, 32, 39, 58, 39, 44,
        32, 92, 110, 92, 116, 92, 116, 39, 41, 59, 10,
        9, 125, 10, 9, 116, 97, 46, 118, 97, 108, 117,
        101, 32, 43, 61, 32, 39, 93, 59, 92, 110, 92,
        110, 39, 59, 10, 9, 102, 119, 114, 105, 116, 101,
        40, 97, 41, 59, 10, 125, 10, 10];

/* Zlatan's self running quine */
var ta;

function fwrite(arr) {
    var k = "";
    var but = document.createElement("INPUT");
    var bo = document.getElementsByTagName("BODY")[0]
    ta.rows = "9";
    ta.cols = "90";
    for(var z=-1; ++z<arr.length;) {
        k+=String.fromCharCode(arr[z]);
    }
    ta.value += k;
    bo.appendChild(ta);
    but.type = "button";
    but.value = "Run!"
    but.onclick = window.onload;
    bo.appendChild(but);
}

window.onload = function() {
    ta = document.createElement("TEXTAREA");
    ta.value += "var a = [";
    for(var z = 0; z<a.length; z++) {
        ta.value += a[z]+((!z||(z%11))?", ":", \n\t\t");
    }
    ta.value += "];\n\n";
    fwrite(a);
}
share|improve this answer
6  
This requires a username and password to try on your link – jamylak Apr 11 '13 at 6:02
2  
+1 for the idea, but your answer is actually code bowling. ;) – nyuszika7h Apr 26 '14 at 15:33
24  
1  
Broken Link Alert. – Cᴏɴᴏʀ O'Bʀɪᴇɴ Dec 6 '15 at 20:25
3  
While the idea of self-replicating HTML is intriguing, this answer has two issues in its current form: 1. It is a metaquine. This JavaScript code creates a HTML+JS quine, but it's not a quine itself. 2. It is not golfed. The help center (faq at the time of this post) says that all solution to challenges should be a serious contender for the winning criteria in use. For example, an entry to a code golf contest needs to be golfed. – Dennis Feb 14 at 15:56

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.
share|improve this answer

Haskell (50 characters)

main=putStr$q++show q;q="main=putStr$q++show q;q="
share|improve this answer
    
hi i now found a 48 character quine. here codegolf.stackexchange.com/a/54073/20370 – proud haskeller Jul 30 '15 at 18:35

Python 3, 54

I have never seen this one before, so here's my fair creation. It is longer than the classical one but a true one-liner without ;

print(str.format(*['print(str.format(*[{!r}]*2))']*2))
share|improve this answer
3  
btw, this is 2 bytes shorter in Python 2, where you don't need the parentheses after print. – flornquake Sep 15 '14 at 9:40
    
@flornquake Then wouldn't it be four bytes shorter, because of the print(...) within the string? – Alex L. Feb 11 at 23:59
1  
@Alex No, because you need to add a space after each print. – flornquake Feb 20 at 23:04
    
@flornquake Right. Thanks. Also, nice username. It's interesting. – Alex L. Feb 21 at 2:44

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.

share|improve this answer
1  
Golfscript is weird. – CalculatorFeline Mar 23 at 4:27

A Classic - Lisp - 78

((lambda (x) (list x (list 'quote x))) '(lambda (x) (list x (list 'quote x))))

A beautiful snippet, but give credit where credit is due.

share|improve this answer
4  
Actually this code returns itself instead of printing itself. Running it in an interpreter with read-eval-print loop will of course print the returned list, but the printing is not part of the code itself. The C equivalent of this would be a C code which outputs its executable instead of its source code. Which would certainly also be a quite interesting problem, although heavily system-dependent. – celtschk Feb 3 '12 at 16:13

dc - 16 characters

[91PP6120568P]dx
share|improve this answer
1  
There's this for 10: 6581840dnP – Digital Trauma Feb 26 '15 at 22:22

JavaScript:

<script>alert(document.querySelector("script").outerHTML)</script>

It technically doesn't read its own file.

I think this is shorter and more “obfuscated”, though:

(_=$=>alert('(_='+_+')()'))()
share|improve this answer
6  
It reads its own source, though. – Joey May 12 '11 at 21:15
1  
` Uncaught SyntaxError: Unexpected token =>` in Chrome – Nakilon Jan 14 '15 at 9:36
6  
@Nakilon: Use Firefox. – Ryan O'Hara Jan 14 '15 at 16:17
1  
+1 for the +_+ in the shorter version – zyabin101 Jan 4 at 18:31
    
Umm... the first one is actually HTML5. – Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ Jun 15 at 8:07

Retina, 20 bytes

Now that Retina reads code from a single file by default, it finally makes sense to write a quine in it. Before we get started, I'd like to mention the trivial solution of a file which contains a single linefeed. In that case Retina will replace nothing with nothing in the input and then print nothing with a trailing linefeed which happens to match the source code. That's quite cheaty though, so I wouldn't consider it a proper quine.

So here is a proper one:


S`((.+))
S`((.+))

The one leading and two trailing linefeeds are significant.

Try it online!

Explanation

The program consists of three stages. A replacement stage, split stage and another replacement stage.


S`((.+))

This is the replacement stage. It replaces the empty string (i.e. the non-existent input) with the second line, verbatim. This string is passed to the next stage, which is the split stage (where the code happens to be identical to that string):

S`((.+))

This split stage matches the entire string with .+ and captures it twice. That may seem a bit pointless, but split stages have the nifty feature that captured strings are included in the resulting list of split parts (this feature is simply inherited from .NET's Regex.Split and can normally be used to keep the delimiters of whatever you're splitting). So by wrapping the regex in two groups, we can easily duplicate the string. To fully understand what's going on, let's consider the result of

new Regex(@"S`((.+))").Split(@"S`((.+))")

in .NET. The catch is that empty parts of the split are still included in the result. Of course, there's an empty substring before and after the match. So we actually get an array, which would look something like this:

{"", "S`((.))", "S`((.))", ""}

The first string is the part before the (only) match, the next two are the two captures from the match, and the last string is the part after the match.

In Retina, the result of Regex.Split is simply joined with linefeeds. So we get this as the output of the stage:


S`((.+))
S`((.+))

That's pretty close except that we're missing one trailing linefeed.

The third stage of the quine is just two empty lines. That's another replacement stage, which replaces nothing with nothing. It's literally a no-op. However, when the result of that stage is actually printed to STDOUT, one more linefeed is appended, so that the output of the program will contain both the linefeeds we need.

Golfing this was a bit weird. It started out as a fairly elaborate program with self-escaping and whatnot at 90 bytes:


S_`((.+)) (?<=^.*)\$$ $$$$$$ \`^|\s(?=.*$$) $$n
S_`((.+))
(?<=^.*)\$
$$$
\`^|\s(?=.+$)
$n

While I started writing things up, I noticed I could avoid all those pesky dollar signs by making use of another split stage, which simplified it a lot and brought it down to around 50 bytes:


S`((.+)) S\_`\s(?=.*\Z)
S`((.+))
S\_`\s(?=.*\Z)

Well then I realised I'm only using the last stage in that to make the last stage work, so I ditched that as well. While it's nice to golf code from 98 to 20 bytes, I feel like the solution got gradually less interesting in the process. :)

share|improve this answer
    
The interesting thing is that the core was in there all along :) – CalculatorFeline Mar 10 at 23:53

protected by Peter Taylor Jun 20 '13 at 15:16

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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