168
\$\begingroup\$

Write a program that takes in a number N from 1 to 9 inclusive. In its native form your program should output N+N. E.g. output 2 if N is 1, 4 if N is 2, 6 if N is 3, and so on.

When every character in your program is duplicated in place, then it should be a program that takes in N (still from 1 to 9) and outputs N×N. E.g. output 1 if N is 1, 4 if N is 2, 9 if N is 3, and so on.

When every character in your program is triplicated in place, then it should be a program that takes in N (still from 1 to 9) and outputs N^N. E.g. output 1 if N is 1, 4 if N is 2, 27 if N is 3, 387420489 if N is 9, etc.

Numbers above 9 aren't required because 10^10 is outside of many language's usual integer range.

Example

If your initial program was

My_Program!
Exit();

Then it should be capable of taking in N and outputting N+N.

Additionally, the program

MMyy__PPrrooggrraamm!!

EExxiitt(());;

should take in N and output N×N.

Finally, the program

MMMyyy___PPPrrrooogggrrraaammm!!!


EEExxxiiittt((()));;;

should take in N and output N^N.

Quadrupled-character programs and beyond are not required.

Rules

  • Input and output should be plain, normally formatted decimal numbers. You may answer using a different base to show off your code but then your answer is non-competitive.

  • Windows users may treat \r\n as one character since things like \r\r\n\n wouldn't make sense or perhaps even work.

  • The shortest native program (the N+N one) in bytes wins.

\$\endgroup\$
6
  • 14
    \$\begingroup\$ is it even possible? \$\endgroup\$ Sep 11, 2016 at 15:54
  • 86
    \$\begingroup\$ It always seems impossible until it's done - Nelson Mandela \$\endgroup\$
    – Adnan
    Sep 11, 2016 at 16:10
  • 44
    \$\begingroup\$ @SargeBorsch Yes. \$\endgroup\$
    – Dennis
    Sep 11, 2016 at 21:00
  • 10
    \$\begingroup\$ Unfortunately it's only possible in limited amount of languages. \$\endgroup\$ Sep 12, 2016 at 14:12
  • 2
    \$\begingroup\$ @R.Kap No, seems too confusing. \$\endgroup\$ Nov 12, 2016 at 1:57

6 Answers 6

223
\$\begingroup\$

Jelly, 12 bytes

N+N

“(ẹ+)‘FQṖṪỌv

Try it online!

N×N

““((ẹẹ++))‘‘FFQQṖṖṪṪỌỌvv

Try it online!

N^N

“““(((ẹẹẹ+++)))‘‘‘FFFQQQṖṖṖṪṪṪỌỌỌvvv

Try it online!

How it works

Jelly has several different types of string literals; all of them start with a . If the literal contains more than one , a string array is returned, and separates the strings from each other.

For example, “abc“def” yields ['abc', 'def'].

Depending on the last character of the literal (any of ”«»‘’, where « is currently unimplemented), one can choose between the different types of literals. For , we get the code points in Jelly's code page instead of the corresponding Unicode characters.

For example, “abc“def‘ yields [[97, 98, 99], [100, 101, 102]].

The three literals in the programs correspond to the following code point arrays.

“(ẹ+)‘           -> [40, 214, 43, 41]
““((ẹẹ++))‘      -> [[], [40, 40, 214, 214, 43, 43, 41, 41]]
“““(((ẹẹẹ+++)))‘ -> [[], [], [40, 40, 40, 214, 214, 214, 43, 43, 43, 41, 41, 41]]

N+N

“(ẹ+)‘FQṖṪỌv                          Main link. Argument: n

“(ẹ+)‘                                As before.
      F                               Flatten the array. Yields an integer array.
       Q                              Unique; deduplicate the integers.
                                      This yields [40, 214, 43, 41].
        Ṗ                             Pop; remove the last element.
         Ṫ                            Tail; extract the last element. 
                                      This yields 43, the Unicode code point of +.
          Ọ                           Unordinal; cast to character.
           v                          Eval; execute the character as a Jelly
                                      program with argument n.

N×N

““((ẹẹ++))‘‘FFQQṖṖṪṪỌỌvv              Main link. Argument: n

