# Question
Title: I double the source, you double the output!
Your task, if you wish to accept it, is to write a program that outputs a positive integer (higher than 0). The tricky part is that if I duplicate your source code, the output must be double the original integer.

# Rules

* You must build a **full program**. That is, your output has to be printed to STDOUT.
* The initial source must be at least 1 byte long.
* Both the integers must be in base 10 (outputting them in any other base or with scientific notation is forbidden).
* Your program must *not* take input (or have an unused, empty input).
* Outputting the integers with trailing / leading spaces is allowed.
* You may not assume a newline between copies of your source.
* This is , so the shortest (original) code *in each language* wins!
* **Default Loopholes** apply.

### Example

Let's say your source code is `ABC` and its corresponding output is `4`. If I write `ABCABC` instead and run it, the output must be `8`.

# Leaderboard

This uses uses @manatwork's layout.

```
/* Configuration */

var QUESTION_ID = 132558; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8349457; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, 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: true,
    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 = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    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 = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

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;
    if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>';
    lang = jQuery(lang).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;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

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="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">
<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>
<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>
<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>
```

# Answer
# Python 2, 33 bytes

```
print len(open(__file__).read())#

```

Try it online!

Try it doubled

# Python 3, 28 bytes

```
print(len(*open(__file__)))#

```

Try it online!

Try it doubled

## Explanation

This opens up the source code using `open(__file__)` and gets its length using `len` the `#` prevents any additional code from being read. When the source is doubled so is the length.
> 170 votes

# Answer
# Jelly, 1 byte

Try it online!

or Try it double!

I have no idea how this works, but apparently it does.
> 105 votes

# Answer
# Google Sheets, 5 Bytes

Anonymous worksheet formula that takes no input and outputs into the cell which holds the formula

```
=4/(2

```

As a single formula this evaluates to a call stack that looks a little something like

```
=4/(2
=4/(2)
=4/2
=2
2

```

However when this worksheet formula is doubled this call stack evaluates down to

```
=4/(2=4/(2
=4/(2=4/(2)
=4/(2=4/(2))
=4/(2=2)
=4/(True)
=4/True
=4/1
=4
4

```

Of course, an implication of using this method is that once this is repeated more than once, at the third and all following iterations of the problem, the call stack will reach `=4/(2=4)` and thus evaluate down to `=4/0` and throw a `#DIV/0!` error
> 84 votes

# Answer
## C (gcc), 37 bytes

```
i;main(){putchar(i+49);}/*
i=1;//*///

```

The file does not contain a trailing newline.

Doubled version, for syntax highlighting:

```
i;main(){putchar(i+49);}/*
i=1;//*///i;main(){putchar(i+49);}/*
i=1;//*///

```

TIO links: single, double.
> 53 votes

# Answer
# Python 2, 21 bytes

```
+1
if id:id=0;print 1

```

Try it online!

**Doubled:**

```
+1
if id:id=0;print 1+1
if id:id=0;print 1

```

Try it online!
> 52 votes

# Answer
# 05AB1E, 2 bytes

**Original**

```
XO

```

Try it online!

**Doubled**

```
XOXO

```

Try it online!

**Explanation**

**X** pushes **1** to the stack.
**O** sums the stack.
> 48 votes

# Answer
# Hexagony, 7 bytes

```
/)!@.).

```

Prints 1 regularly then 2 doubled.

Try it online! or Try it doubled online!

### Expanded versions:

Regular:

```
 / )
! @ .
 ) .

```

Doubled:

```
  / ) !
 @ . ) .
/ ) ! @ .
 ) . . .
  . . .

```

The regular program follows the path: `/)!.@` which increments a memory edge (all are initialised to zero) then prints its numeric value. The doubled program follows: `/.)/)!@` which increments the edge twice before printing, instead.
> 47 votes

# Answer
# Braingolf, 1 byte

```
+

```

Try it online!

Now we're talkin'!

Outputs `20`, or `40` when source is doubled.

## Explanation

`+` is of course the "sum", "add" or "plus" operator, in Braingolf, however it has dyadic, monadic and niladic functions.

When there are at least 2 items on the stack, it's dyadic, and will sum the top 2 items of the stack.

When there is only 1 item on the stack, it's monadic, and will double the item.

When there are no items on the stack, it's niladic, and pushes 20!

Why does it push 20? Well because an empty Braingolf program simply prints a newline, and the ASCII value of a newline is 10, so I figured I'd make niladic `+` push 20 so it's like it's actually being monadic on the implicit newline (even though it isn't at all)

Therefore:

```
+   No input
+   Niladic sum, Push 20
    Implicit output

```

And when doubled up:

```
++  No input
+   Niladic sum, Push 20
 +  Monadic sum, Double top of stack
    Implicit output

```
> 41 votes

# Answer
# Haskell, ~~26~~ 18 bytes

```
main=print$0
 +1--

```

Try it online!

**Doubled:**

```
main=print$0
 +1--main=print$0
 +1--

```

Try it online!

I found this version while answering the tripple version of the challenge.

---

### 26 byte version without comment abuse:

```
main|n<-1,nmain<-2=print n

```

Try it online! Prints `1`.

In the pattern guard the identifier `n` is set to `1` and `nmain` to `2`, then `print n` prints `1`.

### Double program:

```
main|n<-1,nmain<-2=print nmain|n<-1,nmain<-2=print n

```

Try it online! Prints `2`.

In the first pattern guard again `n` is set to `1` and `nmain` to `2`, however the print statement has become `print nmain`, so `2` is printed. Because identifier declarations in a pattern guard evaluate to true, the second pattern guard can never be reached.
> 29 votes

# Answer
# Mathematica, 5 bytes

```
(1+1)

```

outputs 2 and (1+1)(1+1) outputs 4

and of course (as many of you asked)

# Mathematica, 3 bytes

```
(2)

```
> 25 votes

# Answer
# Brain-Flak, 6 bytes

```
({}())

```

Try it online!

## Explanation

What this does should be pretty clear. `{}` grabs a value from the stack, which implicitly zero to begin with, `()` adds one to it and `(...)` pushes the value. On the second run since there is already a 1 on the stack this just adds another 1 to it to make two. In fact if you copy the code `n` times it will always output `n`.
> 20 votes

# Answer
# \>\<\>, ~~7~~ 6 bytes

-1 byte thanks to Teal pelican

```
\ln;
0

```

Try it online!
Try it doubled!

# Explanation

I used a `0` but I could have also used `1`-`9`, `a`-`f` because they all push a single value onto the stack.

## Not doubled:

```
\ redirects execution down
0 pushes zero onto stack; STACK: [0]
  (IP wraps around the bottom)
\ redirects execution right
l pushes stack length (1) onto stack; STACK: [0, 1]
n pops off the top value (1) and prints it; STACK: [0]
; end of execution

```

## Doubled:

```
\ redirects execution down
0 pushes zero onto stack; STACK: [0]
0 pushes zero onto stack; STACK: [0, 0]
  (IP wraps around the bottom)
\ redirects execution right
l pushes stack length (2) onto stack; STACK: [0, 0, 2]
n pops off the top value (2) and prints it; STACK: [0, 0]
; end of execution

```
> 19 votes

# Answer
# Python REPL, 2 bytes

*Also works in Pip, Dyalog APL, JavaScript REPL, J, and R*

```
+1

```

~~*I'm making a TIO right now*~~ I couldn't get python repl to work on TIO
> 18 votes

# Answer
## JavaScript, 38 bytes

```
setTimeout('alert(i)',i=1)/*
i++//*///
```

---

```
setTimeout('alert(i)',i=1)/*
i++//*///setTimeout('alert(i)',i=1)/*
i++//*///
```
> 15 votes

# Answer
## Retina, 3 bytes

```

1

```

Try it online!

Prints `2`. Doubling it prints `4`.

The `1` can be replaced with pretty much anything else.

### Explanation

```

1

```

Replaces the empty input with `1`.

```

```

Counts the number of empty matches in `1` which is two (one before the `1` and one after it).

If we double the program, we get an additional stage like the first one. This time it inserts a `1` before and after the initial one, giving `111`. When we now count the number of matches of the empty regex we get four of them.
> 14 votes

# Answer
# Java8, ~~135~~ ~~118~~ 110 bytes

**Single**, prints 8

```
interface T{static void main(String[]a){System.out.print(Byte.SIZE);}}/*
class Byte{static int SIZE=16;}/**///

```

**Doubled**, prints 16

```
interface T{static void main(String[]a){System.out.print(Byte.SIZE);}}/*
class Byte{static int SIZE=16;}/**///interface T{static void main(String[]a){System.out.print(Byte.SIZE);}}/*
class Byte{static int SIZE=16;}/**///

```

---

**Previews answer, 118 bytes**

**Single**, prints 1

```
interface T{static void main(String[]a){System.out.print(T.class.getResource("B.class")==null?1:2);}}/*
enum B{}/**///

```

**Doubled**, prints 2

```
interface T{static void main(String[]a){System.out.print(T.class.getResource("B.class")==null?1:2);}}/*
enum B{}/**///interface T{static void main(String[]a){System.out.print(T.class.getResource("B.class")==null?1:2);}}/*
enum B{}/**///

```

**How this works**

The java-compiler creates a single file for every class in the source file. Therefore i can simply check if a resource with the name B.class exists.

---

**Orginal Answer, 135 bytes**

**Single**, prints 1

```
interface T{static void main(String[]a){int i=1;try{Class.forName("B");i=2;}catch(Exception e){}System.out.print(i);}}/*
enum B{}/**///

```

**Doubled**, prints 2

```
interface T{static void main(String[]a){int i=1;try{Class.forName("B");i=2;}catch(Exception e){}System.out.print(i);}}/*
enum B{}/**///interface T{static void main(String[]a){int i=1;try{Class.forName("B");i=2;}catch(Exception e){}System.out.print(i);}}/*
enum B{}/**///

```
> 14 votes

# Answer
# Python 2, 32 bytes

```
print open(__file__,"a").tell()#

```

Try it online!

Double source code

## Explanation

This opens the source code file in append mode

```
open(__file__,"a")
```

We then find the current position in the file, this will be at the end of the file due to opening in append mode

```
open(__file__,"a").tell()
```

We print this length

```
print open(__file__,"a").tell()
```

And add a comment, so that doubling the source code does not execute more code

```
print open(__file__,"a").tell()#
```
> 14 votes

# Answer
# Neim, 1 byte

```
>

```

Simply increments the top of the stack.

The stack can be imagined as an infinite amount of zeroes to start off, so this increments zero to get one, and doubled, increments it again to get two.

Try it online!

An alternative solution:

Adds 2, instead of 1.
> 12 votes

# Answer
# Excel VBA, 12 Bytes

Anonymous VBE immediate window function that takes input from and outputs to range `[A1]`. The default value of the range `[A1]` is `""` (empty string) and after one execution the following sets this to `1` and increments by `1` with all subsequent executions.

```
[A1]=[A1+1]:

```

## Input / Output

**Single Version**

```
[A1]=[A1+1]:
?[A1]    ''# display the value of [A1] to the VBE immediate window
 1

```

**Doubled Version**

```
[A1]=[A1+1]:[A1]=[A1+1]:
?[A1]    ''# display the value of [A1] to the VBE immediate window
 2

```
> 9 votes

# Answer
# Japt, 1 byte

```
Ä

```

Try it online!
Try it doubled!
Repeats even longer, too!

Rather simple. Japt transpiles to JS, and `Ä` transpiles to `+ 1`, so `ÄÄ` transpiles to `+ 1 + 1`, and so on.
> 8 votes

# Answer
# Husk, 3 bytes

```
|1"

```

Try it online!

