148
\$\begingroup\$

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>

\$\endgroup\$
32
  • 2
    \$\begingroup\$ @Mr.Xcoder Then I'll just have to include one in my own source. \$\endgroup\$
    – steenbergh
    Jul 15, 2017 at 17:55
  • 3
    \$\begingroup\$ @Mr.Xcoder I think that you should have prevented reading your own source code. \$\endgroup\$ Jul 15, 2017 at 18:09
  • 2
    \$\begingroup\$ It only needs to work when doubled once? We don't need to support n many doublings? \$\endgroup\$
    – Cody Gray
    Jul 16, 2017 at 8:36
  • 7
    \$\begingroup\$ @Daniel Let's say your source is `` (empty program) and it produces 5. If you double it, your source is `` (empty program) and that produces 5 as well, no matter what you do. That being said, an empty program duplicated is still the empty program, and always produces the same output, except for the case where the empty program means something else (a random number generator, for example), which could not be valid anyway. \$\endgroup\$
    – Mr. Xcoder
    Jul 17, 2017 at 9:11
  • 1
    \$\begingroup\$ This shouldn't be hard for esolangs that automatically dump the top of stack upon program termination. \$\endgroup\$
    – MD XF
    Jul 18, 2017 at 22:26

154 Answers 154

3
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ You could change a to a struct, where it'll default to public, saving 6 bytes (explanation here). Also, remove the unneeded #undef, for 9 bytes, and reorder the cases in the #ifndef so it becomes #ifdef for another. You can remove the int before main. Try it online! \$\endgroup\$
    – zbw
    Jul 20, 2017 at 15:47
  • \$\begingroup\$ @zbw Good catches! Thanks. (Can't believe I forgot the struct thing in particular.) The #undef was to avoid a compiler warning but I guess that's not an issue for code golf. :) \$\endgroup\$
    – fluffy
    Jul 21, 2017 at 15:49
3
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ Removing the spaces seems to give the desired results \$\endgroup\$
    – Mr. Xcoder
    Jul 12, 2018 at 12:50
3
\$\begingroup\$

Python 3, 33 bytes

Cheating a little:

id=print('\r',1+(not id),end='');
\$\endgroup\$
2
  • \$\begingroup\$ On a full console, you should only see 1 or 2; or did you mean that the whole output stream contains more than the number itself? (I'm not sure how this behaves in Windows, but on Debian or a Mac, this looks like a single output). \$\endgroup\$
    – lungj
    Jul 22, 2017 at 19:38
  • 1
    \$\begingroup\$ Oh, yeah, I did a test in TIO before and saw that it didn't work there. In a console, the \r gives a carriage return, but not a newline. Thus, when the second copy of the code is run, it actually starts overwriting the content from the first copy of the code. \$\endgroup\$
    – lungj
    Jul 22, 2017 at 19:43
3
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ If the file name is needed, then you have to add the file name to the bytecount. Meta post \$\endgroup\$
    – Jo King
    Feb 11, 2018 at 22:01
  • \$\begingroup\$ Done. I still gain a byte. ^_^ (I'd remove the dot, but otherwise rustc complains) \$\endgroup\$ Feb 12, 2018 at 2:28
3
\$\begingroup\$

Underload, 15 13 8 bytes

-2 thanks to Martin Ender

-5 thanks to Ørjan Johansen

(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.
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

Implicit, 2 1 byte

-1 thanks to ASCII-only

.

:)

\$\endgroup\$
3
  • \$\begingroup\$ Link's broken for me \$\endgroup\$
    – praosylen
    Mar 27, 2018 at 4:17
  • \$\begingroup\$ @AidanF.Pierce fixed. \$\endgroup\$
    – MD XF
    Mar 27, 2018 at 18:32
  • \$\begingroup\$ . seems to work? \$\endgroup\$
    – ASCII-only
    May 14, 2018 at 10:35
3
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ This probably has something to do with why it works. I can't quite tell what the stack is doing, though, because TIO seems to be running an older and significantly different version of Keg.py where line 67 is return self.content.pop(). \$\endgroup\$ Sep 13, 2019 at 3:08
  • 1
    \$\begingroup\$ @UnrelatedString, I haven't asked Dennis to update Keg on TIO yet because we're still testing to see that I haven't broken everything by implementing functions \$\endgroup\$
    – lyxal
    Sep 13, 2019 at 22:46
  • \$\begingroup\$ Polyglot with Vyxal. \$\endgroup\$
    – emanresu A
    Aug 26, 2021 at 7:09
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Before trying to improve this: Don't get confused between ASCII '1' and byte 0x1. This is very easy to do when you're dealing with low-level. ASCII '1' is 0x31 or 49, which none of these instructions or operands will assemble to in bytecode. \$\endgroup\$ Jun 7, 2020 at 2:30
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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)

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
0
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ what's wrong with (2 ? \$\endgroup\$
    – Oki
    Sep 10, 2017 at 18:36
  • \$\begingroup\$ @Oki Nothing? I just didn't consider that. Mind if I change my answer to add that one? \$\endgroup\$
    – Timtech
    Sep 11, 2017 at 16:32
  • \$\begingroup\$ i don't mind. tough your solution is much fancier \$\endgroup\$
    – Oki
    Sep 12, 2017 at 11:27
2
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can save a byte when you remove the whitespace class A { \$\endgroup\$
    – Edwardth
    Jul 19, 2017 at 14:51
2
\$\begingroup\$

Common Lisp REPL, 25 bytes

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

Try it online!

Try the double version online!

\$\endgroup\$
1
  • \$\begingroup\$ The rule says "to be full program"... wait that's REPL. \$\endgroup\$
    – user100411
    May 4, 2021 at 6:38
2
\$\begingroup\$

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 2s 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 /.

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
6
  • 1
    \$\begingroup\$ f.append(2) can be f+=[2] and try: f can be try:f and except: f=[] can be except:f=[] \$\endgroup\$
    – Mr. Xcoder
    Jul 15, 2017 at 15:36
  • \$\begingroup\$ @Dennis happier with this version? \$\endgroup\$
    – wrymug
    Jul 16, 2017 at 20:27
  • 1
    \$\begingroup\$ Much better. You need to count a trailing newline though, as open... and try... mustn't wind up on the same line. \$\endgroup\$
    – Dennis
    Jul 17, 2017 at 21:15
  • \$\begingroup\$ The rules allow assuming a trailing newline between copies. \$\endgroup\$
    – zbw
    Jul 20, 2017 at 15:52
  • \$\begingroup\$ @zbw the rules say explicitly the opposite of that \$\endgroup\$ Aug 2, 2017 at 1:21
2
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to PPCG! I believe you can remove some newlines (after the semicolons) to save some bytes. \$\endgroup\$
    – Stephen
    Aug 8, 2017 at 13:14
  • \$\begingroup\$ Good spot, thank you :) And thanks for the welcoming! \$\endgroup\$ Aug 8, 2017 at 13:23
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Carrot, 5 bytes

^F+1 

Explanation:

^ --- Stack mode
F --- Convert to float
+1 --- Add 1 to the previous result
<space> -- I have no idea
\$\endgroup\$
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ You should consider changing your formatting to have your solution in a separate code block prior to your outputs for both the singlet and doublet forms \$\endgroup\$ Sep 10, 2017 at 19:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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