““((ẹẹ++))‘                           As before.
           ‘                          Increment all integers.
            FF                        Flatten the array. Yields an integer array.
              QQ                      Unique; deduplicate the integers.
                                      This yields [41, 215, 44, 42].
                ṖṖ                    Pop twice; remove the last two elements.
                  ṪṪ                  Tail; extract the last element.
                                      This yields 215, the Unicode code point of ×.
                    ỌỌ                Unordinal; cast to character.
                      v               Eval; execute the character as a Jelly
                                      program with argument n.
                       v              Eval; convert the return value (n×n) to a
                                      string and execute that string as a Jelly
                                      program with argument n. Since the string
                                      consists of a single integer literal, that
                                      integer is returned, ignoring the argument.

Note that F, Q, , and do not alter 1D arrays, arrays without duplicates, integers, and characters (respectively).

N^N

“““(((ẹẹẹ+++)))‘‘‘FFFQQQṖṖṖṪṪṪỌỌỌvvv  Main link. Argument: n

“““(((ẹẹẹ+++)))‘                      As before.
                ‘‘                    Increment all integers twice.
                  FFF                 Flatten the array. Yields an integer array.
                     QQQ              Unique; deduplicate the integers.
                                      This yields [42, 216, 45, 43].
                        ṖṖṖ           Pop thrice; remove the last three elements.
                           ṪṪṪ        Tail; extract the last element.
                                      This yields 42, the Unicode code point of *.
                              ỌỌỌ     Unordinal; cast to character.
                                 v    Eval; execute the character as a Jelly
                                      program with argument n.
                                  vv  Eval twice. See N×N.
\$\endgroup\$
8
  • 80
    \$\begingroup\$ I did expect an answer, because you guys here can solve anything, but this is just some really crazy stuff. You are a master and I'm in awe of your magnificence. \$\endgroup\$
    – Nova
    Sep 11, 2016 at 21:57
  • 27
    \$\begingroup\$ I don't think I've seen an answer from Dennis before that doesn't result in me starting off thinking "no way", then slowly being convinced that he's some sort of god by reading the explanation. \$\endgroup\$ Sep 12, 2016 at 20:32
  • 19
    \$\begingroup\$ Joined to upvote. Wow. \$\endgroup\$
    – Daniel R
    Sep 13, 2016 at 7:41
  • 6
    \$\begingroup\$ No way... how many hours a day do you spend in golfing?!? \$\endgroup\$ Sep 13, 2016 at 15:28
  • 23
    \$\begingroup\$ @Falco I'm sure Dennis was just asleep when it was posted. ;) \$\endgroup\$ Sep 14, 2016 at 15:58
93
\$\begingroup\$

><>, 41 bytes

\<
1:: :
&&* +
i*n n
c&
%:
4l
0(
.i
n}
&?

Try it online: N+N, N*N, N^N. Assumes that the STDIN input is exactly one char.

><> is a 2D language, so we can make use of the fact that code semantics are mostly unchanged if we execute instructions downwards — the extra empty lines that ensue are just no-ops. The exception to this is the conditional trampoline ? which pops a value and skips the next instruction if the value was nonzero — the extra newlines would mess up ? due to the inserted no-ops, but we can get around this by putting the ? at the end of a column and taking advantage of wrapping.

To decide which operation to execute, the key is 40., which teleports the IP to position (4, 0). Due to the expansion of the code, the x = 4 column corresponds to + for the base program, * for the doubled program and ^ for the tripled program. Unfortunately ><> doesn't have exponentiation built in, making that the bulk of the program.

[Setup]
\         Mirror: reflect IP direction to downwards
1&        Put 1 into the register
ic%       Push a code point of input, then take it mod 12. This maps the char '1' to the
          number 1, and so forth for '2' to '9'.
40.       Jump to (4, 0), still heading downwards

[N+N version]
:+        Duplicate then add
n         Output as number
          (Stack is now empty, so the program errors out trying to do the above again)

[N*N version]
:*        Duplicate then multiply
n         Output as number
          (Stack is now empty, so the program errors out trying to do the above again)

[N^N version]
:&*&      Multiply register by N
:l(       Push (N < length of stack + 1)
i         Push input, but since we're now at EOF this pushes -1 (stack length += 1)
}         Move -1 to the back
?<        If (N < length + 1) was 1, execute the < to move leftward. Otherwise, skip it.
          (Continue loop)

\         Mirror: reflect IP direction upwards
&n        Output register
.         Jump to (-1, N), which is invalid so the program errors out
\$\endgroup\$
29
\$\begingroup\$

TovTovTov (a mutation of Chicken): 810147050 bytes

Described below are two suggested solutions: One full solution to the question requiring lots of bytes, and a second partial solution (solving only the N+N and N*N parts, requiring only 484 bytes), each taking a different approach and its own set of cool tricks! :)