An original idea, for what I have seen in other answers.

### Explanation

`|` in Husk is an "or" operator which returns its second argument if it is thruthy, otherwise the first argument. When applied to arguments of different types it firstly transform all of them into numbers: the transformation for strings (and lists in general) is done by computing their length.

In the original program we apply `|` to 1 and an empty string, which gets converted to 0: the result is 1.

In the doubled program we apply `|` to 1 and the string "|1", which gets converted to 2: the result is 2.
> 8 votes

# Answer
# SHENZHEN I/O Assembly, ~~35~~ 19 bytes, 3¥

-16 bytes, thanks @l4m2!

```
@add 7
@mov acc x1

```
> 8 votes

# Answer
# CJam, 3 bytes

```
5],

```

Try it Online

Encapsulate 5 in array. Return length of array. When you duplicate code, the previously returned length, 1, is already on the stack, so you get an array of \[1,5\], which returns length 2.
> 7 votes

# Answer
# Ruby, 16 bytes

```
+1
p&&exit
p=p 1

```

Try it online!

### Doubled:

```
+1
p&&exit
p=p 1+1
p&&exit
p=p 1

```

Try it online!Try it online!
> 7 votes

# Answer
# Braingolf, 1 byte

```
+

```

Try it online!

Try it doubled!

I don't know how this works, most important it does!
> 7 votes

# Answer
# Befunge-98, 5 bytes

```
90g.@

```

Try it online!

`g` gets the character value at coordinate (9, 0) in Funge-Space; `.` prints it as an integer, and `@` halts the program. In the un-doubled version, (9, 0) is out of bounds of the program, and Funge-Space outside the program is initialized to the default value of a space, so we print 32. In the doubled version, (9, 0) is the `@` character, so we print 64.
> 7 votes

# Answer
## Wumpus, 4 bytes

```
" O@

```

Try it online!

```
" O@" O@

```

Try it online!

The normal code prints `32` and the doubled one prints `64`.

### Explanation

`"` works like it does in many other Fungeoids: it toggles string mode, where each individual character code is pushed to the stack, instead of executing the command. However, in contrast to most other Fungeoids, Wumpus's playfield doesn't wrap around, so the IP will instead reflect off the end and bounce back and forth through the code.

So for the single program, the following code is actually executed:

```
" O@O " O@

```

The string pushes `32, 79, 64, 79, 32`. Then the space does nothing, the `O` prints `32`, and the `@` terminates the program.

For the doubled program, the string is instead terminated before the IP bounces back, so the code is only traversed once:

```
" O@" O@

```

This time, the string pushes `32, 79, 64`, the `O` prints the `64` and the `@` terminates the program.

This appears to be the only 4-byte solution.
> 7 votes

# Answer
# SOGL V0.12, 1 byte

```
I

```

Try it Here!, or try the duplicated version
`I` is the increase command, and as no input is provided, it increases 0 (and then in the duplicated program, 1 to 2)
> 6 votes

# Answer
# ,,,, 2 bytes

```
1∑

```

## Explanation

```
1∑

1   push 1
 ∑  pop everything and push the sum of the stack

```
> 6 votes

# Answer
## JavaScript (ES6), 63 bytes

Prints either `1` or `2` through an alert dialog.

### Original

```
clearTimeout((t=this).x),t.x=setTimeout(`alert(${t.n=-~t.n})`);
```

### Doubled

```
clearTimeout((t=this).x),t.x=setTimeout(`alert(${t.n=-~t.n})`);clearTimeout((t=this).x),t.x=setTimeout(`alert(${t.n=-~t.n})`);
```
> 6 votes

# Answer
## Batch, 13 bytes

```
@echo %~z0
:

```

Explanation: `%~z0` expands to the length of the source file, so doubling the file simply doubles the length. The second line defines an empty label, which does nothing. When the file is doubled, it becomes a label named `@echo %~z0` instead, while the third line is another empty label.
> 6 votes

# Answer
# QBasic,  ~~44~~  28 bytes

There is **no** newline at the end. Outputs `4` when single, `8` when doubled.

```
4
READ x,y
?x+y
END
DATA 4,0

```

### Explanation

For the single version:

* `4` is a line number.
* `READ x,y` takes the first two values from the `DATA` statement and stores them in `x` and `y`. Thus, `x` gets `4` and `y` gets `0`.
* `?x+y` adds the two numbers and prints them.
* `END` exits the program.

In the doubled version, the `DATA` statement becomes `DATA 4,04`, which assigns `4` to both `x` and `y`, thus making `x+y` equal `8` instead.
> 6 votes

# Answer
# Python, 15 bytes

```
1or exit(2)
0/0

```

Outputs via exit code. Divides by zero and exits with code 1. Doubled:

```
1or exit(2)
0/01or exit(2)
0/0

```

Calls `exit(2)` and exits with code 2.

# Python?, 9 bytes

```
';exit(2)

```

Throws a syntax error and exits with code 1. Doubled:

```
';exit(2)';exit(2)

```

Calls `exit(2)` and exits with code 2.
> 6 votes

# Answer
# Befunge-98 (PyFunge), 3 bytes

This answer draws heavy inspiration from this one, go vote them up too!

```
".@

```

Try it online! or Try it online doubled!

## Explanation

When wrapping back around to the beginning of the source in quote mode, this Befunge-98 interpreter pushes at least 1 space (ASCII 32). If we print this value and exit, we get 32.

If we double the source code, we don't wrap back around, but rather end quote mode with the duplicated `"`. This means that the last character pushed is not a space, but a `@`, with (drumroll) **ASCII 64**! A complete coincidence that the character that ends the program in Befunge is twice that of a space.
> 6 votes

# Answer
# Perl 5, 7 bytes

With `-M5.10.0`

```
say
+1#

```

Try it online!

Doubled:

```
say
+1#say
+1

```

-2 thanks to Ton Hospel
> 6 votes

# Answer
# PHP, 30 bytes

Original

```
<?=strlen(file(__FILE__)[0]);#

```

Try it online!

# PHP, 60 bytes

doubled

```
<?=strlen(file(__FILE__)[0]);#<?=strlen(file(__FILE__)[0]);#

```

Try it online!
> 5 votes

# Answer
# J, 2 bytes

```
+1

```

`+1` is 1, and `+1+1` is 2.

Fun fact: since J's operator precedence is just right-to-left, this is interpreted as `+(1+1)`
> 5 votes

# Answer
# Hexagony, 4 bytes

```
[@!)

```

Try it online! or Try it doubled online!

This solution was found using brute force by Martin and prints `002` regularly and `4` when doubled. This is the only 4 byte solution, but there are several hundred 5 byte solutions.

### Expanded versions:

Regular:

```
 [ @
! ) .
 . .

```

Doubled:

```
  [ @ !
 ) [ @ !
) . . . .
 . . . .
  . . .

```

Hexagony has 6 instruction pointers, one starting at each corner of the hexagon and initially moving "clockwise." The `[` instruction causes the interpreter to change IP one left. The first program leads us on a bit of a merry go around, executing: `[![.!.)[...)!@` which results in the `002` output. The other program is a bit more tame, executing: `[))[..)...[.......)!@` which results in the clean `4`.
> 5 votes

# Answer
# JavaScript (REPL), 2 bytes

So long as putting code in the console counts as a full program:

```
+1

```
> 5 votes

# Answer
# Google Sheets / Excel, 2 Bytes

***The Trival Solution***

```
+7

```

Or

```
+n

```

<sub>*Such that `n` is an integer between `1` and `9`, inclusive.*</sub>

Google Sheets and Excel both will take a leading `+` or `-` and evaluate them down to `=` or `=-`, respectively if they are the leading character of a cells formula text. As a result, `-n`, such that `n` is an integer between `1` and `9`, inclusive, is a valid negative equivalent of the above

As a single formula this evaluates to a call stack that looks a little something like

```
+7
=7
7

```

However when this worksheet formula is doubled this call stack evaluates down to

```
+7+7
=7+7
=14

```
> 5 votes

# Answer
# Whispers v2, 23 bytes

```
+1
> 1
>> Output 3
>> 1

```

Try it online! or Try it online doubled

Outputs `1` normally and `2` when doubled.

## How it works

### Normal

Whispers only recognises lines that match one of a certain set of regexes. In the normal version, this reduces the program down to

```
> 1
>> Output 3

```

