1-up your average quine

38

1

A 1-up quine is a program which is very similar to a quine. The one major difference is that instead of printing itself once, when n copies of the program are concatenated, the result prints the original program n+1 times.

Example

If your program is Abc123:

Abc123  ->  Abc123Abc123
Abc123Abc123  ->  Abc123Abc123Abc123
Abc123Abc123Abc123  -> Abc123Abc123Abc123Abc123

Challenge

Your challenge is to create the shortest valid 1-up quine in any language. The usual quine rules apply, so you may not:

  • Submit the empty program.
  • Directly or indirectly read1 the source code.
  • Use quining built-ins.

This is code-golf, so shortest code in bytes wins.

1This does not include using a hard-coded string or code block as part of your program.

ETHproductions

Posted 2016-02-15T21:31:19.717

Reputation: 47 880

2Is it ok if n is limited by some data type restriction (maximum integer size etc)? – Luis Mendo – 2016-02-15T21:55:01.257

2@LuisMendo I think that's OK, as long as you can support a reasonable number of repeats (100, maybe). – ETHproductions – 2016-02-15T22:52:47.990

Is reading the length of the source code using a builtin quining method okay? – Conor O'Brien – 2016-02-16T13:22:26.280

2@CᴏɴᴏʀO'Bʀɪᴇɴ That seems a little too similar to getting the source code itself to me, since you're still getting information about the source code. So no. – ETHproductions – 2016-02-16T15:24:23.470

Answers

13

GolfScript, 12 bytes