1. Full solution (810147050 bytes)

Using TovTovTov(TOV='hi',SEP=','), the TOV elements are immune to duplicating characters in place (both "hihihi" and "hhiihhiihhii" have three "hi"s in them, and all TovTovTov cares about is how many TOVs appear between SEPs).

If we used SEP=', ', the entire program would be immune to character duplication (which is cool, but won't solve the question). So we use SEP=','.

So the program "hihihi,hi", for example, compiles to the ints array [3,1], while "hhiihhiihhii,,hhii" compiles to [3,0,1] and "hhiihhiihhii,,hhii" to [3,0,0,1]. This means that the commands themselves don't change their meaning after duplication, but the overall length changes with character duplication. The solution below queries the length of the program and uses this to decide whether to print N+N, N*N or N^N.

The suggested full solution, as ints array, is: [6, 12, 9, 18, 9, 142, 11, 38, 8, 9, 260, 11, 73, 8, 22, 75, 7, 10, 14, 3, 1, 22, 24, 18, 15, 8, 10, 16, 3, 1, 22, 24, 18, 15, 8, 10, 45, 16, 7, 22, 3, 1, 22, 24, 18, 15, 8, 22, 3, 1, 22, 24, 18, 15, 8, 25, 3, 1, 22, 24, 18, 15, 8, 48, 3, 1, 22, 24, 18, 15, 8, 277, 3, 1, 22, 24, 18, 15, 8, 3146, 3, 1, 22, 24, 18, 15, 8, 46677, 3, 1, 22, 24, 18, 15, 8, 823564, 3, 1, 22, 24, 18, 15, 8, 16777237, 3, 1, 22, 24, 18, 15, 8, 387420510, 3, 1, 22, 24, 18, 15, 8]

As a string, it's a pretty long program, consisting of 810147050 characters, starting with: hihihihihihi,hihihihihihihihihihihihi,hihihihihihihihihi,hihihihihihihihihihihihihihihihihihi,hihihihihihihihihi,hihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihihih...

2. Solving only the N+N and N*N parts of the question (484 bytes)

Using TovTovTov(TOV='1',SEP=', '), this time the SEPs are immune to duplication (",, " still has just one ", " in it), so the following suggested solution will always have 33 commands in it, even after character duplication:

1111, 111111111111111111111111111111111111111111111111, 1111111111, 1111111111, 1111111111, 111111, 111111111111, 111111111, 11111111111111, 111, 1, 1111111111111111111111, 111111111111111111111111, 111111111111111111, 111111111111111, 11111111, 111111111111, 1111111111111111, 111111111111111, 1111111111111111111111, 111111111111111111111111111111111111, 11, 1111111111111111111111111111, 111111, 111, 111111, 11111111111, 111111111111111111111111111, 1111, 1, 11111111, 1, 11111111

The corresponding ints array (the number of TOVs (1s) in each of the 33 commands above) is as follows: [4,48,10,10,10,6,12,9,14,3,1,22,24,18,15,8,12,16,15,22,36,2,28,6,3,6,11,27,4,1,8,1,8]

Duplicating the characters in place results in a list of 33 totally different commands: [8,96,20,20,20,12,24,18,28,6,2,44,48,36,30,16,24,32,30,44,72,4,56,12,6,12,22,54,8,2,16,2,16]

The original ints array (that calculates N+N) was designed carefully so that after the commands change their meaning, the program still makes sense, but calculates N*N. For example, the first 4 (that TovTovTov understands as "treat the next op as an ascii code to convert to a character") changes after character duplication to 8, which is a totally different command ("change the Program Counter to the first popped value from the stack, if the value popped immediately after is true").

\$\endgroup\$
0
16
\$\begingroup\$

Befunge-98 (FBBI), 38 41 bytes

(+3 bytes to fix bug, thanks Jo King!)

vx:k::1-k*\/.@
20@
j3.
>^*
>:^
>:+.@

Try it online: N+N, N*N, N^N

This program won't work out-of-the-box since it requires input to be on the stack at the start of execution. By replacing the first line with the following code (adding three more bytes) it will take input from stdin:

v
&x:k:2-

Explanation

Setup

v       Redirect motion downward
02j     Jump over two instructions/spaces, executing the third
        If N=1, it will skip to the 6th line
        If N=2, it will skip to the 5th line
        If N=3, it will skip to the 4th line

N=1

>       Move right
:+.@    Duplicate, add, print and exit

N=2

>>::^^  Move right, duplicate twice, move up
*.@     Multiply, print and exit

N=3

>>>^^^  Redirect motion
30x     Set instruction pointer delta to (3, 0), causing it to
        move right, executing every third instruction
:k::    Duplicate the number (we'll call it M) M+2 times
        The stack is now [M]*(M+3)
1-k*    Multiply things M times (`k' is a quirky instruction)
\/      Divide that result by M (workaround for `k` being quirky)
.@      Print and exit
\$\endgroup\$
2
  • \$\begingroup\$ Unfortunately N=3 doesn't work for input 2 (damn you k!). You can fix this with :k::1-k*\/.@ instead \$\endgroup\$
    – Jo King
    Aug 6, 2020 at 10:47
  • \$\begingroup\$ @JoKing Thank you! I've updated the post. \$\endgroup\$
    – Hactar
    Aug 7, 2020 at 17:31
12
\$\begingroup\$

Gol><>, 20 18 bytes

Unlike ><>, Gol><> actually has an exponentiation built-in.

\hh
I
:
\\
\\\
X*+

Try it online!

Try it online (doubled)!

Try it online (tripled)!

Explanation

For the explanations here, I'll replace un-executed code with spaces.

\      Reflect the pointer down
I      Take an input
:      Copy the input
\\     Series of mirrors...
 \\    That reflect to the addition part
  +    Add the two numbers
  h    (Wrapped around) Print, and Halt

Explanation (doubled)

\            Reflect down

I            Take input

:            Duplicate the stack

\\           Set of mirrors...

 \\          That redirect to the * section

  *          Multiply two numbers

  h          (Wrapped around) Print + Halt

Explanation (tripled)

\            Reflect down


I            Take input


:            Duplicate input


\\           Set of mirrors...


 \\          ... That redirect to the exponentiation section


  X          Exponentiate the two values


  \h         (Wrapped around) Reflect right to the Print + Halt statement

Gol><>, 19 bytes

A longer (and more boring) version based on the ><> solution.

v
IX* +
:hh h
4
0
.

Try it online!

Try it online (doubled)!

Try it online (tripled)!

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Nice use of the reflects like that! :) \$\endgroup\$ Jul 22, 2020 at 14:37
1
\$\begingroup\$

Itr, 29 bytes

"L0#+â*;"0 0 0'+$©^#$0ååä0 0^

online interpreter

doubled

tripled

Explanation

Relies on Itr's redefinition operator $ (and the ability to redefine redefinition) to distinguish between the first and third case. Uses string literals to run independent code for the second case.

normal:

"L0#+â*;"0 0 0'+$©^#$0ååä0 0^
"L0#+â*;"                     ; string literal
         0 0 0                ; push zero 3 times
              '+$©^           ; redefine ^ to mean +
                   #$0        ; read the input, store it in variable zero
                      ååä     ; stack operations
                         0 0^ ; Input + Input (after redefinition)
                              ; implicit output

doubled:

""LL00##++ââ**;;""00  00  00''++$$©©^^##$$00ååååää00  00^^
""                ; empty string
  LL              ; push 1 two times (calling 'L' on number)
    00            ; push zero
      ##          ; read input, 2nd # will push zero as stdin is empty
        ++        ; add up the top 3 stack values (results in the input value)
          ââ      ; "under" stack operation twice (1 1 X -> 1 X X 1 X )
            **    ; multiply top three stack values, giving X*1*X=X*X
              ;;  ; comment out the rest of the line

tripled:

"""LLL000###+++âââ***;;;"""000   000   000'''+++$$$©©©^^^###$$$000ååååååäää000   000^^^

"""LLL000###+++âââ***;;;"""    ; 3 string literals

000   000   000                ; push zero 3 times

'''+++$$                       ; redefine the $ operator to be the string literal "R"

$©                             ; call "R" consuming zero on stack
  ©©                           ; call 3rd zero and empty string on stack
    ^^^                        ; power with basis zero -> will push (vector of) zeros

###$$$000ååååååäää000   000^^^ ; the actual computation
###                            ; read number and two implicit zero from stdin
   $$$                         ; push string "R" 3 times
      000                      ; push zero
         åååååå                ; discard the top 6 values on the stack
               äää             ; duplicate top stack value (Input) 3 times
                  000   000    ; push zero twice
                           ^^^ ; calculates X^(X^(0^0))= X^X
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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