(i.e. the first and last lines don't match any regexes). The program then runs the last line, `>> Output 3`. This calls the 3rd line and outputs the result. However, as the reduced program only has 2 lines, this indexes modularly, returning the \\$3 \mod 2\\$th line (i.e. the first line), `> 1`. This is a basic nilad line which returns \\$1\\$, which is then outputted.

### Doubled

The doubled program is

```
+1
> 1
>> Output 3
>> 1+1
> 1
>> Output 3
>> 1

```

Removing lines which don't match any regex, we get

```
> 1
>> Output 3
>> 1+1
> 1
>> Output 3

```

Again, the last line is run, telling the program to output the result of line 3. This time however, we do have a line 3 to output: `>> 1+1`. This does return \\$2\\$ but not because it evaluates \\$1+1\\$. Rather, it adds the value of line 1 to itself, which happens to be \\$1\\$.

Interestingly, this means that by changing `> 1` to `> n` where \\$n\\$ is any number, the programs output \\$n\\$ and \\$2n\\$. For example

```
+1
> π
>> Output 3
>> 1

```

outputs \\$\pi\\$ normally or \\$2\pi\\$ when doubled
> 5 votes

# Answer
# vJASS (Warcraft 3), 150 bytes

```
//! inject main
set bj_randDistCount=bj_randDistCount+1
call ClearTextMessages()
call BJDebugMsg(I2S(bj_randDistCount))
//! dovjassinit
//! endinject

```

prints `1`

```
//! inject main
set bj_randDistCount=bj_randDistCount+1
call ClearTextMessages()
call BJDebugMsg(I2S(bj_randDistCount))
//! dovjassinit
//! endinject
//! inject main
set bj_randDistCount=bj_randDistCount+1
call ClearTextMessages()
call BJDebugMsg(I2S(bj_randDistCount))
//! dovjassinit
//! endinject

```

prints `2`

**Explanation:**

* `bj_randDistCount` is a non-constant integer variable. Also, it has the shortest variable name you may find in blizzard.j.
* `ClearTextMessages()` clears all text messages in your in-game screen.
* `I2S(int whichInt) -> string` converts from `integer` to `string`
* `BJDebugMsg(string str)` prints text on your in-game screen.
> 5 votes

# Answer
# Pyth, 3 bytes

```
s[1

```

sums a list

Try it!

Double-try it
> 4 votes

# Answer
# Charcoal, 7 bytes

```
ＰＩＬ⊞Ｏυω

```

Try it online! Appends the empty string to the empty list and prints the length of the result (1) in decimal without moving the cursor. When doubled, the empty string gets appended twice so the length is now 2, which then overwrites the 1. Try it online! In verbose syntax, this is `Multiprint(Cast(Length(PushOperator(u, w))));`.
> 4 votes

# Answer
# Self-modifying Brainfuck, 7 bytes

```
<-<201/

```

or doubled:

```
<-<201/<-<201/

```

Outputs 1 and 2 respectively.

The idea is simple: we use Self-modifying Brainfuck's self-modifying capability to make sure that the printing command only happens at the end of the full program.

Try it online!

Try it online, doubled!
> 4 votes

# Answer
# Little Man Computer, 20 bytes (source)

```
LDA 1
ADD 5
OUT
HLT

```

Online Emulator (Flash)
> 4 votes

# Answer
# bash, 16 bytes

a simple one:

```
wc -c<$0;exit 0;

```

First program: Try it online!

Second program: Try it online!
> 4 votes

# Answer
# Python 2, 24 bytes

```
'+1#';exec'print 1''' ''

```

Abusing string syntax.
> 4 votes

# Answer
# Python 2, 27 bytes

```
+7
try:_
except:_=7;print _

```

Try it online!

Try it doubled!
> 4 votes

# Answer
# Powershell, 2 bytes

```
+1

```

It's a full Powershell program. The output has printed to STDOUT.
> 4 votes

# Answer
# Brachylog, 8 bytes

```
w₆-₇ℕ~l"

```

Try it online! Try it online!Try it online!

Although Brachylog has implicit *function* output, full programs won't automatically print without being given arguments, making this challenge a bit more interesting.

```
w₆          Declaratively write a number
  -₇        which minus 7
    ℕ       is a whole number (so length won't throw an error)
     ~l     equal to the length of
       "    an (implicitly terminated) empty string.

```

Doubling the code turns the empty string into a string of length 7, changing the printed output from 7 to 14.
> 4 votes

# Answer
# K (ngn/k), 3 bytes

```
+/1

```

Try it online!

---

`+/1` \- sum 1. returns `1`

~~`+/1+/1` \- rightmost `+/1` evaluates to 1 (as above), giving `+/1 1`, i.e. sum the vector `1 1`. returns `2`~~

EDIT: above is incorrect (written when i had a bad understanding of how k is parsed). corrected explanation:

`+/1+/1` is `+/(1+/1)`, where the parenthesized expression is "sum 1 with a seed of 1", which evaluates to 2, which is passed to `+/`, returning 2
> 4 votes

# Answer
# Vyxal, 1 byte

Try it Online!

Doubled:

```
››

```

Try it Online! Try it Online!

Increments the top of the stack. Since the stack is empty, 0 is incremented instead, outputting 1. When doubled, 0 is incremented twice, outputting 2.
> 4 votes

# Answer
# , 4 bytes

```
øß.

```

Try it online!

Or Try it doubled!
> 3 votes

# Answer
# C++, ~~158~~ ~~138~~ 123 bytes

20 byte savings thanks to @zbw

I'm sure there's a more efficient way to do it in C++ but this is all I could think of.

```
#include <iostream>
#ifdef m
#define m a r;
#else
int v;
#define m struct a{a(){++v;}}q;int main(){std::cout<<v;}
#endif
m

```

How it works: On the first instance, it declares a global int `v` initialized to 0 and a struct `a` which increments every time an `a` is instanced. It instances an `a`, and prints the value of the member.

On the second instance of the source, it just instances another `a`.
> 3 votes

# Answer
# PHP, 16 bytes

Does not actually satisfy the rules because of PHP warnings.

```
ob_start(bcadd);

```

Test it online.
> 3 votes

# Answer
# Cubix, 6 bytes

```
@1u.2O

```

When run, this pushes `1`, `u`-turns, `O`utputs as a number, and h`@`lts:

```
  @
1 u . 2
  O

```

When doubled, the cube is

```
    @ 1
    u .
2 O @ 1 u . 2 O
. . . . . . . .
    . .
    . .

```

which simply pushes `2`, `O`utputs as a number, and h`@`lts.

Try it online!
> 3 votes

# Answer
# Ruby (REPL), 3 2 bytes

Must be run interactively for the implicit output:

```
+2

```

Outputs 2.

Doubled:

```
+2+2

```

Outputs 4.

<sub><sub>2 and 4 are more interesting than 1 and 2</sub></sub>
> 3 votes

# Answer
# R, 2 bytes

```
+1

```

prints 1 and when doubled

```
+1+1

```

prints 2
> 3 votes

# Answer
# Fourier, 3 bytes

```
@^o

```

**Try it Online!**

**Try it Doubled!**

***Explanation:***

Undoubled:

```
@    - Clear screen
 ^   - Increment the accumulator (initialised to zero)
  o  - Output the value of the accumulator

```

Doubled:

```
@       - Clear screen
 ^      - Increment the accumulator (initialised to zero)
  o     - Output the value of the accumulator
   @    - Clear screen
    ^   - Increment the accumulator
     o  - Output the value of the accumulator

```
> 3 votes

# Answer
# Python 3, 33 bytes

Cheating a little:

```
id=print('\r',1+(not id),end='');

```
> 3 votes

# Answer
# R, 2 bytes

```
+T

```

Never expected to codegolf this much in R. Due to the `+`, R changes the `T` for a numeric, using `1` as default.
> 3 votes

# Answer
# PHP, 26 bytes

```
<?=ob_clean()+ob_start()?>

```

Try it online!

Try it doubled!

**Explanation**

PHP can use an output buffer. This buffer has the facility to be cleaned without its contents ever being sent.

When the script is run just once, the output buffer has not initially been started and so cannot be cleaned, and `ob_clean()` returns `false`. The buffer is then successfully started and `ob_start()` returns `true`. `false + true` is really `0 + 1`, and so the script echoes `1` into the buffer and ends with the buffer being outputted.

If the script is doubled then this first `1` is not output but is still in the buffer when the second half of the doubled code starts. The output buffer is now cleaned, the `1` is lost, and `ob_clean()` this time returns `true`. Another output buffer is then started (they are, in fact, stacked) and `ob_start()` again returns `true`, so this time we have `true + true`, which is `1 + 1`, and so `2` is sent to the output buffer and then on to the actual output when the script ends.
> 3 votes

# Answer
# Proton, ~~63~~ ~~53~~ 52 bytes

```
+(x? !print(x=2):0)
while(x? x-2? print(1):0:(x=1))x

```

Prints `1`.

Try it online!

**Doubled:**

```
+(x? !print(x=2):0)
while(x? x-2? 0:print(1):(x=1))x+(x? !print(x=2):0)
while(x? x-2? 0:print(1):(x=1))x

```

Prints `2`.

Try it online!
> 3 votes

# Answer
## Rust, 62 bytes

```
fn main(){let a=include_str!("a.");print!("{}",a.len()-1)}//

```

What's happening is the file is including itself as a string during compiletime, and getting the length of itself.

When appended, the extra code is commented out, but still effects the length of the file.

Only works if the file name is 'a.'

## Secondary Solution, 63 bytes

```
fn main(){let a=include_str!(file!());print!("{}",a.len()-1)}//

```

This solution doesn't use a hardcoded filename, losing 1 byte.
> 3 votes

# Answer
# Underload, ~~15~~ ~~13~~ 8 bytes

<sup>-2 thanks to Martin Ender</sup>

<sup>-5 thanks to Ørjan Johansen</sup>

```
(1)\r2)S(

```

The `\r` in the code should be a literal carriage return character.

There's no way for spec-complaint Underload to actually solve this challenge. This submission uses several tricks to do it:

* `stringie`, the TIO interpreter, ignores unmatched close brackets and segfaults on unmatched open brackets, which is allowed.
* Using `\r` allows us to overwrite whatever has already been output with new output. This requires a terminal for which `\r` clears the line, rather than just allowing it to be overwritten with new text.
> 3 votes

# Answer
# bash builtins only - 21 bytes

The `X` file:

```
trap "echo $[++i]" 0;

```

`EXIT` –\> `0`
`$((...))` -\> `$[...]`
;-)

---

# bash builtins only - 26 bytes

Straight forward while using only `bash` builtins.
IOW: No external helpers.

The `X` file:

```
trap "echo $((++i))" exit;

```

(No final newline.)

Proof of the pudding:

```
$ bash <(cat X)
1
$ bash <(cat X X)
2
$ bash <(cat X X X)
3

```

Concat with or without newline inbetween:

```
$ cat X X ; echo # added echo compensates missing \n only
trap "echo $((++i))" exit;trap "echo $((++i))" exit;
$ bash <(cat X X)
2
$ cat X <(echo) X ; echo
trap "echo $((++i))" exit;
trap "echo $((++i))" exit;
$ bash <(cat X <(echo) X)
2

```
> 3 votes

# Answer
# Implicit, ~~2~~ 1 byte

<sup>-1 thanks to ASCII-only</sup>

```
.

```

:)
> 3 votes

# Answer
## Keg, 2 bytes

