31
\$\begingroup\$

There have been a couple of challenges involving doubling source code: here and here. The task we have here is a bit harder, but should be doable in almost every language.

In this challenge, you will take in an arbitrary positive integer. Your program must output that integer doubled. When your source code is doubled, it will take in a positive integer, and output it squared.

How is your source code doubled? Well, you can have it your way. That is to say, you can split your source code up into strings of bytes or characters (or tokens in tokenized langs) of any equal length you want, and repeat each chunk twice in succession.

For an initial program of ABCDEFGHIJKL, (length 12) here are all possible doubled programs:

Chunk length |   Doubled source code
-------------+-------------------------
           1 | AABBCCDDEEFFGGHHIIJJKKLL
           2 | ABABCDCDEFEFGHGHIJIJKLKL
           3 | ABCABCDEFDEFGHIGHIJKLJKL
           4 | ABCDABCDEFGHEFGHIJKLIJKL
           6 | ABCDEFABCDEFGHIJKLGHIJKL
          12 | ABCDEFGHIJKLABCDEFGHIJKL

Note that this means programs of prime lengths can only be doubled two ways: every character doubled, or the full program is repeated twice.

Rules:

  • Code must be a full program or function.
  • Standard loopholes are forbidden.
  • Standard I/O methods are allowed.
  • All characters/bytes, including whitespace and newlines, are counted in the length of the code and contribute to chunks.
  • You may assume that the input and its square can be represented by your language's int/integer type.
  • You may not assume a trailing newline or other character.
  • Provide your chunk size in the heading after the byte count.
  • This is , so shorter programs are better! If two programs are the same length, the one which uses the smaller chunk length wins. (If you have a longer program which uses a smaller chunk length, that is worth posting too!)
  • If your program requires a second input/line, you may make no assumptions on its value. In particular, your program should work if the second input is empty, the same as the first, or a different integer. If your program does not require a second input/line, you may ignore this restriction.

Sandbox link

\$\endgroup\$
  • \$\begingroup\$ Can I output result as float (with .0 at the end)? \$\endgroup\$ – val says Reinstate Monica Sep 11 at 16:08
  • \$\begingroup\$ May we print the square twice when the code is doubled? Single code: 5 -> 10; double code: 5 -> 25 25. \$\endgroup\$ – Robin Ryder Sep 12 at 7:05
  • \$\begingroup\$ @RobinRyder No, you may not. \$\endgroup\$ – GammaFunction Sep 12 at 7:53
  • \$\begingroup\$ @val You may output as float. \$\endgroup\$ – GammaFunction Sep 12 at 15:28

29 Answers 29

18
\$\begingroup\$

Perl 5, 8 bytes (chunk size 4)

$_*=~~+2

Try it online, or try the doubled version.

Unary ~ is the bitwise negate, so applying it twice is a noop. Thus, the base program simply multiplies $_ (the implicit input-output variable) by 2.

Binary ~~ is smartmatch, which returns a boolean. ~~+2~~+2 parses as (~~+2) ~~ (+2). Since 2 equals 2, this yields true (1). Thus, the doubled program first multiplies $_ by 1, then multiplies $_ by itself.

\$\endgroup\$
17
\$\begingroup\$

05AB1E, 4 bytes (chunk size 2 or 4)

·Inr

Try it online or doubled as a single 4-byte chunk or doubled as two 2-byte chunks.

·        # double the implicit input
 In      # square the input
   r     # reverse the stack: it's now [input ** 2, input * 2]
         # if we stop here: implicitly output the top of the stack (input * 2)
·        # double the top of the stack (giving input * 4, not that it matters)
 In      # square the input
   r     # reverse the stack: it's now [input ** 2, input * 4, input ** 2]
         # implicitly the top of the stack (input ** 2)
\$\endgroup\$
15
\$\begingroup\$

Python 3, 26 bytes (chunk size 13)

lambda n:"and n*n#"and 2*n

Try it online!

Doubled:

lambda n:"andlambda d:"and n*n#"and 2*n n*n#"and 2*n

This solution is provided by @Grimy.


Python 3, 32 30 28 bytes (chunk size 16 15 14)

lambda n:bool(0)*n*n or  2*n

Try it online!