{`'.~'+:n}.~

Try it online!

Explanation

This combines ideas from the standard GolfScript quine:

{'.~'}.~

And my recently discovered quine:

":n`":n`

The main idea is again to use n which is printed implicitly at the end of the program in order to get the additional copy of the quine. Since assigning the variable doesn't change anything when it's done again in subsequent copies, this will only add one copy. Here's a breakdown of the code:

{        # Standard quine framework. This pushes the block, duplicates it and runs the
         # second copy, such that it can process the first copy to create a quine.
  `      # Convert the block to its string representation.
  '.~'+  # Append the string '.~' to make a complete quine. This is simply left on the
         # stack to be printed at the end.
  :n     # Store the string in n such that one more copy is printed at the end.
}.~

Martin Ender

Posted 2016-02-15T21:31:19.717

Reputation: 184 808

13

GolfScript, 12 bytes

{: ".~"][}.~

Try it online!

How the source code works

{: ".~"][}.~

{        }    Define and push a code block.
          .~  Push a copy and execute it.
 :            Save the code block in the space character.
              Every subsequent space will now execute the code block.
   ".~"       Push that string.
       ]      Wrap everything up to the last [ in an array.
        [     Set a new array marker.

If the above source code is executed once, the stack will end up as

["" {: ".~"]} ".~"]

where the empty string at the beginning corresponds to the initial state of the stack (empty input).

Two copies of the source code would leave a final state of

["" {: ".~"]} ".~"] [{: ".~"]} ".~"]

three copies a final state of

["" {: ".~"]} ".~"] [{: ".~"]} ".~"] [{: ".~"]} ".~"]

and so on.

What happens next

After executing the source code, the interpreter does the following.

  1. It wraps the entire stack in an array, and pushes that array on the stack.

    For two copies of the source code, the stack now contains

    ["" {: ".~"][} ".~"] [{: ".~"][} ".~"] [["" {: ".~"][} ".~"] [{: ".~"][} ".~"]]
    
  2. It executed puts with the intention of printing the wrapped stack, followed by a linefeed.

    puts is defined as {print n print}, so it does the following.

    1. print prints the wrapped up copy of the stack without inspecting it (i.e., without converting it to its string representation). This sends

      {: ".~"][}.~{: ".~"][}.~
      

      (the source code) to STDOUT and pops the stack copy from the top of the stack.

      The stack now contains

      ["" {: ".~"][} ".~"] [{: ".~"][} ".~"]
      
    2. executes the code block we defined previously.

      : begins by saving [{: ".~"][} ".~"] in the space character, then ".~" pushes itself, ] wraps the ".~" in an array, and [ sets a new array marker.

    3. n pushes a string consisting of a single linefeed.

      The stack now contains

      ["" {: ".~"][} ".~"] [{: ".~"][} ".~"] [".~"] "\n"
      
    4. is executed once more. However, it was redefined when we called it for the first time and now contains an array, not a code block.

      In fact, it pushes [{: ".~"][} ".~"], leaving the stack as

      ["" {: ".~"][} ".~"] [{: ".~"][} ".~"] [".~"] "\n" [{: ".~"][} ".~"]
      
    5. Finally, print prints the topmost stack item without inspecting it, sending

      {: ".~"][}.~
      

      to STDOUT, 1-upping the source code.

Dennis

Posted 2016-02-15T21:31:19.717

Reputation: 196 637

11

Javascript ES6 (REPL), 55 bytes

var a=-~a;$=_=>`var a=-~a;$=${$};$();`.repeat(a+1);$();

Saved 2 bytes thanks to @user81655!

Explanation

Here's the standard quine framework:

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

You should be able to see this framework inside the submission. More explanation below.


var a=-~a;

This is the counter, defaulted to 1. Basically, it tells us how much to repeat the quine and increments at the same time.

$=_=>`var a=-~a;$=${$};$();`.repeat(a+1);$();

This is the quine part. We essentially repeat the quine string by the counter+1. Subsequent function calls will override the output.

Mama Fun Roll

Posted 2016-02-15T21:31:19.717

Reputation: 7 234

This might be just me, but this doesn't seem to print anything. (tested using JSFiddle, if it matters?) – jrich – 2016-02-16T01:28:11.620

Ah, you should use the Firefox console. (And reload after each run to reset a). – Mama Fun Roll – 2016-02-16T01:33:10.313

I don't think you need var – Cyoce – 2016-02-17T01:53:44.027

No, I do because a is initially undefined. Using var allows us to work with it. – Mama Fun Roll – 2016-02-17T02:20:08.687

7

CJam, 14 bytes

{"_~"]-2>_o}_~

Try it online!

How it works

{"_~"]-2>_o}_~

{          }    Define a code block and push it on the stack.
            _~  Push and execute a copy of it.
 "_~"           Push that string.
     ]          Wrap the entire stack in an array.
      -2>       Discard all but the last two elements (block and string).
         _o     Push and print a copy of that array.

After the last copy of the program has been executed, the array that contains the block and the string is still on the stack, so it is printed implicitly.

Dennis

Posted 2016-02-15T21:31:19.717

Reputation: 196 637

4

NodeJS, 63 61 60 55 bytes

this will also work in JavaScript (ES6) if you consider multiple console messages to be separated by newlines (no REPL required)

Saved 2 bytes thanks to @dev-null

(f=_=>(t=_=>console.log(`(f=${f})()`)||(_=>t))(t()))()

note that there is a newline at the end of the code.


This was an interesting one, definitely one of my favorites for this site so far.

I'm fairly confident this can't be golfed much more. (maybe SpiderMonkey's print function...)

Explanation

//FIRST ITERATION
            console.log(`(f=${f})()`)                   //logs to the console a quine of the source code using function f's toString()
                                     ||                 //causes the expression to evaluate to the second part, since console.log's return value is falsy
                                       (_=>t)           //a function that returns function t when called
       t=_=>                                            //defines function t to be the code above. When called, t will log a quine and then return a function that returns t.
      (                                      )(t())     //call t twice. (one call is done via the t() as an ignored parameter) This will print the quine twice.
 f=_=>                                                  //define f as the above code.
(                                                  )()  //call function f with no arguments. this results in a function returning t. (the result of calling t once)
                                                        //this newline is to compensate for console.log's behavior of adding a newline to its output
//SECOND ITERATION
(                                                  )    //call the function that returns t that was returned from the first iteration. This expression will result in whatever that function returns, which is t.
 f=_=>(t=_=>console.log(`(f=${f})()`)||(_=>t))(t())     //this part evaluates to a function, which is passed as a parameter to the function that returns t, that ignores its parameter.
                                                    ()  //call whatever the last expression returned, which is the function t, with no parameters. This will print the quine once.
                                                        //this call will result in a function returning t, just like from the first iteration, so we can add on more iterations at will.

jrich

Posted 2016-02-15T21:31:19.717

Reputation: 3 898

I love how it also looks like it's putting on sunglasses first. (f=_= I may be a little too tired. – Ben Leggiero – 2016-02-17T01:00:41.353

4

Groovy, 83 bytes

s="s=%c%s%c;f={printf(s,34,s,34,10)};f()%cf()//";f={printf(s,34,s,34,10)};f()
f()//

There is one embedded and no trailing newline. This prints:

s="s=%c%s%c;f={printf(s,34,s,34,10)};f()%cf()//";f={printf(s,34,s,34,10)};f()
f()//s="s=%c%s%c;f={printf(s,34,s,34,10)};f()%cf()//";f={printf(s,34,s,34,10)};f()
f()//

The function f() prints one copy of the quine. The initial program calls it twice. The first line of the appended code becomes a comment and only the second call to f() is executed.

Sleafar

Posted 2016-02-15T21:31:19.717

Reputation: 2 722

4

Ruby, 43 bytes

1;s="1;s=%p;$><<s%%s*n=2-0";$><<s%s*n=2-0

By itself, this prints itself 2-0 or 2 times. When concatenated to another copy of itself, the final print statement looks like $><<s%s*n=2-01, meaning it outputs itself just once (01 being octal 1). So only the final copy of the string prints twice, the others print once.

The inline assignment to n is just to get the order of operations working correctly; state isn't actually being passed from one copy to the next.

histocrat

Posted 2016-02-15T21:31:19.717

Reputation: 20 600

2

Perl 6, 58 53 bytes

Thanks to Jo King for -5 bytes.

<say "<$_>~~.EVAL for 0..!.++;">~~.EVAL for 0..!.++;

Based on Jo King's quine.

Try it online!

bb94

Posted 2016-02-15T21:31:19.717

Reputation: 1 831

2

Ruby, 55 bytes

n||=2;s="n||=2;s=%p;$><<(s%%s)*n;n=1;";$><<(s%s)*n;n=1;

Nothing very interesting here, it is just a normal ruby quine with a counter.

afuous

Posted 2016-02-15T21:31:19.717

Reputation: 429

2

JavaScript (ES6), 164 bytes

console.log((`+String.fromCharCode(96)).repeat(window.a||(a=3,5)).slice(67,-14))
console.log((`+String.fromCharCode(96)).repeat(window.a||(a=3,5)).slice(67,-14))

Works in any JS testing page or console in Firefox, assuming that the space between two console messages counts as a newline.

ETHproductions

Posted 2016-02-15T21:31:19.717

Reputation: 47 880

Many props for doing this in a general-purpose language! – Ben Leggiero – 2016-02-17T01:03:43.793

shorten window to this. – Mama Fun Roll – 2016-02-17T04:32:29.513

1

Brachylog, 20 bytes

⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅

Try it online!

Modified from this quine.

⊥                       Fail,
 ∨                      or
                w       print
  "⊥∨~kgjw₃w₅"          "⊥∨~kgjw₃w₅"
                 ₃      formatted
              gj        with itself;
                 ₃w₅    print it again at the end of the program if this route succeeds.

When this is concatenated with itself, every route except the last fails and the program moves on to the next one, executing each w₃ and backtracking past every w₅ except the very last one.

⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅

Try it online!

⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅

Try it online!

⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅⊥∨"⊥∨~kgjw₃w₅"gjw₃w₅

Try it online!

Unrelated String

Posted 2016-02-15T21:31:19.717

Reputation: 5 300

1

Python 3.8 (pre-release), 65 61 55 bytes

a=2
exec(s:='print(end="a=2\\nexec(s:=%r)#"%s*a);a=1')#

Try it online!


Python 2, 60 bytes

s='try:n\nexcept:n="s=%r;exec s"%s;print n\nprint n';exec s

Try it online!

Mukundan

Posted 2016-02-15T21:31:19.717

Reputation: 1 188

1

Japt, 40 bytes

Oo("+Q ²pT°?1:2 é4;POo("+Q ²pT°?1:2 é4;P

Test it online! Explanation to come.

ETHproductions

Posted 2016-02-15T21:31:19.717

Reputation: 47 880

1

Y

Noncompeting, 6 bytes

UCn*px

Y is a headcannon that I've had for a while, and this inspired me to write it. It is made for challenges in which sequencing is key, such as this. The code is divided into links by "node" characters. In this case, our code is put into two chains (originally), with the node being C.

U  C  n* px
1  N    2

U records a transcendental string, i.e., one that spans links. It records until it meets another U. If a U is not met by the end of the string, it wraps around. Also, U is included in the string by default. After recording the string, we proceed to the node C, which just moves us to the next link.

n pushes the number of chains. For our base case, this 2. For a sequence of K chains, there are K+2 chains, as there are K nodes. * is string repittion. p prints the entire stack (in this case, one string), and x terminates the program.

In a text:

UCn*px
U..... record that string
 C     next link
  n*   repeat that string twice.
    px print and terminate

UCn*pxUCn*pxUCn*px
U.....U            record string
 C                 next link
  n*               repeat that string four times (three Cs)
    px             print and terminate

Try it here!

Conor O'Brien

Posted 2016-02-15T21:31:19.717

Reputation: 36 228

So what would be the practical use of U besides quining? (Congrats on 7k, btw) – ETHproductions – 2016-02-17T02:09:22.013

@ETHproductions U can be used to capture a string that spans links, also able to capture and spend a link dismantles to the program. And thanks! :D – Conor O'Brien – 2016-02-17T02:11:16.603