This indeed works. (Works in the old TIO version, I don't know which version is this)

```
1+

```

## A version that I can understand, 4 bytes

```
1(+)

```

Explanation:

```
1#    Push 1 onto the stack
 (+)# Add the whole stack together

```
> 3 votes

# Answer
# GAS x64 Assembly (Linux, GCC 10.1): ~~143 107 104~~ 100 bytes

Assembled with `-no-pie -nostdlib`.

## Original code

```
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall
.ifndef b
ja b
.endif
a=.
.ascii " 1\b2"
a=a+2
b=.;

```

## Annotated Single

Single one segfaults, printing `1` to the terminal with a leading space. (Rules say this is OK.)

```
// Print 2 characters from a
// Use lea so we don't need $.
// We are optimizing for assembly, not machine code
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall

// Since b hasn't been defined yet, this gets left in, jumping to b
// (Pseudo-op is needed when we double)
.ifndef b
// Since gcc clears all flags at the start
ja b
.endif

// You can define re-writable labels like this too!
a=.
.asciz " 1\b2"

// Increase a by 2 (needed in double version)
a=a+2

// Attempt to jump here, but crash because there's no executable code
// Also, intentional semicolon to separate double version
b=.;

// Let crash

```

Gives the following:

```
 1[1]    74584 segmentation fault (core dumped)  ./a.out

```

The first `1` is the program output. Since Segfault stuff isn't program output, we're good.

## Annotated Double (fluff removed)

Takes advantage of the backspace character, overwriting the `1` with a `2`. (Also segfaults)

```
// Print 2 characters
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall

// Skip to b
ja b

// Every reference to a prior to this line points here
a=.
.ascii " 1\b2"
// Now point a to \b for next usage
a=a+2

// Now print the last two characters from new a
b=.
lea a,%rsi
lea 2,%dx
lea 1,%di
lea 1,%ax
syscall

// Crash

```

```
 2[1]    391605 segmentation fault (core dumped)  ./a.out

```
> 3 votes

# Answer
# Flurry, 6 bytes

```
([])[]

```

### Verification

```
$ echo -n "([])[]" | wc -c
6
$ ./flurry -nin -c "([])[]"
1
$ ./flurry -nin -c "([])[]([])[]"
2

```

Found by accident (kind of). Single copy returns 1, two copies returns 2.

`(...)` pushes its content to the stack, and `[]` evaluates to the stack height in Church numeral. Juxtaposition is function application (which is reversed exponentiation for Church numerals), so the entire code evaluates like the following:

```
Single copy
([])    Evaluate to stack height (0), and push 0 to the stack
[]      Evaluate to stack height (1)
        Function application gives 1 ** 0 = 1

Two copies
([])[]  Evaluate as above; evaluates to 1 and pushes a 0
([])    Evaluate to stack height (1), and push 1 to the stack
        Function application gives 1 ** 1 = 1
[]      Evaluate to stack height (2)
        Function application gives 2 ** 1 = 2

```

---

Honorable mention goes to the literal 2:

# Flurry, 10 bytes

```
{<({}){}>}

```

Returns 2 as-is, and returns 4 (`= 2**2`) when doubled.

I call it a "literal" because it is a single pure `{...}` node (so it can be placed in larger programs without modification), and any number constant can be constructed using the same pattern.

```
{       Start a lambda; implicitly pushes its argument before running
 <      Start a function composition group
  ({})  Pop the argument {} and push again (...)
  {}    Pop the argument again
 >      End composition group
}       End lambda

Evaluates to the following lambda function
\f. f ∘ f
= \f. \x. f (f x)
= 2

```

To create a higher number `n`, we can place `n-1` copies of `({})` before `{}`, which then evaluates to `\f. f ∘ f ∘ ... ∘ f` (`n` copies), which is precisely `n` in Church numeral. For example, 3 can be written as `{<({})({}){}>}`, which is similar to what I previously used.
> 3 votes

# Answer
# Add++, 11 bytes

```
o
+1
o:""
o

```

Try it online!

The variable `o` isn't used, so the program is essentially equal to:

```
o
+1
o

```

All you need to know is that `o` outputs the active variable, which starts at `0`, and that `+1` increments the active variable. This program is equivalent to this one.

# Doubled

```
o
+1
o:""
oo
+1
o:""
o

```

Try it online!

`o` is an empty string, so we can disregard the `oo`. The `o` variable isn't used anywhere else, so we can ignore those, and we get this program:

```
o
+1
+1
o

```

This program is equivalent to this one.
> 3 votes

# Answer
# x86 Linux machine code, ~~16~~ 15 bytes

`XX` is a linker placeholder for 15 bytes past the first instruction. It can still be repeated.

Place it in its own write+execute section.

```
00000034: 04 04 b9 XX XX XX XX 80 01 34 43 42 cd 80 cc     .........4CB...

```

```
        // We modify bytes "in" this section
        .section ".wtext","awx",%progbits
        .intel_syntax noprefix
        .globl _start
_start:
       // Assumes the default Linux startup state,
       // where all regs except ESP are zero.
       // EAX = 4
       // This is encoded as 04 04, which is important.
       add     al, 4
       // Set ECX to point to....nothing?
       mov     ecx, offset 1f
       // Add '4' into.... nothing?
       add     byte ptr [ecx], '4'
       // EBX = 1
       inc     ebx
       // EDX = 1
       inc     edx
       // write(1, 2f, 1)
       int     0x80
       // Exit by raising a SIGTRAP (#BP).
       // We must exit: if we double the program, it will run twice.
       int3
1:
       // Nothing

```

This abuses the Linux program startup state where all registers are zero, and how it doesn't get mad if you read or write a few bytes past the end of a section.

Specifically, Linux will zero pad the section to a page boundary. It doesn't care about it until you go too far out of bounds.

So label 2 when we only have one copy is this:

```
2:
       .byte 0x00

```

But when we double the code, we have this:

```
2:
       add     al, 4

```

Let's expand the encoding:

```
2:
       .byte   0x04, 0x04

```

So, when we have one copy, it is 0, and when we double it, we get 4. So all we have to do is add ASCII 4 to get '4' on a single and '8' on double.

Try it online! (Single)

Try it online! (Double)
> 3 votes

# Answer
# Desmos, 3 bytes

## Original

```
1+0

```

## Doubled

```
1+01+0

```

Try It On Desmos!

Any answer in the form `a+0`, where `a` is a positive integer, will work. For example, `4444+0` outputs `4444` and `4444+04444+0` outputs `8888`.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 13 bytes

There is already another Mathematica answer, but this one is a full program instead of an REPL snippet.

```
Print@Depth@a

```

Try it online!

The depth of the expression `a` is `1`.

**Doubled:**

```
Print@Depth@aPrint@Depth@a

```

Try it online!

`aPrint@Depth@a` is `aPrint[1]`, which has depth `2`.
> 3 votes

# Answer
# K (ngn/k), 2 bytes

```
#2

```

Try it online!

`#2`: length of `2`, which is 1

`#2#2`: length of two copies of `2`, which is 2

This solution polyglots with J. Try it online!
> 3 votes

# Answer
# Python 3, ~~74~~ ~~67~~ 57 bytes

Quick and dirty... Output via text file is allowed per meta.

```
try:f+=[2]
except:f=[2]
open('o','w').write(str(sum(f)))

```
> 2 votes

# Answer
# Klein, 5 + 3 = 8 bytes

```
\+@
2

```

Single, Double

The single program puts a two on the stack and attempts to add it. There is nothing to add so it is a noop and outputs `2`. In the doubled program the `\+@` section is not encountered but we do hit an additional `2` meaning that when we add again we add two `2`s instead of a `2` and a zero. This results in `4`. `2` can be replaced with any single digit number and this will still work, `+` can also be replaced with a `*` as long as we keep the `2`, and `\` can be replaced with a `/`.
> 2 votes

# Answer
# Bash + coreutils, 43 bytes

```
x=$(history|cut -c 8-|tail -1);echo ${#x};#

```

# Explanation

Outputs the length of the last command entered. Uses the same concept as the Python and PHP solutions to prevent execution of any further copies (finishes with a comment marker, so anything after it is ignored). Length of the command will be doubled when it is written twice, hence the output.
> 2 votes

# Answer
# \>\<\>, ~~24~~ 20 bytes

```
\0r+n;
"

"
0
8
p
1

```

Try it online!

Uses the same trickery as my original 24 byte answer, just outputs 1 and 2 instead of 2/4.

---

```
\0r+n;
"

"
0
a
p
1
1
+

```

Try it online!

And try the double!

This starts at the `\`, diverts code execution down, does its trick\*, pushes two 1's, then wraps around again. It hits the `\` again, but from a different angle now, so the `0r+n` gets executed and `;` terminates the program.

(\*) Note that the trick is to alter the source code by turning the instruction at 0, 10 into a space instead of a `\` when the code is doubled.

When the code hits `n;` (print number and quit), the top of the stack is either 2 or 2, 2. In each case, a 2 gets printed, So we need to add 2 and 2 in case of the double source code, but we don't have a second stack item on the regular run. This is solved by `0r`: push a zero and reverse stack. We now either sum 2 and 2 and ignore the (now bottom) 0, or we add 2 and 0.
> 2 votes

# Answer
# Common Lisp REPL, 25 bytes

```
(if(boundp'z)6(setq z 3))

```

Try it online!

Try the double version online!
> 2 votes

# Answer
# Carrot, 4 bytes

```
2^F*

```

Outputs 2 normally and 4 when doubled.

Explanation normal:

```
2 //Input on the stack
^ //Convert to operations mode
F //Convert stack to float mode
* //Multiply stack by an empty argument (don't do anything)
  //Implicit output of stack

```

Explanation doubled:

```
2  //Input on the stack
^  //Convert to operations mode
F  //Convert stack to float mode
*2 //Multiply stack by 2
^  //Convert to string stack mode
F* //Place the literal "F*" onto the string stack
   //Implicit output of float stack

```

In Carrot there are three stack modes: string, float and array. Only the current stack modes stack is output at the end of the program.
> 2 votes

# Answer
# PowerShell, 47 bytes

```
(gc $MyInvocation.MyCommand.Definition).Length#

```

Try it online! (Output: 47)

Output:

```
47

```

## Explanation

```
(gc $MyInvocation.MyCommand.Definition).Length#
 ^  ^             ^         ^           ^     ^^
 |  |             |         |           |     ||
 |  |             |         |           |     |No newline and/or whitespace at the end
 |  |             |         |           |     |
 |  |             |         |           |     Hash - Marks all next text as comment
 |  |             |         |           |
 |  |             |         |           Length - Returns length of string
 |  |             |         |
 |  |             |         Definition - Returns full path to script file
 |  |             |
 |  |             MyCommand - Contains information about the script file
 |  |
 |  $MyInvocation - Auto variable containing information about the current script
 |
 Alias for Get-Content commandlet, returns content of file

```
> 2 votes

# Answer
# TI-Basic, 4 bytes

Fairly simple. I'm wondering if there are many alternate solutions.

```
1:2Ans       --> prints 2
1:2Ans1:2Ans --> prints 4

```

Alternate solutions

```
1+0 <-- 3 bytes based on @alexanderbird's answer

```
> 2 votes

# Answer
# Java, 121 bytes

### Original Code:

```
class A {static int n=1;public static void main(String[]a){System.out.print(n);}}/*
class B extends A{static{n++;}}//*///

```

### Duplicated Code:

```
class A {static int n=1;public static void main(String[]a){System.out.print(n);}}/*
class B extends A{static{n++;}}//*///class A {static int n=1;public static  void main(String[]a){System.out.print(n);}}/*
class B extends A{static{n++;}}//*///

```

Technically you have to run the main method of A the first time, and of B the second time. Still, it's one program.
> 2 votes

# Answer
# PHP, ~~48~~ ~~47~~ 43 bytes

```
<?php ob_end_clean();ob_start();echo++$i;?>

```

Try it online!

Result: 1

There's 2 PHP answers on here already, one of them looks like a port from Python and the other one breaks the error rule imo, so there's my shot at it.

Doubled:

# PHP, ~~96~~ ~~95~~ 86 bytes

```
<?php ob_end_clean();ob_start();echo++$i;?><?php ob_end_clean();ob_start();echo++$i;?>

```

Try it online!

Result: 2

Explanation:
ob\_end\_clean() once called, turns off the ob\_start(). However, ob\_end\_clean will only clean items that started within the ob\_start(). So to counter act this, we clear it first, run ob\_start() then execute our counter.
> 2 votes

# Answer
# , 2 bytes

```
*2

```

Try it online!

A "monadic" (one argument) `*` means "first", and a dyadic (two argument) `*` is multiplication.
Therefore `*2` is seen as "the first element of a list containing 2", which is `2`.
`*2*2` first evaluates `2*2`, which is `4`, and then evaluates `*4`, which is `4`.
> 2 votes

# Answer
## Perl, 15 bytes

```
++$_,exit print

```

Try it online!

**Doubled:**

```
++$_,exit print++$_,exit print

```

Try it online!

Increments `$_` to 1 in the first instance, `print` outputs `$_` by default, and we pass that as an argument to `exit`. When doubled, `print` explicitly outputs `++$_` which is now `2`.
> 2 votes

# Answer
# Carrot, 5 bytes

```
^F+1

```

Explanation:

```
^ --- Stack mode
F --- Convert to float
+1 --- Add 1 to the previous result
<space> -- I have no idea

```
> 2 votes

# Answer
# Brian & Chuck, 15 bytes

```
>>.>?2<<<?1
!>.

```

Try it online!

```
>>.>?2<<<?1
!>.>>.>?2<<<?1
!>.

```

Try it twice!

---

This was my first attempt at learning Brian & Chuck. I took a short break after writing this answer and I've forgotten most of how it works.

It relies on the facts that:

* Chuck's 4th value is zero in the single program and non-zero in the double
* `.` is a no-op in Brian's instructions, but prints in Chuck's instructions
* In the double program, Brian's instructions are appended to Chuck's, but Chuck's are ignored because they're on the 3rd line.
> 2 votes

# Answer
# Ly, 6 bytes

```
1&+s>l

```

Try it online!

**breakdown**

```
Command Operation               stack content   cell
1       push 1                  1
 &+     push sum of the stack   1,1
   s    pop to backup cell      1               1
    >   next stack                              1
     l  push backup cell        1               1
            implicit output of stack
            - or second execution:
1       push 1                  1,1             1
 &+     push sum of the stack   1,1,2           1
   s    pop to backup cell      1,1             2
    >   next stack                              2
     l  push backup cell        2               2
            implicit output

```
> 2 votes

# Answer
# TI-BASIC, 2 bytes

```
2!

```

There are also 5 more solutions, of equal or greater length.

```
(2

abs(2

int(2

iPart(2

round(2

```

These all work on the same principle. Something evaluates to 2, and twice it is merely 2\*2.
> 2 votes

# Answer
# CJam, 4 bytes

```
1]:+

```

Try it online!

Explanation:

```
1]:+

1    push 1 to stack
 ]:+ sum stack

```

# CJam, 1 byte

```
)

```

Try it online!

I'd say this uses 2 bytes since there is a 0 in the header. I don't know if this is a valid loophole or forbidden.
> 2 votes

# Answer
# Cubix, 4 ~~5~~ bytes

Of course as soon as I look at it again this presents itself. Not as nice as the previous, but shorter.

```
))O@

```

Try it online!

```
  )
) O @ .
  .

```

Increment, output and exit.

```
))O@))O@