-4 bytes thanks to @negativeSeven

Doubled:

lambda n:bool(lambda n:bool(0)*n*n or  2*n0)*n*n or  2*n

Try it online!

The function takes advantage of the unique chunk rule of this challenge.

\$\endgroup\$
  • 3
    \$\begingroup\$ 26: TIO \$\endgroup\$ – Grimmy Sep 10 at 21:19
  • 1
    \$\begingroup\$ @Grimy Nice approach. I think it is different enough and deserves its own post. \$\endgroup\$ – Joel Sep 10 at 23:47
  • 1
    \$\begingroup\$ @Grimy I added your solution to my post since you do not seem to be interested in making a separate post. \$\endgroup\$ – Joel Sep 13 at 2:25
9
\$\begingroup\$

Befunge-98 (FBBI), 8 bytes (chunk length 2)

;&:#* +q

Try it online!

;&;&:#:#* * +q+q

Try it online! (doubled)

Excluding control flow, the first program executes &:+q (input, duplicate top of stack, add, exit with return code), and the second executes &:*+q (input, duplicate top of stack, multiply, add (sums with an implicit 0), exit with return code)

\$\endgroup\$
9
\$\begingroup\$

Hexagony, 14 bytes (chunk size 14)

?"+==*/}=+!@!<

Expanded:

  ? " +
 = = * /
} = + ! @
 ! < . .
  . . .

Try it online!

Doubled

?"+==*/}=+!@!<?"+==*/}=+!@!<

Expanded:

   ? " + =
  = * / } =
 + ! @ ! < ?
" + = = * / }
 = + ! @ ! <
  . . . . .
   . . . .

Try it doubled online!

Hexagony is in a bit of a weird position in this challenge, in that actually achieving the task is not much more difficult than simply being able to write the two individual programs. However, golfing the solution proved rather difficult.

This solution is the trivial idea in the shortest form that I could fit, but I suspect there are shorter, cleverer answers. This version very naively sets two values to the input and sums them or multiplies them, depending on if the source is doubled. The only code reuse is the "+ which makes making the copy code for the doubled program short enough to fit in the unused space from the original program.

I suspect using the IP change instructions [] will make isolating the parts easier, but a truly ideal solution will reuse a lot of code between the two. I made a helper program to double hexagony source code. Note that it removes trailing no-ops so if you want to have placeholder no-ops at the end just fill in some other character and change it back after. It can handle different chunk sizes, though I didn't yet write code to output each possible program (Hexagony seems to lend itself to using the full chunk size).

\$\endgroup\$
  • 2
    \$\begingroup\$ @JoKing Well done! It's rather different from my answer, so would you want to post it (using the different chunk size to fill up unused space is really neat!)? Otherwise I'll add it and an explanation when I have more time. \$\endgroup\$ – FryAmTheEggman Sep 12 at 2:55
9
\$\begingroup\$

Hexagony, 12 bytes (chunk size 4)

?"2+...}=*!@

Try it online!

Formatted:

  ? " 2
 + . . .
} = * ! @
 . . . .
  . . .

And doubled, then formatted:

   ? " 2 +
  ? " 2 + .
 . . } . . .
} = * ! @ = *
 ! @ . . . .
  . . . . .
   . . . .

Basically, this sets the first edge to the input, then the second edge to either 2 or a copy of the input, then multiplies those two edges into the third edge, prints that and terminates. The list of executed instructions are just

?"2}=*!@

and

?"2+}=*!@

With the only difference being the + overriding the 2 on the second program.

\$\endgroup\$
8
\$\begingroup\$

JavaScript (ES6),  24  22 bytes

Despite its unusual format, this is the definition of an anonymous function, which can be either called directly or assigned to a variable.

+(g=x=>x*x)?g:(x=>x*2)

Try it online!

+(g=x=>x*x)?g:(x=>x*2)+(g=x=>x*x)?g:(x=>x*2)

Try it online doubled!

How?

Applying the unary + to a function is interpreted as an attempt to coerce it to a number and results in NaN. Therefore, the leading +(g=x=>x*x) is falsy in both versions.

On the other hand, applying the binary + between 2 functions results in a string. Therefore, (x=>x*2)+(g=x=>x*x) is truthy in the doubled version.