```

Try it online!

```
    ) )
    O @
) ) O @ . . . .
. . . . . . . .
    . .
    . .

```

Increment twice, output and exit
> 2 votes

# Answer
# Julia 0.6, 41 bytes

My first two ideas were already done in python answers (check file length, use a finalizer on an object). So here I check if π is an integer to gate the code that sets π=1 and registers the print to occur on exit. Then just double π each time.

```
π%1>0?(π=1;atexit(()->show(π))):π*=2;

```

Try it online!

Try twice it online!
> 2 votes

# Answer
# Julia 0.6, 24 bytes

Riffing off of lungj's Python 3 answer. This works on my terminal on my mac, but not on TIO. The `\r` should reset back to the start of the line, so it always overwrites the previous output. Uses string interpolation with `$` to execute `π=2π÷1` which doubles π and uses integer division to round it to an integer. It does output "WARNING: imported binding for π overwritten in module Main" as well, but thats not an error, and is pretty close to a compiler warning.

```
print("\r$(π=2π÷1)");

```

Try it online!
> 2 votes

# Answer
# Wumpus, 6 bytes

```
$@1$O+

```

Try it online!

Doubled:

```
$@1$O+$@1$O+

```

Try it online!

The first program pushes 1, adds the top two items on the stack (the 1 and an implicit 0), reflects off the end of the line, outputs and exits.

The second program does the same, except it adds *two* 1s to the stack, meaning it prints 2 and exits. This works for any number from 1-9.

A shorter solution may exist that takes advantage of two lines making the pointer bounce differently.
> 2 votes

# Answer
# ///, 20 bytes

Prints 1:

```
/\\1\//\/1\/2\/\//\1

```

Try it online!

Duplicated prints 2:

```
/\\1\//\/1\/2\/\//\1/\\1\//\/1\/2\/\//\1

```

Try it online!

# How it works

* The initial substitution `/\\1\//\/1\/2\/\//` (in both versions) searches for the string `\1/` in the remainder and replaces it by `/1/2//`.
* In the single program there is no such string, and nothing is replaced. The program is now reduced to the final `\1`, which prints a `1`.
* In the duplicated program `\1/` crosses the boundary between the copies.
    + After substituting, the remaining program becomes `/1/2//\\1\//\/1\/2\/\//\1`, which is the substitution `/1/2/` followed by the single program.
    + This substitution then replaces every `1` in the single program by `2`, giving `/\\2\//\/2\/2\/\//\2`.
    + This then runs pretty much like the single program does, except for printing `2` instead of `1`.
* The normally redundant `\` before the final `1`, and the corresponding `\\` in the initial substitution, are needed because without them, the substitution would be applied again to the `/1/2/` result, causing an infinite loop.
> 2 votes

# Answer
# Momema, 12 bytes

```
00 1+1*1-8*1

```

Try it online! This outputs `1`.

Try it doubled! This outputs `02`.

## Explanation

The ungolfed form of the singular program `00 1+1*1-8*1` is

```
0   0     # set the 0th cell to 0 (this has no effect).
1   +1*1  # set the 1st cell (initialized to 0) to itself plus one (i.e. 1).
-8  *1    # output the value of the first cell as a decimal (1).

```

The ungolfed version of the doubled program `00 1+1*1-8*100 1+1*1-8*1` is

```
0   0     # set the 0th cell to 0.
1   +1*1  # increment the 1st cell.
-8  *100  # output the value of the 100th cell (0).
1   +1*1  # increment the 1st cell.
-8  *1    # output the value of the 1st cell (2).

```

This submission hinges on Momema's syntax: in particular, it allows leading `0`s in a numeric literal to be parsed as separate numbers. This allows the leading `00` in the program to be parsed as a pointless assignment statement.

When the program is doubled, however, the `0`s are no longer leading a numeric literal—they are a continuation of the literal `1` at the end of the program, forming `100`.
> 2 votes

# Answer
# Labyrinth, ~~8~~ 5 bytes

-3 bytes thanks to @MartinEnder

**Single version**

```
^)!@

```

Try it online!

**Double version**

```
^)!@
^)!@

```

Try it online!
> 2 votes

# Answer
# Rust, 81 bytes

```
mod x{pub const Y:i8=1;}use x::*;fn main(){print!("{}",Y)}/*
const Y:i8=2;// *///

```

Doubled:

```
mod x{pub const Y:i8=1;}use x::*;fn main(){print!("{}",Y)}/*
const Y:i8=2;// *///mod x{pub const Y:i8=1;}use x::*;fn main(){print!("{}",Y)}/*
const Y:i8=2;// *///

```

Rust pretty much doesn't allow duplicate items in a source code. For instance, following code causes an error due to an item defined multiple times.

```
const Y: i32 = 2;
const Y: i32 = 2;

```

There are three exceptions to this rule.

* Macros - which are pretty much useless, as macros don't follow the usual visibility rules - code cannot refer to a macro later in the code.
* Wildcard imports - if there is a non-wildcard import, it has precedence while resolving item references. This is to help avoid incompatibilities caused by other crates (including `std` itself) adding more public items.
* Overriding a builtin item or item from prelude - see bonus below, this way turned out to be longer, but also has more potential for improvements.

I decided to go with duplicating an item by using a glob import. This necessiated making a module.

```
mod x { ... }

```

That had a public item in it. Not public items aren't accessible outside of module that defined them. `i8` type was chosen because it's the shortest integer type -- a type needs to be declared for `const` items, this cannot be skipped.

A string literal wasn't used as `&str` is 2 bytes longer, and also quotes would be necessary, not saving bytes even with removal of `"{}",` from main function. Adding 6 bytes is not worth it for removing 5 bytes.

```
pub const Y: i8 = 1;

```

Later I glob import this constant. Note that the constant can be overridden by a different non-wildcard declaration.

```
use x::*;

```

And a function prints whatever value `Y` holds. Note that `Y` can be overridden by a non-wildcard declaration. This is important when doubling source code.

`print!` ends with an exclamation mark as it is a macro. As the first parameter is a formatting pattern, I cannot use an integer directly, instead I have to specify `"{}",` formatting pattern.

Missing semicolon at the end of block means that this block returns a value. This is fine, as `main` returns `()` (implicit, due to not specifying another return type), and `print!` macro returns `()` (as in, it doesn't have an useful return value).

```
fn main() {
    print!("{}", Y)
}

```

Later, I want there to be a second declaration of `Y`, but I don't want it come into play for the first pass, so I comment it out. There is a newline, so that a line comment that will be declared later won't skip over a constant declaration. There is a space after `//` as there is nested comments feature, otherwise Rust would see `/*` inside block comment and start a nested comment.

```
/*
const Y:i8=2;// */

```

At end, I put `//`, so that first line of code of code is skipped when the code is doubled. It involves items that cannot be defined multiple times.

```
//

```

The execution may conntinue from second line. If it does, value of `Y` used by main function will be different.

```
 const Y: i8 = 2;

```

A line comment is included so that closing block comment that was needed for first pass won't cause issues.

```
// *///

```

And that's it, a program that detect it being duplicated in Rust done in 81 characters. Thank you for reading this explanation.

# Bonus (alternative way for possible improvements, ~~93~~ 92 bytes)

Instead of using glob imports, it's possible to override one builtin items from either a builtin type or something imported from prelude.

```
fn main(){println!("{}",i8::max_value())}/*
enum i8{}impl i8{fn max_value()->u8{254}}// *///

```

However, this solution is currently longer than the solution above.
> 2 votes

# Answer
# Ruby, 10 bytes

```
+1;a||=p 1

```

Try it online!

Try it online!Try it online!

Explanation:

* Single version (`+1;a||=p 1`):
    + `+1` is ignored
    + `a` is assigned to `1` (printing 1 in the process) because `a` was previously undefined
* Double version (`+1;a||=p 1+1;a||=p 1`)
    + `+1` is ignored
    + `a` is set to `1+1` (2) (printing 2 in the process) because `a` was undefined
    + The next part is not executed because `a` is already defined
> 2 votes

# Answer
# JavaScript (console), 30 bytes

```
[$^=1]+{valueOf:x=>alert(2-$)}

```

In console environments, we have the `$` default global variable, which is two characters shorter than `Map`, which is the shortest in other environments.

The way this works:

1. `$` is coerced to a number, and has bitwise XOR applied to it, making it `1`.
2. The object at the end is part of an addition equation, so it is also coerced into a number, calling the `valueOf` function which alerts `2-$`, which equals `1`.

When the code is repeated, it looks like this:

```
[$^=1]+{valueOf:x=>alert(2-$)}[$^=1]+{valueOf:x=>alert(2-$)}

```

The first instance of the object now has a member operator attached, so instead of the object's `valueOf` being called, instead we have `(object)[$^=1 /* 0 */ ]`, which is `undefined`. The first instance doesn't alert anything, but the second one does, and by now `$` has been changed to `0` because `$^=1` has run twice, so it alerts `2`.

Or, for non-console environments, we can use `Map` instead of `$` (34 bytes):

```
[Map^=1]+{valueOf:x=>alert(2-Map)}

```

Or, we could use...

# JavaScript, 32 bytes

```
-0?alert(2)+'':[,a=alert(1)]=[1]
```

When not repeated:

When repeated:

```
-0?alert(2)+'':[,a=alert(1)]=[1]-0?alert(2)+'':[,a=alert(1)]=[1]
```
* `-0` is still false, so we go to `[,a=alert(1)]=[1]-0?alert(2)+'':[,a=alert(1)]=[1]`
* `[1]-0` returns `1` which is true, so we `alert(2)` and coerce the `undefined` result to a string by adding an empty string. This returns `"undefined"`. `a` is still being set to the `"undefined"[1]` which is this case is the letter `"n"`. Since `"n"` is a value, the default `alert(1)` isn't run.
> 2 votes

# Answer
# Perl 5, 10 bytes

```
print-s$0#

```

Try it online!

# Doubled, 20 bytes

```
print-s$0#print-s$0#

```

Try it online!

Inspired by Sriotchilism O'Zaic recursive comment approach (Nice work by the way).
> 2 votes

# Answer
# Octave, ~~25~~ ~~13~~ ~~11~~ 3 bytes

```
3;ans=fix(ans);ans=ans*2.

```

Try it online! Try it doubled!

### Edit 1

Got rid of the `fix`

```
1;ans=3*ans-0

```

Try it online! Try it doubled!

### Edit 2

Got rid of the `*`

```
3;ans=ans+0

```

Try it online! Try it doubled!

### Edit 3

Got rid of `ans` ...

```
3+0

```

Try it online! Try it doubled!
> 2 votes

# Answer
# Google Sheets, 12

This answer is much shorter. But here's one for a "normal" `=` formula.

```
=LEN("&00001

```

Google Sheets auto-closes quotes and parens. This outputs 6 (the length of `&000001`). Here is the doubled version:

```
=LEN("&00001=LEN("&00001

```

This outputs 12 because `&00001=LEN(` is 11 characters, concatenated with 1 gives 12 characters.
> 2 votes

# Answer
# BRASCA, 2 bytes

Original:

```
C}

```

Doubled:

```
C}C}

```

Try it!

Try it!Try it!

## Explanation

Original:

```
C     - Sets implicit output to number mode
 }    - Increment top of stack (stack is infinite zeroes by default)

```

Doubled:

```
C     - Sets implicit output to number mode
 }    - Increment top of stack (stack is infinite zeroes by default)
  C   - Implicit output is already set to number mode, so it does nothing
   }  - Increment top of stack again

```
> 2 votes

# Answer
# Zsh, 9 bytes

```
wc -l<<<x
```

Note there is no trailing newline.

Attempt This Online! (outputs 1)

Attempt This Online!Attempt This Online! (outputs 2)

Explanation:

* `wc`: output word-count information:
    + `-l`: the number of lines in the input
* `<<<x`: and input the single-line string `x`

ExplanationExplanation:

* `wc`: output word-count information:
    + `-l`: the number of lines in the input
* `<<<xwc`: and input the single-line string `xwc`
* `-l`: redundant duplication of the previous `-l` option
* `<<<x`: and input a second single-line string `x`

---

## Zsh, 6 bytes

If output requirements followed standard rules, we could output via exit code for 6 bytes:

```
grep x
```

Again, no trailing newline.

* `grep x` searches for `x` in the (empty) input, which has no results and outputs with status code 1
* `grep xgrep x` searches for `xgrep` in the (non-existent) file `x`, which is an error and outputs with status code 2

Attempt This Online! (returns 1)

Attempt This Online!Attempt This Online! (returns 2)

There might be an even shorter option using exit codes.
> 2 votes

# Answer
# Rust, 69 bytes

```
use std::u8::*;fn main(){print!("{}",MIN+1)}#[test]
const MIN:u8=1;//

```

Try it online

Try it online (doubled)

This follows the suggestion in Konrad's bonus solution to override a standard library item and uses `#[test]` instead to "disable" a declaration on the next line. It's not as short as this solution, but it doesn't require reading the source.
> 2 votes

# Answer
# Backhand, 3 bytes

```
]h

```

Try it online! Try it doubled!

Prints 1 as-is, and prints 2 when doubled. There is a trailing space.

There is no two-byte solution because:

* The first command should produce some nonzero number, and the second should be `h` (print the number and halt)
* but both `ab` and `abab` will execute `a` then `b`, so any such program will print the same number (not twice) when doubled.

For a three-byte program, `abc` runs `a` then `b` while `abcabc` runs `aab` in the order, so "`a` = increment = `]`, `b` = print and halt = `h`" works.
> 2 votes

# Answer
# Lambda calculus (Nat), 5 bytes

```
(SBI)

```

Try it online!

> Instructions: Copy-paste the code into the code box, select Nat, press Compile and then Run to see the Output.

Outputs in Church numeral.

```
SBI
\xy. SBIxy
\xy. Bx(Ix)y
\xy. Bxxy
\xy. x(xy)

```

Applying a Church numeral `n` to another `m`, i.e. `n m`, evaluates to `m^n`. Therefore, `(SBI)(SBI) = 2 2 = 2^2 = 4`.

Turns out that I already did the same thing in Flurry...
> 2 votes

# Answer
# MathGolf, 1 byte

There are multiple answers possible:

**Explanation:**

If the stack is empty when a numeric operator is used, it'll use an implicit \\$0\\$. The three programs will respectively do the following:

* `)`: Pop the top of the stack \\$t\\$, and push \\$t+1\\$
* : Pop the top of the stack \\$t\\$, and push \\$t+2\\$
* `ó`: Pop the top of the stack \\$t\\$, and push \\$2^t\\$

After which the entire stack joined together is output implicitly as result.
> 2 votes

# Answer
# Pip, 2 bytes

```
+1

```

Try it online!

Try the double version!
> 1 votes

# Answer
# Newline 3 bytes

```
i\n

```

Note: running newline in TC mode

Output is the red text up top

Try it online
> 1 votes

# Answer
# Ohm, 2 bytes

Try it online!

Try the double version!

aaaaaaaaaaaaaaa i can't find a language where this is one byte aaaaaaaaaaaaaaa
> 1 votes

# Answer
# QBIC, 12 bytes

```
p=p+q┘Z=!p$┘

```

## Explanation

```
p=p+q        Adds 1 to p (q = 1 in QBIC, and p starts out as 0)
┘            (Syntactic linebreak)
Z=!p$        Set Z$ to a string representation of p.
┘            (Syntactic linebreak)

```

At the end of a QBIC program, if `Z$<> ""` it gets printed. So when running this code once, p gets increased by 1, the result is saved in `Z$`, the program ends and we print 1. By running it twice, `Z$` will get overridden on the second iteration by `p`, which is now 2.
> 1 votes

# Answer
# Vim, 5 bytes

```
i0<esc><C-a>:

```

Since V is backwards compatible, you can Try it online! or Try it doubled!
> 1 votes

# Answer
# LOGO, 16 bytes

```
 ct pr bf gensym

```

output 1.

When doubled, it becomes

```
 ct pr bf gensym ct pr bf gensym

```

output 2.

Explanation:

* `ClearText` clears all the output.
* `Print` just print whatever it is given.
* `ButFirst` return the input with the first item removed.
* `GenSym` (perhaps `GenerateSymbol`) return `g1` the first time it is invoked, `g2` the second time, etc.

Because the output of `GenSym` depends on previous outputs, the interpreter should be reset between runs.
> 1 votes

# Answer
# JavaScript (Node.js), 60 bytes

```
console.log(require('fs').readFileSync(__filename).length)//

```

Inspired by this Python 2 answer, this reads the length of the current file and prints it, preventing any duplicates of this code from being executed with the trailing comment.

Try it online!

Try it online doubled!
> 1 votes

# Answer
# BlitzMax, 13 bytes

```
Print..
+1..'

```

No trailing newline.

Newlines act as statement terminators in BlitzMax unless prevented by a `..`. The `'` symbol introduces a line comment. So if run as-is, the program outputs the result of the expression `+1`, which is 1. If doubled, the second `Print` is commented out and the program outputs the result of `+1+1`, which is 2. If you double the program a second time, you get 4, etc.
> 1 votes

# Answer
# JavaScript, 41 chars

```
clearTimeout(1);x=setTimeout('alert(x)');
```

```
clearTimeout(1);x=setTimeout('alert(x)');clearTimeout(1);x=setTimeout('alert(x)');
```
> 1 votes

# Answer
## Ohm, 3 bytes

Original:

```
0Wl

```

Duplicated:

```
0Wl0Wl

```

Owles?

## Explanation

```
0Wl    Main wire
0      Push 0
 W     Wrap in an array
  l    Push Length (1)
0Wl0Wl
0Wl    Push 1 ^
   0   Push another 0
    W  Wrap in an array ([0,1])
     l Push the length (2)

```

Try it online!
Try it online!Try it online!
> 1 votes

# Answer
## Lua, 63 bytes

```
a=1+(a or 0)t=setmetatable(t or{},{__gc=function()print(a)end})

```

This code does not have a newline at the end.
When program starts, variable `a` is `nil`, then it gets modified from `nil` to `1` and (if program code is doubled) from `1` to `2`.
The finalizer of table `t` gets executed when program finishes (when memory of the table is released), it simply prints last value of variable `a`.
Lua 5.2+ is required.
> 1 votes

# Answer
# Ruby, 31 bytes

```
x||=1;x*=2;END{p x;exit!};

```

Try it online!
> 1 votes

# Answer
# \>\<\>, 9 bytes

```
l";3"+10p

```

Try it online!

# Explanation

```
l";3"+10p
l              | Push the length of the stack to the stack; STACK[0]
 ";3"          | Push 59 and 51 to the stack;               STACK[0, 59, 51]
     +         | Add the stack top 2 items;                 STACK[0, 110]
      10p      | At codebox[0,1] put the stack top item;    STACK[0]
                   NEW CODEBOX; ln;3"+10p
ln;            | Push length, print stack top and end;

```

When doubled we run through the code twice, it edits the print function in the same spot but doubles the amount of items we push to the stack.

# \>\<\>, 18 bytes Doubled version

```
l";3"+10pl";3"+10p

```

Try it online!
> 1 votes

# Answer
# Python 3, 48 bytes

Apparently, file I/O is acceptable as an output format.

```
try:y*=2
except:y=1
open('x','w').write(str(y))

```

The 48th character is a new-line character at the end of this program.
> 1 votes

# Answer
# Python 3, ~~62~~ 60 bytes

This time, back to `stdout` and no cheating.

```
class X:
 def __del__(s):print(y)
try:y*=2
except:y=1;z=X()

```

Saved 2 bytes thanks to @OldBunny2800!
> 1 votes

# Answer
# Bash 35 bytes

```
trap 'echo $a' 0
a=$((2**${a:-1}))

```

single source output:

```
2

```

double source output:

```
4

```

This uses bash default value parameter expansion to set `a` to either `1` or the result of `2^a`. An exit trap is defined that will print the current value of `a`, so each additional copy of the source will double the output.
> 1 votes

# Answer
# WinDBG, 40 bytes

```
r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$

```

Outputs 26, and that doubles each time the source is appended.

How it works:

```
r $t0 = d;                           Initialize psuedo-register t0 to 13
r $t0 = @$t0 * 2;                    Double t0
.printf "\r%d", @$t0;                Move caret to start of output line and print t0
$$                                   Comment until the next ; (comment r $t0 = d)

```

Sample output:

```
0:000> r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$
26

0:000> r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$
52

0:000> r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$
104

0:000> r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$r$t0=d;r$t0=@$t0*2;.printf"\r%d",@$t0;$$
208

```
> 1 votes

# Answer
## Scala (interpreted), 85 Bytes

```
if(System getProperty "v"eq "")print(2)else{System.setProperty("v","");print("1\r")};

```

**Commented**

```
if(System getProperty "v"eq "") // If the system property "v" is set to ""
  print(2)                      // Print 2
else{                           // Otherwise
  System.setProperty("v","");   // Set the system property "v" to ""
  print("1\r")                  // Print 1 with a carriage return
};

```

Text that ends with a carriage return and not a newline will be overwritten if anything else is written to the line.

**Note:** likely doesn't work on all consoles, tested on Windows 8.1 command prompt. For example the TIO console.
> 1 votes

# Answer
# Implicit on TIO, 2 bytes

```
:.

```

Hmm, not particularly positive how this works. I'll explain it to myself:

```
:.
    (implicit read integer input), duplicate stack (stack: 0, 0)
 .  increment                                      (stack: 0, 1)

```

Ok, now I see. `:` doesn't read input if the stack has a value on it.

```
:.:.
:     stack: 0, 0
 .    stack: 0, 1
  :   stack: 0, 1, 1
   .  stack: 0, 1, 2

```

Only works on TIO (`:.`, `:.:.`) when the input box is empty.
> 1 votes

# Answer
# Ruby, 21 bytes

```
$.+=1
END{p$.
exit!};

```

1x: Try it online! 2x: Try it online!
> 1 votes

# Answer
# Pyt, 2 bytes

Explanation:

```
0       Push 0 onto the stack [0]
 Ł      Get the length of the stack (1)

```

Try it online!

Doubled:

```
0Ł0Ł

```

Explanation:

```
0           Push 0 onto the stack [0]
 Ł          Get the length of the stack (1)
  0         Push 0 onto the stack [1,0]
   Ł        Get the length of the stack (2)

```

Try it online!
> 1 votes

# Answer
# Chip, 11+5 = 16 bytes

+5 bytes for `-wc1`

```
<b
*\ae*f
`

```

### The active code:

```
*\ae*f

```

Activates a, e, and f which means `0x00110001`.

### Active code when doubled:

```
 b
*\ae*f
`<
*\a

```

Prevents activation of both a's, activates b, e, and f, which means `0x00110010`.

Try it online!
> 1 votes

# Answer
# tinylisp, 16 bytes

```
((q(G(i G 2 1)))

```