\$\endgroup\$
  • \$\begingroup\$ Dude, have you noticed that this can be split in chunks of 11, too? \$\endgroup\$ – Gust van de Wal Sep 24 at 9:31
7
\$\begingroup\$

Perl 6, 8 bytes (chunk size 1)

* *<1 2>

Try it online! Try it doubled!

A Whatever/HyperWhatever lambda that takes a number and returns a number for the first program and a singleton list for the second program. Basically this keeps the exact same logic, except that the multiplication operator (*) is replaced by the exponential one (**).

**  **<<11  22>>

The Whatever literal (confusingly also represented by a *) are doubled up to a HyperWhatever (**) which is basically the same except it maps over lists. The space is needed to separate the Whatever literal from the multiplication and is ignored when doubled up. Instead of just 2 (which would get doubled to 22) we use a list containing two elements, which evaluates to 2 in a numeric context). The <> can be doubled to a list with interpolation, and the two elements inside are doubled, but neither of those change the length of the list.

\$\endgroup\$
6
\$\begingroup\$

Runic Enchantments, 9 bytes (chunk size 3)

i3?:*@:+@

Try it online!
Try it doubled!

The 3? skips the next 3 instructions, resulting in an (executed) i3?...:+@. When doubled it results in an executed i3?...:*@ where . represents the 3 NOP'd instructions. @ is "print entire stack and terminate."

\$\endgroup\$
5
\$\begingroup\$

C# (Visual C# Interactive Compiler) / Javascript, 22 bytes, chunk size 11

m=>/*      /2*m//*/m*2

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Also works in JavaScript \$\endgroup\$ – Shaggy Sep 10 at 21:24
  • 1
    \$\begingroup\$ Also works in Java by changing the = to -. Nice answer! \$\endgroup\$ – Kevin Cruijssen Sep 11 at 6:27
  • 2
    \$\begingroup\$ I like how the comment actually describes what the code does. :p \$\endgroup\$ – Arnauld Sep 11 at 7:50
5
+100
\$\begingroup\$

Brain-Flak, 48 30 bytes (chunk size 10)

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

Try it online! Try it doubled!

This basically takes three steps, then when doubled executes those steps twice each. The initial program is:

  1. Duplicate TOS, switch stacks and start pushing a value
  2. Get the TOS's triangular number n*(n-1)/2
  3. Pop TOS, switch stack and pop twice, then push the result.

For an input n into an undoubled program, this results in:

1.  Start stack: n n
    Other stack: <
    Third stack: 
2.  Start stack: n n
    Other stack: 0 <
    Third stack: tri(0) = 0
3.  Start stack: n+n+tri(0) = 2n <
    Other stack:
    Third stack:

For the doubled program:

1a. Start stack: n n
    Other stack: <
    Third stack: 
1b. Start stack: n n <
    Other stack: 0 0
    Third stack: 
2a. Start stack: n 0 <
    Other stack: 0 0
    Third stack: tri(n)
2b. Start stack: n 0 <
    Other stack: 0 0
    Third stack: tri(n)+tri(0) = tri(n)
3a. Start stack: n
    Other stack: tri(n) <
    Third stack: tri(n)
3a. Start stack: 0+n+tri(n)+tri(n) = n + 2*tri(n) = n + n*(n-1) = n*n <
    Other stack: 
    Third stack: 
\$\endgroup\$
4
\$\begingroup\$

Brain-Flak, 76 bytes, 76 byte chunks

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

Try it online!

Doubled (with newline for clarity)

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

Try it online!

Here is a version that uses a more complex doubling procedure. It does 5 chunks of size 15. The code here is 46 bytes however due to the required padding it is substantially longer.

105 90 bytes, 15 byte chunks

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

Try it online!

Doubled (with newlines for clarity)

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

Try it online!

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

Cubix, 18 14 bytes (chunk length 9 7)

*OI$|:/@O+:I. 

Note the trailing space. Try it online!

Doubled:

*OI$|:/*OI$|:/@O+:I. @O+:I. 

Again, there is one trailing space. Try it online!

Explanation

The main idea is that doubling the code causes the cube to become bigger, so the instruction pointer starts at a different symbol. Since the addition program cannot be put on a cube of side length 1, the side length is going to be 2. Additionally, the doubled code needs to be on a cube of side length 3, so the doubled code must be at least 25 bytes. This means the code must be at least 13 bytes long. As such, at most 1 more byte can be saved.

Now to the actual code. The first observation is that the top face (that is, the first 4 characters) are not used by the addition program. Furthermore, if we make the 5th character reflect the IP around the cube, we can free up 2 more characters. We will use these characters to put the squaring program.

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

Mornington Crescent, 656 Bytes (Chunk size 328)

Just to add weight to the theory that this can be solved in almost any language...

Take Northern Line to Bank
Take District Line to Bank
Take District Line to Parsons Green
Take District Line to Bank
Take District Line to Hammersmith
Take Piccadilly Line to Russell Square
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Hammersmith
Take District Line to Upminster
Take District Line to Embankment
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Acton Town
Take District Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Leicester Square
Take Northern Line to Leicester Square
Take Northern Line to Mornington Crescent

(The trailing newline is important)

Try the single version! ...or... Try the doubled version!


This was a particularly tricky challenge in Mornington Crescent because the program must have such a rigid structure. It's also important to watch where the doubling would take place, because teleporting between stations is illegal in London.

The theory here is simple: In the single version, 'Bounds Green' is filled with a random string, but in the doubled version it gets filled with the squared input. After the chunk ends, both versions double the 'input', but in the doubled version of the code, the input has been replaced with 0.

This result is taken back to Bounds Green, which performs a max() operation twice, before taking the result to the output. In the single version this leaves the doubling unaltered (the int and string are just switched back and forth), but in the doubled version this replaces the 0 with the squared result already stored in Bounds Green.


If my explanation wasn't good enough, I suggest you visit London and try the two routes yourself.

\$\endgroup\$
  • \$\begingroup\$ Typo: your chunk size is 328 and not 326. Welcome to CGCC! \$\endgroup\$ – Robin Ryder Sep 26 at 21:21
  • \$\begingroup\$ Nice spot, thanks! \$\endgroup\$ – Alevya Sep 26 at 21:30
  • \$\begingroup\$ @JoKing Not sure how I missed that! As it is, I routed it so the 2nd half has no excess chars, and found a way to pad the first half to match without needing extra whitespace. Looks better this way anyway ;) \$\endgroup\$ – Alevya Sep 27 at 8:48
3
\$\begingroup\$

JavaScript (Node.js), 15 12 bytes (chunk size: 6)

x=>/**/2*(x)

Try it online!

Single case:

x=>/**/2*(x)

Double case:

x=>/**x=>/**/2*(x)/2*(x)

Seems to also work in C#, and Java if changing => to ->?

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

R, 42 35 28 bytes (chunk size 4)

Now with a smaller chunk and no error. I also have a longer solution with chunk size 3; see below.

I don't think it is possible to write an R answer with chunk size 1 or 2; I'll happily give a bounty to anyone who proves me wrong.

s =scan#
n=s()# 
  
n/2*4#  

Try it online!

The # is for comments in R. The 3rd line is only spaces, making a chunk of newline + 2 spaces + newline, so that the previous and next chunk can have no newline.

Doubled, it becomes:

s =ss =scan#can#
n=s
n=s()# ()# 
  

  
n/2*n/2*4#  4#  

Try it online!

The single version computes \$\frac n2\times4=2n\$; the double version computes \$\frac n2\times \frac n2\times4=n^2\$.

Here is a slightly longer solution, but with chunk size 3:

R, 39 bytes (chunk size 3)

s =bbb=scan#
n=s(#
 
)# 
n* 1/ 2/ 1* 4#

Try it online!

Doubled:

s =s =bbbbbb=sc=scan#an#
n=
n=s(#s(#
 

 
)# )# 
n*
n* 1/ 1/ 2/ 2/ 1* 1* 4# 4#

Try it online!

Note that Giuseppe has another R answer, with one chunk of 30 bytes.

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

R, 59 30 bytes (chunk size 59 30)

F=F+1;f=function(n)n*c(2,n)[F]

Try it online!

Credit to Robin Ryder for inspiring this; increments F each time, and the function f selects the appropriate output.