Try it online!

Try it doubled!

### How?

`(q (G (function-body)))` creates an unnamed lambda function that takes a variable number of arguments and names the arglist `G`. In our case, the body of the function is `(i G 2 1)`, which tests if `G` is empty or not; if it is, we return `1`; if it isn't, we return `2`. In other words, if we call this function with zero arguments, it returns 1; otherwise, 2.

In the single version, therefore, we call the function without arguments: `(function` (with an implicit closing parenthesis). In the double version, we call the function, and then call it again with that result as an argument: `(function (function` (with two implicit closing parentheses).
> 1 votes

# Answer
# Microscript, 2 bytes

```
1

```

(Note the trailing space.)
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 48 bytes

```
	INPUT('I',1,,'.code.tio');	OUTPUT =size(I);end;

```

Try it online!

Equivalent to this python answer.

Because the existence of an END label terminates the program, reading the source file is the only way to get this to work, as the program `ABCABC` is otherwise equivalent to `ABC`.

SNOBOL always reads input one line at a time so we have to use `;` rather than newlines.
> 1 votes

# Answer
# Stax, 2 bytes

```
|X

```

Run online, doubled

Added for completeness. `|X` in Stax means increment register `x` and push. Register `x` is implicitly initialized with `0`. The top of stack is implicitly output.
> 1 votes

# Answer
# SmileBASIC, ~~11~~ 10 bytes

```
CLS?X+1X=1

```
> 1 votes

# Answer
# Yabasic, 22 bytes

An Anonymous function that takes no input and outputs to STDOUT *in graphics mode*.

```
Clear Screen
n=n+1
?n

```

*Note:* Because this answer uses graphics mode, it does not function on TIO
> 1 votes

# Answer
## Reflections, 10 bytes

```
_~#  _#_v

```

Test it! Test it double!

### Explanation:

* `_~`: read own source and push size
* `# _`: convert to string
* `#_`: print the first digit
* `v`: reflects the IP down

Then, the program does either end when hitting the other `v` or when leaving the grid.
> 1 votes

# Answer
# Fission, 13 bytes

```
O\aL;
+
$
SV;

```

Returns 1

Try it online!

Doubled:

```
O\aL;
+
$
SV;O\aL;
+
$
SV;

```

Returns 2

Try it online!

Fun twist with this language, that doubling source will double atoms, and each atom is in general command pointer. So my idea was to build such code that second atom will be destroyed.

```
  L  Created atom, moving left (mass 1, energy 0)
 a   stores in it ascii code of 'a' (97)
\    mirrors
 V   fission reactor, spliting atom into two with halved masses (48)
  ;  destroy right atom
S    conditional mirror - mirrors right, if energy is zero (default energy level)
$    increase energy by 1 (mass 48, energy 1)
+    increase mass by one (mass 49)

```

if one copy on source:

```
O    print ascii by mass of atom, destroy atom (prints 1)

```

if code was copied

```
S    conditional mirror - energy is 1 now, so goes throw
$    increase energy by 1 (mass 49, energy 2)
+    increase mass by one (mass 50)
O    print ascii by mass of atom, destroy atom (prints 2)

```

Second atom is created with copied code `\aL;` on 4th row. Mirror `\` sends it to the `;` on the first row, where atom is destroyed
> 1 votes

# Answer
# QBasic, 12 bytes

A script that takes no input and outputs to the console. Outputs `1` when single, outputs `2` when doubled.

```
CLS
n=n+1
?n

```
> 1 votes

# Answer
# Small Basic, 45 bytes

A script which takes no input and outputs to the `TextWindow` console.

```
n=n+1
TextWindow.Clear()
TextWindow.Write(n)

```

Try it at SmallBasic.com

```
n=n+1
TextWindow.Clear()
TextWindow.Write(n)
n=n+1
TextWindow.Clear()
TextWindow.Write(n)

```

Try it Doubled at SmallBasic.com

*SmallBasic.com depends on Silverlight, and thus the links must be opened in IE to function.*
> 1 votes

# Answer
# Lenguage, 730750818665451459101842416358141509827966271746 bytes

Not doubled: Try it online!

Doubled: Try it online!

Not that golfed but at least it's a solution, handling loop is so hard
> 1 votes

# Answer
# Python 2, ~~25~~ 24 bytes

```
x=1
print 4*'\b',x,;x=2#

```

Both values of x (1 and 2) get printed when the code is repeated. However the second time, the backspace character backspaces/"erases" the 1 and prints the 2 over the top of it.

The behaviour of printing the backspace escape character `\b` seems quite system dependent (and it doesn't seem to work on many web REPLs...).

Trailing comment idea inspired by W W's answer.

Edit: byte saved, see comment.
> 1 votes

# Answer
# Z80Golf, 6 bytes

```
00000000: 3676 f630 3ce5                           6v.0<.

```

Try it online!

### Doubled

```
00000000: 3676 f630 3ce5 3676 f630 3ce5            6v.0<.6v.0<.

```

Try it online!

### Disassembly

```
start:
  ld (hl), $76
  or $30
  inc a
  push hl

```

The trick is to exclude any `call` or `rst` instructions, so that the execution exactly follows the order:

* The program (one or two copies)
* The `nop` slide, then `putchar` at address `$8000` (exactly once), and then
* `halt` which should be hit on return from `putchar`.

`or $30; inc a` sets up the ASCII `'1' = $31` to print. `push hl` sets up the stack; `ld (hl), $76` writes the `halt` instruction on the return address.

When doubled, the second `inc a` changes the value to ASCII `'2' = $32`. The other instructions are effective no-ops; the *return address* and the *halt instruction on return* don't change.
> 1 votes

# Answer
# Ahead, 7 bytes

```
1~@O+K~

```

Prints 1 on its own, 2 when doubled, 3 when tripled etc.

Try it online!
> 1 votes

# Answer
# Aheui, 23 bytes

```
분아떠망히
아뷴

```

outputs 4.

Doubled:

```
분아떠망히
아뷴
분아떠망히
아뷴

```

outputs 8.

Try it on jsaheui
> 1 votes

# Answer
## , 2 bytes

```
1+

```

## Explanation

```
1+   % Adds an (implicit) 0 (on empty input)
  1+ % Add the constant 1 by 1
     % Implicit output

```
> 1 votes

# Answer
# MathGolf, 1 byte

Added just for completeness.

```
)

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 2 bytes

```
2*

```

Try it online!

`2` pushes `2` to the stack.

`*` multiplies the last 2 elements of the stack.

# Doubled

# 05AB1E, 4 bytes

```
2*2*

```

Try it online!
> 1 votes

# Answer
## Javascript (NodeJS) 44 bytes

```
l={get a(){console.log(z)}};z=this.z?2:1;l.a

```

Or in a browser environment, 38 bytes:

```
l={get a(){alert(z)}};z=this.z?2:1;l.a

```

I found this really challenging, but really interesting. I probably overlooked a much simpler way of doing this.

Using a getter was the only way I could think of so far where appending the second copy of the string would not cause the initial behaviour to run before we get a chance to intervene. When it's repeated, we get:

```
l={get a(){console.log(z)}};z=this.z?2:1;l.al={get a(){console.log(z)}};z=this.z?2:1;l.a

```

The critical part is that `l.a` (the getter) only ends up happening once, because the first time it becomes `l.al=...`
> 1 votes

# Answer
# Pxem (esolang-box notation), 8 bytes.

In this docker environment Pxem program, officially given as a pair of filename and its content, is given as a file:

> The first line is the file name of the pxem code.
>
> The rest is the content of the pxem code.

Original is

```
.f.+.n
.

```

which is translated to filename `.f.+.n` with content `.`. It outputs 46, which is ASCII code for `.`.

When doubled:

```
.f.+.n
..f.+.n
.

```

which is translated to filename `.f.+.n` with content `..f.+.n\n.`. It outputs 92.

## How it works

```
.f pushes content in reverse order
.+ does push (pop+pop) if size>=2; nop otherwise
.n does printf %d pop

```

Try it online!

Try it online!Try it online!
> 1 votes

# Answer
# Python 3 (notebook), 2 bytes

```
+1

```

This only works in a notebook enviroment. Also, You can replace the 1 with any p. number and it'll work.

Try it online!
> 1 votes

# Answer
# brainfuck, 41 bytes

```
[---.+++++++++++[.]]+++++++[->+++++++<]>.

```

Try it online!

Try it online!Try it online!

Contecting two brainfuck programs always output the output of first program, so `1` and `1.999...` is the only choice
> 1 votes

# Answer
# Uiua (0.0.18): 9 bytes

(unfortunately not 7 bytes because Uiua has no single-byte codepage yet)

```
⍣'2;'1;

```

Try it online or Try it online doubled

**Explanation**:  is the `try` glyph, so it attempts to pop an item off the stack and then push 2. This fails, because the stack is empty, so instead it switches to the other branch, where it pops off the (automatically pushed) error description and then pushes 1. If the code is doubled, the second time it is successful at popping an item off the stack, and so it continues on the main branch and outputs 2 instead.
> 1 votes

# Answer
# 05AB1E, 2 bytes

```
2*

```

Try it online!

```
2    # Push 2
*    # Multiply. Multiplies two by itself the first time.

```

Old attempt (3 bytes):

```
0so

```

Try it online!

`0` can actually be any number, first item is `2^n`. `·` can be used instead of `o`, Doubles last number instead of `2^n`.

```
0    # Push 0
s    # Switch with last item
o    # 2^item

```
> 1 votes

# Answer
# 05AB1E, 2 bytes

```
¼¾

```

Try it online!

```
¼¾  # full program
¼   # increment counter_variable (initially 0)
 ¾  # push counter_variable
    # implicit output

```

# Doubled, 4 bytes

```
¼¾¼¾

```

Try it online!Try it online!

```
¼¾¼¾  # full program
¼     # increment counter_variable (initially 0)
 ¾    # push counter_variable
  ¼   # increment counter_variable
   ¾  # push counter_variable
      # implicit output

```
> 0 votes

# Answer
# Pxem, 0 bytes (content) + 21 bytes (filename); requires to be executed on console.

* Content is empty.
* Filename (escaped): `\001.r.v.w.s\b2.p.d.a11.o`

Try it online!

Try it online!Try it online!

## How it works

When single, it just outputs `1`; when doubled, it appends backspace character and `2`; this is how it looks like as if it were doubled. If this would violate the rules, I'm sorry.
> 0 votes

# Answer
# Thunno, \\$ 2\log\_{256}(96) \approx \\$ 1 byte