This isn't particularly interesting, but doubtless something clever manipulating the chunk size will be dreamed up. As expected, Robin Ryder came up with this which is both shorter and has some neat chunk manipulation.

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

PowerShell, 22 bytes (chunk size 11)

param($p)
#   /
2 * $p

Try it online.

Doubled:

param($p)
#param($p)
#   /
2 * $p   /
2 * $p

This solution is based on @ShieruAsakoto's solution.

@Grimy solution that has been converted to PowerShell, 26 bytes (chunk size 13)

param($p)$t=';$p*$p#';$p*2

Try it online.

Doubled:

param($p)$t=';param($p)$t=';$p*$p#';$p*2$p*$p#';$p*2
\$\endgroup\$
  • 1
    \$\begingroup\$ Unfortunately you need to have a chunk size that divides your code into equal chunks. As per example in question about prime length solutions. \$\endgroup\$ – John Rees Sep 17 at 10:38
  • \$\begingroup\$ @JohnRees, i corrected my answer, thanks. \$\endgroup\$ – Andrei Odegov Sep 17 at 10:59
1
\$\begingroup\$

Perl 5 (-p), 22 15 bytes

-7 bytes thanks to Grimy

$_*=$'/4||2;//;

TIO

\$\endgroup\$
  • \$\begingroup\$ 15: TIO \$\endgroup\$ – Grimmy Sep 10 at 13:39
  • \$\begingroup\$ looking at your solution, I'd just found a 22 bytes solution \$\endgroup\$ – Nahuel Fouilleul Sep 10 at 13:42
  • \$\begingroup\$ understood, first input*=2, then by input*=input/4 \$\endgroup\$ – Nahuel Fouilleul Sep 10 at 13:44
  • \$\begingroup\$ another 16 bytes (-a) $_*=/@F/?2:$_/4; \$\endgroup\$ – Nahuel Fouilleul Sep 10 at 13:58
  • \$\begingroup\$ Down to 8 (posted as a separate answer since it's very different). \$\endgroup\$ – Grimmy Sep 10 at 13:59
1
\$\begingroup\$

Charcoal, 13 bytes

PI×Iθ⎇υIθ²⊞υω

Try it online! Explanation: The predefined empty list is falsey so the input is multiplied by 2. When doubled the second pass sees the empty string has been pushed to the list so it multiplies the input by itself instead. Try it online! In verbose syntax this corresponds to Multiprint(Cast(Times(Cast(q), Ternary(u, Cast(q), 2)))); Push(u, w);.

\$\endgroup\$
1
\$\begingroup\$

Python 3, 56 53 bytes

print(eval(input()+"**2"[len(*open(__file__))%2:])) #

My python skills kinda suck, so can definitely be golfed.. Based on the Python answer in the "I double the source, you double the output!" challenge.

Chunk length 53.

Try it online or try it online doubled.

\$\endgroup\$
1
\$\begingroup\$

Java 8, 62 bytes

n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///

Chunk length 62.

Try it online or try it online doubled.

Explanation:

n->                    // Method with integer as both parameter and return-type
  n*                   //  The input, multiplied by:
    (Byte.SIZE>8?      //   If Byte.SIZE is larger than 8:
      n                //    Multiply by the input itself
     :                 //   Else:
      2);              //    Multiply by 2
class Byte{            // Class which overwrites Byte
  static int SIZE=9;}  //  And sets the SIZE to 9

In Java, the available comments are // comment and /* comment */. Which are combined here to overwrite certain parts. See how these comments work thanks to the Java highlighting:

n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///

n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///

The doubled program created a custom Byte class and its value SIZE=9, which overwrites the default java.lang.Byte class and its value SIZE=8.

\$\endgroup\$
1
\$\begingroup\$

Japt, 7 5 bytes

*N²jJ

Try it | Doubled

² pushes 2 to the array of inputs N then j removes & returns the element at index J=-1 (i.e., the newly inserted 2) and multiplies the input by that.

When doubled it results in J being multiplied by 2, so the element at index -2 (i.e., the input) is returned by j and used as the multiplier.

\$\endgroup\$
1
\$\begingroup\$

Jelly, 8 6 bytes (chunk length 3)

Ḥ;²3ị 

Try it online!

Doubled

\$\endgroup\$
1
\$\begingroup\$

Nice solution: Lua, 66 bytes (chunk size 66 bytes)

a,x=a and...^2 or ...*2,setmetatable(x or{},{__gc=load'print(a)'})

Try it online! (double it yourself, it is not so hard)

Oh yeah, pretty sure that there is shorter solution to this, but it's the best I was able to came up with this way. Take input as first argument.

Brief explanation: whole business with a is quite obvious for everyone, while the second part with x is more interesting. Basically, I create a table (or update existing one on second pass) with finalizer (__gc metamethod) which gets called when program exits.

Lame solution: Lua, 60 bytes (chunk size 30 bytes)

a=a and...^2 or ...*2;                     print(a)os.exit()

Try it online! or Try it doubled!

Smaller and with better chunking, but ultimately boring and lame without any clever tricks. I'm pretty sure no comments are required to this one.

\$\endgroup\$
1
\$\begingroup\$

J, 15 10 9 bytes

+: :(*-:)

Try it online!

Doubled version: Try it online!

f : g creates a verb that executes f when called with one argument, and g when called with 2 arguments. So ours executes double +: with the original source and *-: when the source is doubled.

This works because a train of two verbs in J becomes a hook, and thus f f is executed as y f (f y) where y is the original input. Additionally, *-: is itself a "dyadic hook" which works by multiplying * the left arg by half -: the right arg. The left arg will be the original input, and the right arg will be the input doubled, so this will produce the square of the original input.

original answer

J, 15 bytes

*:@]`(+:@])@.=~

Try it online!

Doubled version: Try it online!

In the single version, we have a single verb which uses Agenda @. to do the if... then logic: If the argument is equal to itself =~, then take the argument and double it (+:@[).

However, when we double the code, we get a J hook. Call the verb f and the input y. Then the hook f f executes like this:

y f (f y)

Which means that now the original input is the left arg, and the right arg is the doubled input. Since these will not be equal, =~ will return false this time, and now we'll execute the other fork of the Agenda, ie, *:@], which means "square the right arg." And since ~ reverses the inputs of a dyadic verb, the right arg will be the original input.

\$\endgroup\$
1
\$\begingroup\$

Python 3, 60 bytes

Chunk size 6.
Not a great solution, but it works. This is such a unique challenge, it really makes you think from a different perspective.

0;  i=input;0;  p=print;n=i()#
x=int(n)##
z=2*x#z=x*x
p(z)##

Try it online!

Doubled:

0;  i=0;  i=input;input;0;  p=0;  p=print;print;n=i()#n=i()#
x=int
x=int(n)##
(n)##
z=2*x#z=2*x#z=x*x
z=x*x
p(z)##p(z)##

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Cascade, 13 bytes (chunk size 13)

]
&/2
#
*
 2&

Try it online!

]
&/2
#
*
 2&]
&/2
#
*
 2&

Try it doubled!

This was quite difficult. The basic gist of this is to print the input multiplied by 2 for the first program, and replace the 2 by a copy of the input for the second.

Explanation:

The executed part of the first program looks like

]     Redirection
 /
#     Print
*     The multiplication of
 2&   Input and 2 (wrapping around the left)

The doubled program basically adds the first ] to the end of the last line, so the program wraps around to that instead of the &. This turns it into

]     Redirection
 /
#     Print
*     The multiplication of
 2 ]  Set the value of
& 2   The variable '2' to the input
      Then multiply the result of that (input) by '2' (input)
\$\endgroup\$
0
\$\begingroup\$

Zsh, 30 bytes (chunk size 10)

m=$m[1]*2
x=$[$1$m]
return $x

Try it online! Try it doubled!

Abuses the fact that $var in $[$var] gets expanded first, then evaluated in the arithmetic context.

             # each line is 9 characters long. when doubled, each is run twice.
m=$m[1]*2    # first time: m='*2'   second time: $m[1] is '*', so m='**2'
x=$[$1$m]    # single: x=$[$1*2]    doubled: x=$[$1**2];x=$[$1**2].
return $x    # zsh supports 32-bit return values from functions, unlike bash

If anyone wants a crack at lowering this, here's the closest to a 24/8 solution I've gotten (outputs x^2+2 when doubled)

\$\endgroup\$

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.