(actually 1.65 bytes but the leaderboard doesn't accept that)

```
1+

```

Attempt This Online!

Or try it doubled

Pretty straight-forward approach. The stack starts off at `[0]` so the first `+` doesn't do anything.

## Alternative approach, \\$ 3 \log\_{256}(96) \approx \\$ 2.47 bytes

```
zdL

```

Attempt This Online!

Or try it doubled!

(Sort-of) port of Wheat Wizard's Python solution:

* `zd` gets the source code
* `L` gets the length
* (Implicit output of the top of the stack)

When you double it, it will run it twice, and just end up with 6 on the top of the stack.
> 0 votes

# Answer
# Awk, 4 bytes

```
$0++

```

The original increments `$0` to `1`, which auto-prints and the doubled version (`$0++$0++`) just increments it twice.
> 0 votes

---
Tags: code-golf, source-transformation
---


title: Truncate words in a sentence

text:
# Question
Title: Truncate words in a sentence
Inspired by wezl.

Your challenge is to take words (sequences of `[a-zA-Z]`) and truncate them to length 3. For example, `never gonna give you up` would become `nev gon giv you up`.

Words will not necessarly be delimited by spaces - for example, `youtube.com/watch?v=dQw4w9WgXcQ` will become `you.com/wat?v=dQw4w9WgX`. Input will be printable ASCII.

This is , shortest wins!

## Testcases

```
never gonna give you up -> nev gon giv you up
youtube.com/watch?v=dQw4w9WgXcQ -> you.com/wat?v=dQw4w9WgX
code golf -> cod gol
happy_birthday_to_you -> hap_bir_to_you
*hello world* -> *hel wor*
abcd1234fghi -> abc1234fgh

```

# Answer
> 10 votes
# K (ngn/k), ~~21~~ 20 bytes

-1 byte thanks to coltim!

```
{5>1(1+*)\~"a{"'_x}#

```

Try it online!

`{ ... }#` Filter the input using the boolean mask returned by the left function.
`_x` Convert the string to lowercase.
`~"a{"'` For each character, is it in `["a", "{")`?
`1(1+*)\` A scan that converts each 1 to the number of consecutive 1s up to it, incremented by 1. 0s are mapped to 1.
`5>` Keep the indices where this is at most 4.

# Answer
> 9 votes
# x86-64 machine code, 29 bytes

```
83 C9 FF AC 88 07 2C 41 72 06 24 1F 3C 1A 72 02 31 C9 83 F9 FC 7E EC B0 00 AE E0 E7 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string; and the address of the input, as a null-terminated byte string, in RSI.

In assembly:

```
f:
    or ecx, -1
startloop:
    lodsb
    mov [rdi], al
    sub al, 0x41
    jb notletter
    and al, 0x1F
    cmp al, 26
    jb isletter
notletter:
    xor ecx, ecx
isletter:
    cmp ecx, -4
    jle startloop
    mov al, 0
    scasb
    loopnz startloop
    ret

```

# Answer
> 7 votes
# Python, 52 bytes

```
lambda s,c=0:[i for i in s if(c:=-~c*i.isalpha())<4]
```

Attempt This Online!

Outputs as a list of characters.

If that's not allowed:

## Python, 58 bytes

```
lambda s,c=0:"".join(i*((c:=-~c*i.isalpha())<4)for i in s)
```

Attempt This Online!

# Answer
> 6 votes
# Zsh, 39 bytes

```
<<<${1//(#m)[a-zA-Z](#c3,)/$MATCH[1,3]}
```

Attempt This Online!

# Answer
> 6 votes
# BQN, 22 bytes

```
⊣/˜3≥·(×+⊢)`2|"A[a{"⊸⍋

```

Try it here!

-5 bytes thanks to @ovs!

## Explanation

* `⊣/˜...` filter input by constructing this binary array...
* `2|"A[a{"⊸⍋` for each char, 1 if alphabetical and 0 otherwise
    + more literally: check if ordering the char into `A[a{` will yield an odd index
* `(×+⊢)`` count consecutive runs of 1s
* `3≥·` for each element, check if \>= 3

Example of how the input is manipulated under the hood:

```
never gonna give you up  # input
11111011111011110111011  # 2|"A[a{"⊸⍋
12345012345012340123012  # (×+⊢)`
11100111100111101111111  # 3≥·
nev██ gon██ giv█ you up  # ⊣/˜

```

# Answer
> 6 votes
# JavaScript (V8), 39 bytes

```
x=>x.replace(/(?<=[a-z]{3})[a-z]/gi,"")

```

Try it online!

Pretty straightforward.

```
x=>x.replace(/(?<=[a-z]{3})[a-z]/gi,"")

x=>x.replace(                      ,  )  // standard regex replace setup
             /                  /gi      // case insensitive, replace all occurences of
                           [a-z]         // an alphabetical character
                                    ""   // with the empty string
              (?<=        )              // given that it is immediately following
                  [a-z]{3}               // 3 consecutive alphabet characters

```

# Answer
> 5 votes
# brev, 81 bytes

```
(print (strse (read-line) '(+ alpha) (as-list (fn (take x (min (length x) 3))))))

```

I would've wanted:

```
(print (strse (read-line) 'word (as-list (fn (take x (min (length x) 3))))))

```

but that YouTube example looks differently.

Reading and writing stdin/out adds 13 bytes, it's just 68 as a function:

```
((over (strse x '(+ alpha) (as-list (fn (take x (min (length x) 3))))))
 '("never gonna give you up"
   "youtube.com/watch?v=dQw4w9WgXcQ"
   "code golf"
   "happy_birthday_to_you"
   "*hello world*"
   "abcd1234fghi"))

```

# Answer
> 4 votes
# Vyxal `s`, 7 bytes

```
øWƛL3∵Ẏ

```

Try it Online!

Would be 5 bytes if not for modular indexing. Undone by something otherwise useful, I say!

## Explained

```
øWƛL3∵Ẏ
øW      # Split the input on words (/[A-z]+/). Numbers and punctuation are left as single character strings.
  ƛ     # To each "word":
   L3∵  #   get the minimum of the length of the word and the number 3. This is needed to account for modular indexing. This would otherwise just be `3`
      Ẏ #   get the first amount of characters of the word, where the number of characters is the number we just calculated.
# the s flag joins everything into a single string before printing it.

```

# Answer
> 4 votes
# , 38 bytes

```
\(x)gsub('([a-z]{3})[a-z]+','\\1',x,T)
```

Attempt This Online!

-2 bytes thanks to pajonk!

Direct application of `gsub`.

# Answer
> 4 votes
# Perl 5 `-p`, 17 bytes

```
s/\pL{3}\K\pL*//g

```

Try it online!

# Answer
> 3 votes
# Factor, ~~58~~ ~~50~~ 48 bytes

```
[ R/ [a-z]+/i [ 3 short head ] re-replace-with ]

```

Try it online!

# Answer
> 3 votes
# Retina 0.8.2, 21 bytes

```
i`([a-z]{3})[a-z]+
$1

```

Try it online! Link includes test cases. Explanation: Case-insensitively matches runs of three letters followed by at least one more letter and keeps only the first three.

# Answer
> 3 votes
# Python, 84 bytes

```
lambda s:''.join([w,w[:3]][w.isalpha()]for w in re.split('([^a-zA-Z])',s))
import re

```

Attempt This Online!

# Answer
> 3 votes
# C (clang), ~~78~~ 65 bytes

```
c;*p;f(*s){for(c=0,p=s;*s;p+=c<4)c=iswalpha(*p=*s++)?c+1:0;*p=0;}

```

Try it online!

*Saved a whopping 13 bytes thanks to Neil!!!*

Inputs a wide character string.
Performs the word truncations in place.

# Answer
> 3 votes
# Python, 57 bytes

```
lambda s:re.sub('([a-z]{3})[a-z]+',r'\1',s,0,2)
import re
```

Attempt This Online!

A straight port of my regex R solution. `re.IGNORECASE` is 2.

Framework taken from solid.py's answer.

# Answer
> 3 votes
# Pip, ~~38~~ 25 bytes

Simple regex solution, matches runs of letters and captures the first 3, replacing matches with the capture group.

```
aR-`([A-Z]{3})[A-Z]*``\1`

```

Attempt This Online!

# Answer
> 3 votes
# Ruby, 31 bytes

```
->s{s.gsub(/[a-z]+/i){$&[0,3]}}

```

Try it online!

# Answer
> 3 votes
# Jelly, 10 bytes

```
=ŒskŻḣ€4FḊ

```

Try it online!

It's absolutely hideous, but the most elegant thing I've come up with is a byte longer: `nŒs‘×¥\<4x@`

```
    Ż         Prepend a 0 to the input, and
   k          partition that after indices where
=             the original input equals
 Œs           itself case-swapped.
     ḣ€4      Keep the first 4 elements of each slice (one non-letter + up to 3 letters).
        F     Flatten,
         Ḋ    and remove the 0.

```

# Answer
> 2 votes
# Stax, 7 bytes

```
îªZ╛▲?↕

```

Run and debug it

# Answer
> 2 votes
# Charcoal, 15 bytes

```
ΦθΦ⁴¬№α↥§⁺×_μθκ

```

Try it online! Link is to verbose version of code. Explanation: Generates all overlapping substrings of up to four characters ending at each character and keeps those containing at least one non-letter.

```
 θ              Input string
Φ               Filtered by
   ⁴            Literal integer `4`
  Φ             Any value satisfies
      α         Predefined variable uppercase alphabet
    ¬№          Does not contain
           _    Literal string `_`
          ×     Repeated by
            λ   Current value
         ⁺      Concatenated with
             θ  Input string
        §       Indexed by
              κ Current index
       ↥        Uppercase
                Implicitly print

```

Note that I use `Filter` instead of `Any` because the latter does not implicitly convert an integer to a range.

# Answer
> 2 votes
# Julia, ~~46 bytes~~ 42 bytes

```
~~`f(s)=replace(s,r"([\p{L}]{3})[\p{L}]*"=>s"\1")`~~
```

We do not need the square brackets, thx to @thejonymyster:

```
f(s)=replace(s,r"(\p{L}{3})\p{L}*"=>s"\1")
```

Attempt This Online!

`\p{L}`: https://stackoverflow.com/questions/3617797/regex-to-match-only-letters

# Answer
> 2 votes
# Pyth, 15 bytes

```
sf<=Z*hZ}rT0G4Q

```

Try it online!

Port of pxeger's Python answer

# Answer
> 2 votes
# 05AB1E, 12 bytes

```
.γa}DaÅÏ3£}J

```

Try it online or verify all test cases.

**Explanation:**

```
.γ }          # Adjacent group the (implicit) input-string by:
  a           #  Letters
    D         # Duplicate this list of groups
     a        # Check which groups only consist of letters
      ÅÏ  }   # Apply on the truthy indices:
        3£    #  Keep up to the first 3 characters
           J  # Join all groups back together to a string
              # (which is output implicitly as result)

```

# Answer
> 2 votes
# Lua, 41 bytes

```
print(((...):gsub('(%a%a?%a?)%a*','%1')))

```

Try it online!

# Answer
> 1 votes
# sed -E, 24 bytes

```
s/([A-Z]{3})[A-Z]*/\1/gi

```

Try it online!

# Answer
> 1 votes
# Raku -p, 20 bytes

### (formerly known as Perl\_6)

```
s:g/<:L>**3<(<:L>*//

```

FYI, Raku regexes tolerate whitespace by default, so a more readable (exploded) version would be:

```
s:g/ <:L>**3 <( <:L>* //

```

# Answer
> 1 votes
# Rust, 109 bytes

```
fn f(s:&str)->String{let mut n=0;s.chars().filter(|c|if c.is_alphabetic(){n+=1;n<4}else{n=0;true}).collect()}

```

Try it online!

# Answer
> 1 votes
# J-uby, 29 bytes

Port of G B’s Ruby answer.

```
~(:gsub+(~:[]&3&0))&/[a-z]+/i

```

Attempt This Online!

## Explanation

```
(~(:gsub +               )               # replace
                           & /[a-z]+/i)  # each word
           (~:[] & 3 & 0)                # with its first three characters

```

# Answer
> 1 votes
# Scala, 54 bytes

Golfed version. Try it online!

```
def f(x:String)=x.replaceAll("(?<=[a-z]{3})[a-z]", "")

```

# Answer
> 1 votes
# Uiua SBCS, 18 bytes

```
↘1▽<5\(+1×)≠0±.⊂@a

```

Try it!

```
↘1▽<5\(+1×)≠0±.⊂@a
               ⊂@a  # prepend letter a
           ≠0±.     # mask of letters
     \(+1×)         # multiply-increment scan
  ▽<5               # keep letters that correspond to less than 5 in scan
↘1                  # remove first letter

```

---
Tags: code-golf, string
---