title: What temperature is my stove?

text:
# Question
Title: What temperature is my stove?
My stovetop has 10 (0 through 9) different settings of heat and a very odd way of cycling through them.

* It always starts at 0
* When I hit plus it increments the number, *unless* the number is 9 in which case it becomes 0, or the number is 0 in which case it becomes 9.
* When I hit minus it decrements the number, *unless* the number is zero in which case it becomes 4.

There are no other temperature control buttons.

In this challenge you will take as input a string of commands and output which setting my stovetop ends up on after running that sequence.

Answers will be scored in bytes with fewer bytes being better.

## Input

You may take input in any of the following formats:

* A list/array/vector/stream of booleans/1s or 0s/1s or -1s
* A string (or list/array/vector/stream) of two different characters (which should be consistent for your program)

And you may output

* An integer on the range 0-9.
* A character on the range '0'-'9'.
* A string of size 1 consisting of the above.

## Testcases

Input as a string `-` for decrement and `+` for increment.

```
 : 0
- : 4
+ : 9
-- : 3
-+ : 5
+- : 8
++ : 0
--- : 2
--+ : 4
-+- : 4
-++ : 6
+-- : 7
+-+ : 9
++- : 4
+++ : 9
---- : 1
---+ : 3

```

# Answer
> 10 votes
# JavaScript (ES6),  ~~38 37~~  36 bytes

Expects an array of Boolean values, with *false* for `+` and *true* for `-`. Returns an integer.

```
a=>a.map(c=>a=a++?c?a-2:a%10:9>>c)|a

```

Try it online!

### Commented

It's important to note that `a++` with `a = [ true ]` is evaluated to `NaN` because it's first coerced to the string `"true"` and then to a number. That's why we can safely re-use the array `a[]` to store the temperature even when we get the singleton `[ true ]` as input.

```
a =>             // a[] = input array, re-used to store the temperature
  a.map(c =>     // for each command c in a[]:
    a =          //   update the temperature:
      a++ ?      //     if a is numeric and not equal to 0
                 //     (increment it afterwards):
        c ?      //       if this is a '-':
          a - 2  //         subtract 2
        :        //       else:
          a % 10 //         apply a modulo 10
      :          //     else:
        9 >> c   //       yield 4 if this is a '-', or 9 if this is a '+'
  ) | a          // end of map(); return the final result

```

# Answer
> 8 votes
# PHP, ~~103~~ ~~90~~ ~~86~~ ~~75~~ 71 bytes

```
while($k=$argv[1][$i++])--$k?$p?$p++<9?:$p=0:$p=9:($p--?:$p=4);echo+$p;

```

Try it online! \- Add string as argument - 1 for `-`, 2 for `+`. Example: for `---+`, `1112`.

Thanks to @Kaddath for -13 bytes (see comment). -4 by changing input format to 0/1. -11 thanks to @640KB. -4 thanks to @DewiMorgan.

# Answer
> 7 votes
# C (clang), ~~58~~ \\$\cdots\\$ ~~56~~ 54 bytes

```
t;f(*s){for(t=0;*s;)t=*s++-7?t?t-1:4:t?-~t%10:9;*s=t;}

```

Try it online!

*Saved ~~a~~ 3 bytes thanks to Johan du Toit!!!*

Inputs a string of minuses and ~~pluses~~ bell-characters (ASCII 7) and returns the stovetop temperature in the input string (right at the end where the `'\0'` terminator would have been).

# Answer
> 6 votes
# Rust, 46 bytes

```
|x|x.fold(0,|u,v|if u>0{u-v*2+1}else{9>>v}%10)

```

Try it online!

Takes an `Iterator` of zeros (for `+`) and ones (for `-`), and returns the resulting stove temperature. Taking -1s and 1s doesn't seem to help, because `(-1,1) -> (4,9)` isn't trivial to represent in integer arithmetic.

Uses Arnauld's input method and bit-shift trick for the zero case. Also, Rust's if-else expression can be a part of larger expression, so `%10` is factored out to avoid the parentheses in `(u-v*2+1)%10`.

# Answer
> 6 votes
# convey, 41 bytes

Takes in a list of 0 for + and 1 for -.

```
  }{
0>?@`"+1
^ 1-0=v
`15|8*v
|<<,<+<
^10

```

Try it online!

`a` loops around and based on the input `}` goes `@` down towards `-1` and mod 15 `|15` (to set -1 to 14), or goes to `+1` and `+ ((a=0) * 8)` – thus gets set to 9 if `n` was 0. We join both paths `,` and with mod 10 `|10` we get 14 -\> 4, 10 -\> 0. If the input is empty, `a` goes on `?` to the side path to the output `}`.

(The `^` next to the 10 shouldn't be necessary, but I haven't fixed the bug yet.)

# Answer
> 5 votes
# 05AB1E, ~~16~~ ~~15~~ ~~14~~ 12 bytes

Input as a list of `-1`/`1` for `-`/`+` respectively.

```
ÎvD_Ƶ≠yè*yOθ

```

Try it online or verify all test cases.

**Explanation:**

```
Î             # Push 0 and the input-list
 v            # Loop `y` over the input-list:
  D           #  Duplicate the current value
   _          #  Pop the copy, and check that it's 0 (1 if 0; 0 otherwise)
    Ƶ≠        #  Push compressed integer 185
      yè      #  Index `y` into it (0-based modulair, so the leading 1 is ignored, while
              #  1→8 and -1→5)
        *     #  Multiply it to the ==0 boolean
         y    #  Push `y`
          O   #  Take the sum of the three values on the stack
           θ  #  And only leave the last digit (for 10→0)
              # (after the loop, the value is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ƶ≠` is `185`.

# Answer
> 4 votes
# Coconut, 39 bytes

Takes input as a list of `1/-1`

```
reduce$((p,k)->[k%7-2,p+k][p>0]%10,?,0)

```

Try it online!

This uses `((-1)%7-2)%10 = (6-2)%10 = 4` and `(1%7-2)%10 = (-1)%10 = 9`, which works because in Python the result of the modulo operation has the same sign as the divisor.
`-k%-7` would work instead of `k%7-2` and is one byte shorter if we swap `-1` and `1` in the input, but that feels like abusing the input format.

# Answer
> 4 votes
# Retina 0.8.2, 33 bytes

```
^
0
{T`+09d`_9d`^.\+
T`-d`_4d`^.-

```

Try it online! Link includes test suite. Explanation:

```
^
0

```

Start with heat setting 0.

```
{

```

Process all of the control buttons.

```
T`+09d`_9d`^.\+

```

If the control button is a plus, then delete it (by transliterating to `_`) and cyclically increment the digit (`T`9d`d` is the standard way to cyclically increment digits) but change `0` to `9` instead by listing it as an exception before the expansion of `d` to `0123456789`.

```
T`-d`_4d`^.-

```

If the control button is a minus, then delete it and decrement the digit, but use `4` instead of the usual `9` for cyclic decrement.

# Answer
> 4 votes
# Haskell, ~~45~~ 37 bytes

```
0#1=9
0#a=4
9#1=0
x#a=x+a
f=foldl(#)0

```

Try it online!

* Saved 8 thanks to @Wheat Wizard

# Answer
> 4 votes
# , 24 bytes

Takes `-1` for `-` and `1` for `+`.

```
0(10|15|++8*0=<.)/@|.@,]

```

Try it online!

```
0(10|15|++8*0=<.)/@|.@,]
0                    @,] prepend a 0 and …
                  @|.    rotate and …
 (              )/       fold from the left:
            0=<.         if the minimum of the step and the accumulator is 0
                           (can only happen if they are 1/0)
         +8*             add 8 to …
        +                the sum of the step and the accumulator
     15|                 mod 15 to get -1 -> 14
  10|                    mod 10 to get 10 -> 0, and 14 -> 4

```

# Answer
> 4 votes
# Python 2, 50 bytes

```
n=0
for b in input():n=[b%7-2,n+b][n>0]%10
print n

```

Try it online!

Takes input as ±1's. Pretty explicitly fixes the `n=0` case to have `b=-1` give `4` and `b=1` give `9`. There's probably a better way.

**50 bytes**

```
n=0
for b in input():n=((n or 9-b%5)+b)%10
print n

```

Try it online!

# Answer
> 4 votes
## , ~~57~~ 55 bytes

```
f=function(x){for(i in x)F=(F+i)%%10+"if"(i>0,8,-5)*!F;F}

```

Try it online!

# Answer
> 3 votes
# AWK, ~~47~~ 43 bytes

Expects each operation on a separate line with `+` for increment and `-` for decrement

```
/-/{a?a--:a=4}/+/{a=a?++a%10:9}END{print+a}

```

Try it online!

# Answer
> 3 votes
## x86-16 machine code, 40 bytes

Port of @Arnauld's answer. Be sure to upvote him! (Example run is unneccecary since it's just a port.)

```
0BAC:0100  31 DB E3 23 AC 84 DB 74-14 84 C0 75 04 FE CB EB   1..#...t...u....
0BAC:0110  14 FE C3 89 D8 B7 0A F6-F7 88 C3 EB 08 B3 09 86   ................
0BAC:0120  C8 D2 EB 86 C8 E2 DD C3                           ........

```

Callable function.

Expects `[SI]` = index of list (0x00 for `-`, 0x01 for `+`), `CX` = length of list.

Needs a spare `AX`.

Function output is to `BL` (accumulator value).

Disassembled:

```
0BAC:0100 31DB          XOR     BX,BX
0BAC:0102 E323          JCXZ    0127
0BAC:0104 AC            LODSB
0BAC:0105 84DB          TEST    BL,BL
0BAC:0107 7414          JZ      011D
0BAC:0109 84C0          TEST    AL,AL
0BAC:010B 7504          JNZ     0111
0BAC:010D FECB          DEC     BL
0BAC:010F EB14          JMP     0125
0BAC:0111 FEC3          INC     BL
0BAC:0113 89D8          MOV     AX,BX
0BAC:0115 B70A          MOV     BH,0A
0BAC:0117 F6F7          DIV     BH
0BAC:0119 88C3          MOV     BL,AL
0BAC:011B EB08          JMP     0125
0BAC:011D B309          MOV     BL,09
0BAC:011F 86C8          XCHG    CL,AL
0BAC:0121 D2EB          SHR     BL,CL
0BAC:0123 86C8          XCHG    CL,AL
0BAC:0125 E2DD          LOOP    0104
0BAC:0127 C3            RET

```

# Answer
> 3 votes
# Perl 5 `-pF`, 36 bytes

```
$\+=$\?1-2*/-/:9-5*/-/,$\%=10for@F}{

```

Try it online!

# Answer
> 3 votes
# x86-16 machine code, ~~27~~ 26 bytes

```
00000000: 33c0 803c 2d74 0a84 c075 02b0 0840 37eb  3..<-t...u...@7.
00000010: 0548 3f14 003f 46e2 e9c3                 .H?..?F...

```

**Listing:**

```
33 C0           XOR  AX, AX             ; clear accumulator
            SLOOP:
80 3C 2D        CMP  BYTE PTR[SI], '-'  ; is a "-"?
74 0A           JZ   MINUS              ; is a minus operation
84 C0           TEST AL, AL             ; is plus op and 0?
75 02           JNZ  PLUS               ; if not, continue as plus op
B0 08           MOV  AL, 8              ; otherwise add 8
            PLUS:
40              INC  AX                 ; increment
37              AAA                     ; if al > 9 { al = 0, cf = 1 }
EB 06           JMP  DONE               ; done
            MINUS:
48              DEC  AX                 ; decrement
3F              AAS                     ; if al < 0 { al = 9, cf = 1 }
14 00           ADC  AL, 0              ; if cf { al = 10 }
3F              AAS                     ; if al == 10 { al = 4 }
            DONE:
46              INC  SI                 ; next input instruction
E2 E8           LOOP SLOOP
C3              RET                     ; return to caller

```

Callable function, input as string in `[SI]`, length in `CX`. Output to `AL`.

This is the first time I can ever think of where `AAA` and `AAS` were actually useful in a challenge! These instructions, intended for BCD math, are able to be abused a little to do a bit of the dirty work here.

**Tests:**

# Answer
> 3 votes
# Python 3, 92 bytes

```
f=lambda x,t=0:f(x[1:],{"+":{9:0,0:9},"-":{0:4}}[x[0]].get(t,t+eval(f"{x[0]}1")))if x else t

```

Try it online!

Expects input as a string of "-" and "+" as in the test cases.
Recursively looks up the few exceptions or defaults to adding and subtracting one based on the first character of the given string.

# Answer
> 3 votes
# TI-Basic, ~~52~~ 47 bytes

```
Prompt A
For(I,1,dim(ʟA
If ʟA(I:Then
Ans+1+8not(Ans
Ans(Ans≤9
Else
Ans-1+5not(Ans
End
End

```

-5 bytes thanks to MarcMush.

Takes input as a list of 0s and 1s. Output is stored in `Ans` as an integer. Note that there can not be empty lists in TI-Basic, so the first test case throws an error. The below version has 8 bytes more but outputs 0 for the first test case.

---

### ~~60~~ 55 bytes

```
Prompt Str1
For(I,1,length(Str1
If expr(sub(Str1,I,1:Then
Ans+1+8not(Ans
Ans(Ans≤9
Else
Ans-1+5not(Ans
End
End

```

Takes input as a string of "0"s and "1"s. Output is stored in `Ans` as an integer.

# Answer
> 2 votes
# Python 3, ~~151~~ 117 bytes

```
p=0
for k in input():
  if k=='+':
    if p==0:p=9
    elif p==9:p=0
    else:p+=1
  if p==0:p=4
  else:p-=1
print(p)

```

Try it online!

@pxeger So Nice thank you -35 bytes

# Answer
> 2 votes
# Brain-Flak, 132 bytes

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

```

Try it online!

This loses a lot of bytes to simple equality checks (equals 0 and equals 10).

# Answer
> 2 votes
## CESIL , 850 bytes (including data section)

CESIL was taught in UK schools until the mid-1980s (I may have been in one of the last years that had it as an introduction before moving on to the powerhouse of BASIC).

This has been run through a parser I wrote in Python as a little exercise, each column is tab separated.

Everything has to be moved in and out of the accumulator for any function to be performed on that.

There was no real input, as it was designed for punched cards, so data has to be in a separate section at the end (I use -1 and 1 to indicate both temperature controls, and zero to terminate). It gave the correct results from the samples, but did mean I had to update the data section each time, save it, and run it again.

```
        LOAD    0
        STORE   HEAT
LOOP    IN
        JIZERO  END
        STORE   BUTTON
        ADD     HEAT
        STORE   TMP
* CHECK ZERO DOWN TO 4
        JINEG   ZTF
* CHECK 9 UP TO 0
        LOAD    TMP
        SUBTRACT        10
        JIZERO  NTZ
* CHECK 0 UP TO 9
        LOAD    BUTTON
        JINEG   DEC
        LOAD    TMP
        SUBTRACT        1
        JIZERO  ZTN
        LOAD    TMP
        STORE   HEAT

SHOW    LOAD    HEAT
        PRINT   "HEAT IS "
        OUT
        LINE
        JUMP    LOOP

DEC     LOAD    TMP
        STORE   HEAT
        JUMP    SHOW

END     HALT

* 0 GOES DOWN TO 4
ZTF     LOAD    4
        STORE   HEAT
        JUMP    SHOW

* 9 GOES UP TO 0
NTZ     LOAD    0
        STORE   HEAT
        JUMP    SHOW

* ZERO GOES UP TO 9
ZTN     LOAD    9
        STORE   HEAT
        JUMP    SHOW

        %
        -1
        -1
        -1
        1
        0

```

# Answer
> 2 votes
# Pyth, 23 bytes

```
 m?Z=Z%?dhZtZT=Z?d9 4QZ

```

Try it online!

```
 m?Z=Z%?dhZtZT=Z?d9 4QZ   Q auto-initialized to input; Z auto-initialized to zero
 m                   Q    Map through input, using 'd' as current element
  ?Z                      If Z is not 0:
    =Z%?dhZtZT                          Z++ or Z--, Then modulo by 10
                          Else:
              =Z?d9 4          Z = 9 if + or 4 if -
                     Z    Print Z

```

# Answer
> 2 votes
# Python 3, 86 bytes

```
def f(c,t=0):
 if len(c):p=c[0];t=((0,9,4)[p],t+p)[t>0]%10;return f(c[1:],t)
 return t

```

Takes input as a list of 1s and -1s, 1 indicating a + button press and -1 indicating a - button press.

Try it online!

Recursively handles the exceptions that happen in what might be considered the expected function of the buttons, each at t==0.

# Answer
> 2 votes
# Python 3.8 (pre-release), 68 bytes

Nice little lookup table solution.

Thanks to Jay Ryan for -7 bytes, and for making me revisit my code to find and fix a bug! 8 definitely is not 0, much to my previous solutions disbelief.

```
lambda s,a=0:[[a:=b'49021324354657687980'[c+2*a]-48for c in s],a][1]

```

Try it online!

# Answer
> 1 votes
# Stax, ~~23~~ 14 bytes

```
Ç∞/▌Çklº<&CV@‼

```

Run and debug it

Input as a list of 1s and -1s.

-9 bytes from Kevin's answer.

# Answer
> 1 votes
# Jelly, ~~14~~ 13 bytes

```
¹o8 5<?+%⁵µƒ0

```

Try it online!

-1 thanks to xigoi: -1 is always smaller than the accumulator, and the right argument to `o` doesn't matter if it's nonzero anyways

Takes input as 1/-1.

```
           ƒ     Reduce from
            0    zero
          µ      :
¹                (break the leading triple dyad pattern.)
 o               Logical OR the left argument with
  8              eight
     <?          if it is less than the right argument,
    5            else five.
       +         Add the right argument to the result,
        %⁵       mod 10.

```

# Answer
> 1 votes
# Julia, 47 bytes

```
l->(n=0;[n=n>0 ? (n+2i-1)%10 : 4+5i for i=l];n)

```

Try it online!

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 111 bytes

```
	X =0
N	I =INPUT	:F(O)S($I)
A	X =REMDR(X + 1,10)
	X =EQ(X,1) 9	:(N)
S	X =X - 1
	X =4	LT(X)	:(N)
O	OUTPUT =X
END

```

Try it online!

Uses `A` for `+` and `S` for `-`, separated by newlines.

```
	X =0				;* Set X
N	I =INPUT	:F(O)S($I)	;* read input. If empty, goto O, else goto label identified by I
A	X =REMDR(X + 1,10)		;* Incremenet X, mod 10
	X =EQ(X,1) 9	:(N)		;* if X = 1, set it to 9. Goto N
S	X =X - 1			;* decrement X.
	X =4	LT(X)	:(N)		;* If X is less than 0, set X to 4. Goto N.
O	OUTPUT =X			;* Output X and exit.
END

```

SNOBOL won't reassign values on a FAILURE, so `X =EQ(X,1) 9` is a no-op if X isn't equal to 1.

# Answer
> 1 votes
# Java (JDK), 42 bytes

```
a->a.reduce(0,(t,c)->t<1?9>>c:(c*8-~t)%10)

```

Try it online!

Another port of Arnauld's JavaScript answer.

The input is an `IntStream` with `-` being represented by `1` and `+` being represented by `0`.

## Credits

# Answer
> 1 votes
# \>\<\>, 30 bytes

```
0l1=?n:?v~49{?$~!
+1-a%00.>{2*

```

Try it online! (or fishlanguage.com, as this input format is a bit tricky)

Takes an array of `0`s(decrement) and `1`s(increment)

```
---row 1---
0               !    Initialisation
 l1=?n:              Termination
       ?             Branching to special case 0
         ~49{?$~       0 branch, discard 4 or 9 depending on button
---row 2---
+1-a%   >{2*           other branch, conditional increment/decrement mod 10
     00.               loop

```

# Answer
> 1 votes
# PowerShell 7, 50 44 bytes

```
$args|%{$x=$_ ?$x ?++$x%10:9:$x ?$x-1:4};+$x

```

TIO still runs on PS 6, which this solution is incompatible with, so no Try It Online link, for now.

# Explanation

```
$args|%{                            #For each number in the argument list (0 or 1)
    $x=                             #Assign to x
        $_                            #Ternary on the number
            ?                           #Number is non-zero, + button was pressed
                $x                        #Ternary on x
                    ? ++$x%10               #x is non-zero, set x to its increment mod 10
                    : 9                     #x is 0, set x to 9
            :                           #Number is zero, - button was pressed
                $x                        #Ternary on x
                    ? $x-1                  #x is non-zero, decrement
                    : 4                     #x is zero, set x to 4
}                                   #End for each loop
+$x                                 #Output x, coercing it to 0 if null

```

# Answer
> 1 votes
# PowerShell, ~~58~~ 54 bytes

-4 bytes thanks @Zaelin Goodman

```
$args-ge0|%{$x=(($x-1),4,(($x+1)%10),9)[2*$_+!$x]}
+$x

```

Try it online!

Any version of PowerShell. See also the solution for PS7+

# Answer
> 1 votes
# Befunge-98, 21 bytes

```
:&|@>#.
-1_4^
+1_9^%a

```

Try it online!

Input as a list of `0`s and `1`s (or any other format with some character after the last number).

## Explanation

```
:&|@>#.
:        Create a copy of the temperature counter (which starts at 0).
 &       Get the next input number.
  |      Is it 0 (minus) or 1 (plus)?
         If the input is 0, move down to the second line.
         If the input is nonzero, move up (and wrap around) to the third line.

    >    Once the program has returned to the first line:
     #   Skip the next instruction.
      .  (skipped)
         Repeat.

On EOF:
:        Duplicate the final temperature.
      .  Print it.
     #   Skip the next instruction.
    >    (skipped)
   @     End the program.

Second line (minus):
-1_4^
  _      Is the copy of the current temperature zero?
         If so,
   4            replace it with 4,
    ^                              and return to the first line.
         If not,
-                subtract
 1                        1,
    ^                        and return to the first line.

Third line (plus):
+1_9^%a
  _      Is the copy of the current temperature zero?
         If so,
   9            replace it with 9,
    ^                              and return to the first line.
         Otherwise,
+                   add
 1                      1,
     %   take the result modulo
      a                         10,
    ^                               and return to the first line.

```

# Answer
> 1 votes
# naz, 152 bytes

```
2x0v2x3v1a2x1v1a2x2v7a2x4v1x0f3v1o0x1x1f3v3x0v2e1s2x3v6f0x1x2f4a2x3v6f0x1x3f3v3x0v4e3x4v5e1a2x3v6f0x1x4f9a2x3v6f0x1x5f9s2x3v6f0x1x6f1r3x0v0e3x1v1e3f0x6f

```

Expects a null-terminated string of SOH and STX characters (U+0001 and U+0002), representing the minus and plus buttons respectively. Variable 3 stores the temperature.

**Explanation** (with `0x` instructions removed)

```
2x0v2x3v                   # Set both variables 0 and 3 equal to 0
1a2x1v                     # Set variable 1 equal to 1
1a2x2v                     # Set variable 2 equal to 2
7a2x4v                     # Set variable 4 equal to 9
1x0f                       # Function 0
    3v1o                   # Output variable 3
1x1f                       # Function 1
    3v                     # Move variable 3 into the register
      3x0v2e               # Goto function 2 if it equals variable 0
            1s2x3v6f       # Otherwise, subtract 1, write to variable 3, & call function 6
1x2f                       # Function 2
    4a2x3v6f               # Add 4, write to variable 3, and call function 6
1x3f                       # Function 3
    3v                     # Move variable 3 into the register
      3x0v4e               # Goto function 4 if it equals variable 0
            3x4v5e         # Goto function 5 if it equals variable 4
                  1a2x3v6f # Otherwise, add 1, write to variable 3, and call function 6
1x4f                       # Function 4
    9a2x3v6f               # Add 9, write to variable 3, and call function 6
1x5f                       # Function 5
    9s2x3v6f               # Subtract 9, write to variable 3, and call function 6
1x6f                       # Function 6
    1r                     # Read a byte of input
      3x0v0e               # Goto function 0 if it equals variable 0 (NUL)
            3x1v1e         # Goto function 1 if it equals variable 1 (SOH)
                  3f       # Otherwise, call function 3
6f                         # Call function 6

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 40 bytes

```
Fold[+##/.-1->4/. 10|1/;#2>0->9-#&,0,#]&

```

Try it online!

# Answer
> 1 votes
# jq, 44 bytes

```
reduce.[]as$n(0;(7?+(.>0//2.5*$n)//$n+.)%10)

```

Try it online!

with `1` for `+` and `-1` for `-`

# Answer
> 1 votes
# MathGolf, 17 bytes

```
0ê{∙85ß§⌐_¬┌*ßΣ♂%

```

Uses `-1`/`1` for `-`/`+` respectively.

Try it online.

**Explanation:**

```
0                  # Start with a 0 (let's call this `r`)
                   #  STACK: 0
 ê                 # Push all inputs as integer-array
                   #  STACK: 0,[input-list]
  {                # Foreach over them (let's call these `n`):
                   #   STACK: r,n
   ∙               #  Triplicate the current integer
                   #   STACK: r,n,n,n
    85ß            #  Wrap it in a triplet-list with 8 and 5
                   #   STACK: r,n,n,[n,8,5]
       §           #  Use `n` to index into this list (0-based modulair, so 1→8; -1→5)
                   #  (let's call this `i`)
                   #   STACK: r,n,i
        ⌐          #  Rotate the stack
                   #   STACK: n,i,r
         _         #  Duplicate the top
                   #   STACK: n,i,r,r
          ¬        #  Rotate the stack back
                   #   STACK: r,n,i,r
           ┌       #  Check if the top is equal to 0
                   #   STACK: r,n,i,r==0
            *      #  Multiply the top two
                   #   STACK: r,i,n*(r==0)
             ß     #  Wrap the top three values into a list
                   #   STACK: [r,i,n*(r==0)]
              Σ    #  Sum them together
                   #   STACK: r+i+n*(r==0)
               ♂%  #  Modulo-10
                   #   STACK: (r+i+n*(r==0))%10
                   # (afterwards, the entire stack is output implicitly as result)

```

# Answer
> 0 votes
# Charcoal, 23 bytes

```
≔⁰θＦＳ≔⎇⁼ι+﹪⊕∨θ⁸χ⊖∨θ⁵θＩθ

```

Try it online! Link is to verbose version of code. Explanation:

```
≔⁰θ

```

Start with heat setting 0.

```
ＦＳ

```

Loop through the input string.

```
≔⎇⁼ι+﹪⊕∨θ⁸χ⊖∨θ⁵θ

```

If the next character is a plus, then take the heat setting, or 8 if it was zero, and increment it modulo 10, otherwise take the heat setting, or 5 if it was zero, and decrement it.

```
Ｉθ

```

Output the final heat setting.

# Answer
> 0 votes
# Japt, 21 bytes

Port of @Arnauld's Answer to Japt.

Expects input to be a binary array where `0` represents increment and `1` represents decrement

```
£T=T°?X?T-2:T%A:9ÁXÃT

```

Try it

## Explanation

```
£              // Map input with func (X) {
 T=            //   update T:
   T°?         //     if T is not 0 (increment T afterwards)
      X?       //       if X is 1 ('-' case)
        T-2    //          subtract 2
      :        //       else      ('+' case)
        T%A    //          modulo 10
   :           //     else
     9ÁX       //       yield 4 if X is 1 ('-' case), or 9 if X is 0 ('+' case)
ÃT             // End map; implicit output T

```

# Answer
> 0 votes
# Raku, ~~49~~ ~~46~~ 41 bytes

```
{reduce {($^u%7-2,$^t+$u)[?$t]%10},0,|$_}

```

Takes input as a list where `1` represents `+` and `-1` represents `-`.

Try it online!

# Answer
> 0 votes
# Racket, 81 bytes

```
(λ(a)(foldl(λ(x r)(match(list x r)['(1 0)9]['(1 9)0]['(-1 0)4][_(+ r x)]))0 a))

```

Try it online!

Just simple but verbose pattern matching:

```
(define (f a)
  (foldl (λ (x r)
            (match (list x r)
                 ['( 1 0) 9]
                 ['( 1 9) 0]
                 ['(-1 0) 4]
                 [_ (+ r x)]))
         0
         a))

```

---
Tags: code-golf
---


title: Third time the charm

text:
# Question
Title: Third time the charm
Your task, if you wish to accept it, is to write a program that outputs a positive integer (higher than 0). If the source code is duplicated the output must remain the same. The tricky part is that if the source code is typed three times **(triplicated?)** the output will be multiplied by 3.

# 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.
* Leading Zeroes are allowed only if the numbers of digits is consistent eg: 001 - 001 - 003 or 004 - 004 - 012
* 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 still be `4`. However if I write `AbcAbcAbc` and run it, the output must be `12`.

---

~~Shamelessly stolen~~ Derived from Mr. Xcoder's challenge

# Answer
> 21 votes
## Wumpus, 6 bytes

```
{~)
@O

```

Try it online!
Try it doubled!
Try it tripled!

Prints `1` and `3`.

### Explanation

I found a ton of 6-byte solutions by brute force search, but none for 5 bytes. That doesn't necessarily mean there aren't any at 5 bytes but they'd probably use weird characters or something.

I ended up picking this solution because it doesn't print any leading zeros (most of them do) and it has some interesting control flow. Let's start with the single program:

So the executed code is:

```
{~)O@

{   Turn the IP left by 60°.
~   Swap two implicit zeros on the stack, does nothing.
)   Increment the top zero to 1.
O   Print it.
@   Terminate the program.

```

Easy enough. Now the doubled program. Since the first line gets appended onto the second line, the grid extends to width 5 (and height 3) which changes the control flow significantly:

The IP goes around that loop exactly once, so the executed code is:

```
{~){~)){~O@

{~) As before, we end up with a 1 on top of the stack.
{   Turn left by 60° again.
~   Swap the 1 with the 0 underneath.
))  Increment the zero to 2.
{   Turn left by 60° again.
~   Swap the 2 with the 1 underneath.
O   Print the 1.
@   Terminate the program.

```

Finally, the tripled program is quite similar to the doubled one, but we get a couple more important commands onto that third line:

So the executed code is:

```
{~){~)){~~)O@

{~){~)){~
    As before. We end up with a 1 on top of the stack and a 2 underneath.
~   Swap the 1 with the 2 underneath.
)   Increment the 2 to a 3.
O   Print the 3.
@   Terminate the program.

```

# Answer
> 11 votes
# Husk, 5 bytes

```
KΣK+1

```

Try it online!

Repeated twice!

Repeated thrice!

## Explanation

It's quite difficult to construct a repeatable program in Husk. Because the type system forbids a function that can be applied to itself, I have to somehow allow the first part to evaluate to a function, and the remainder to evaluate to a value, and the types of existing built-ins are designed to prevent this kind of ambiguity. The tokens of the program are

* `K`, which constructs a constant function. `K a b` is equivalent to `a`.
* `Σ`, which takes an integer **n** and returns the **n**th triangular number.
* `+`, which adds two numbers.
* `1`, which is the literal 1.

The original program is interpreted like this:

```
   K Σ (K+) 1
== Σ 1
== 1

```

The `(K+)` is a nonsensical function that gets eaten by the first `K`.

The twice repeated program is interpreted like this:

```
   K Σ (K+1KΣK+) 1
== Σ 1
== 1

```

The function in parentheses is again eaten by the first `K`.

The thrice repeated program is interpreted like this:

```
   K (Σ (K (+1) (KΣK+) 1)) (KΣK+1)
== Σ (K (+1) (KΣK+) 1)
== Σ ((+1) 1)
== Σ (+1 1)
== Σ 2
== 3

```

# Answer
> 11 votes
# Cubix, 5 bytes

```
)<@OP

```

Try it online: once, twice, thrice.

---

## Explanation

Cubix is a stack-based language whose instructions are wrapped around the outside of a cube. Important to note is that the stack is initially filled with infinite zeroes, which allows us to "pull values out of thin air" with operators rather than pushing them explicitly.

I must admit that this was found by a brute-forcer; I never would have found it on my own. In fact, @MartinEnder was the one who asked me to try brute-forcing, as he had been looking for this solution without luck. This is the only solution the brute-forcer found, and I do believe it is the one and only shortest solution in Cubix.

### Single program

Watch it run!

The original program fits on a unit cube. Here's the unfolded net:

```
  )
< @ O P
  .

```

The IP (instruction pointer) starts on the leftmost face (the `<`) headed east. The `<` immediately points it west, and it wraps around to the `P`. `P` is exponentiation, and since there's nothing on the stack, the interpreter pulls out two **0**s and calculates **00**, which is **1** according to JavaScript. `O` then prints this value, and `@` ends the program.

### Double program

Watch it run!

```
)<@OP)<@OP

```

The 10-byte program is too long to fit onto a unit cube, and so it is expanded to a size-2 cube:

```
    ) <
    @ O
P ) < @ O P . .
. . . . . . . .
    . .
    . .

```

As before, the IP starts out at the top-left of the left-most face. This time, the very first instruction is `P`, which pushes a **1** as before. Next is `)`, which increments the top item, turning it into a **2**. Then `<` turns the IP around, and it hits the `)` again, transforming the **2** into a **3**.

Here's where it gets interesting. `P` raises the second-from-top item to the power of the first item, which gives **03 = 0**. Then the IP wraps around to the rightmost face and passes through two no-ops `.` before hitting another `P`. Here we see another quirk of Cubix: binary operators (such as `P`) don't remove their operands from the stack. So since the stack is now `[3, 0]`, we calculate **30 = 1**, which `O` outputs, and `@` terminates the program.

### Triple program

Watch it run!

```
)<@OP)<@OP)<@OP

```

As with the double program, the triple can fit on a size-2 cube:

```
    ) <
    @ O
P ) < @ O P ) <
@ O P . . . . .
    . .
    . .

```

This program starts out in the same way as the previous: `P` pushes **1**, `)` increments, `<` points the IP west, `)` increments again, and `P` now pushes **0**. The IP is then wrapped around to the `<` on the rightmost face, which does nothing since the IP is already pointed west.

Here is the one difference from the double program: the `)` increments the **0** on top of the stack to a **1**. When `P` performs its magic again, this time it calculates **31 = 3**. `O` outputs and `@` terminates, and we prove conclusively that the third time is indeed the charm.

# Answer
> 10 votes
# Jelly, ~~7~~ 5 bytes

```
»‘µ*Ḃ

```

Try it online!

Try it doubled!

Try it tripled!

### How it works

```
»‘µ*Ḃ            Main link. No arguments. Implicit argument: x = 0

 ‘               Increment; yield x + 1 = 1.
»                Take the maximum of x and 1. Yields 1.
  µ              Begin a new, monadic chain. Argument: y = 1
    Ḃ            Bit; yield 1 if y is odd, 0 if it is even. Yields 1.
   *             Power; yield y**1 = 1.

```

```
»‘µ*Ḃ»‘µ*Ḃ       Main link.

»‘µ*Ḃ            As before.
      ‘          Increment; yield y + 1 = 2.
     »           Take the maximum of 1 and 2. Yields 2.
       µ         Begin a new, monadic chain. Argument: z = 2
         Ḃ       Bit; yield 1 if z is odd, 0 if it is even. Yields 0.
        *        Power; yield z**0 = 1.

```

```
»‘µ*Ḃ»‘µ*Ḃ»‘µ*Ḃ  Main link.

»‘µ*Ḃ»‘µ*Ḃ       As before.
           ‘     Increment; yield z + 1 = 3.
          »      Take the maximum of 1 and 3. Yields 3.
            µ    Begin a new, monadic chain. Argument: w = 3
              Ḃ  Bit; yield 1 if w is odd, 0 if it is even. Yields 1.
             *   Power; yield w**1 = 3.

```

# Answer
> 10 votes
# Haskell, 24 bytes

```
main=print.div 3$4
 -1--

```

Prints `1`: Try it online!

```
main=print.div 3$4
 -1--main=print.div 3$4
 -1--

```

Also prints `1`: Try it online!

```
main=print.div 3$4
 -1--main=print.div 3$4
 -1--main=print.div 3$4
 -1--

```

Prints `3`: Try it online!

# Answer
> 8 votes
# Brain-Flak, 10 bytes

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

```

Try it online!

Try it doubled!

Try it tripled!

Explanation:

```
#Toggle stacks
<>

#Push
(
    #Stack-height (initially 0) +
    []

    #The TOS (initially 0) +
    {}

    #1
    ()
)

```

When we run this once, it will put `(0 + 0 + 1) == 1` onto the alternate stack. Ran a second time, it puts the same onto the main stack. Run a *third* time however, it evaluates to `(1 + 1 + 1) == 3`, and pushes that to the alternate stack and implicitly prints.

# Answer
> 8 votes
## SQL, ~~25~~ ~~24~~ 23 bytes

(**-1 Byte** *Removed a mistyped character that was always commented out and doing nothing*)
(**-1 Byte** *Changed `SELECT` to `PRINT` as recommended by Razvan Socol*)

```
PRINT 2/*
*2+1--*/-1
--

```

**How it works:**
In SQL, you can comment out the comment tags, like so:

```
/*
'Comment'--*/

```

vs

```
--/*
'Not Comment'--*/

```

*Code on 1 line with comments excluded:*
First iteration: `SELECT 2-1` Output: `1`
Second iteration: `SELECT 2-1*2+1` Output: `1`
Third iteration: `SELECT 2-1*2+1*2+1` Output: `3`

# Answer
> 6 votes
# 05AB1E, ~~6~~ 5 bytes

```
.gDÈ+

```

Try it online! or Try it doubled! or Try it tripled!

**Explanation**

```
.g     # push length of stack
  D    # duplicate
   È   # check if even
    +  # add

```

**Single: `0 + (0 % 2 == 0) -> 1`
Double: `1 + (1 % 2 == 0) -> 1`
Triple: `2 + (2 % 2 == 0) -> 3`**

# Answer
> 6 votes
# SOGL V0.12, ~~7~~ ~~5~~ 4 bytes

```
ē»«I

```

Try it here!

Try it doubled!

Try it tripled!

Explanation:

```
ē»«I
ē     push counter, then increment it.
      First time running this will push 0, then 1, then 2.
             TOS on each: 0  1  2
 »    floor divide by 2   0  0  1
  «   multiply by 2       0  0  2
   I  and increment       1  1  3

```

# Answer
> 6 votes
# Lost, 38 bytes

```
\\<<<<</<<<<>
2>((1+@>?!^%^
.........v

```

Try it online!

```
\\<<<<</<<<<>
2>((1+@>?!^%^
.........v\\<<<<</<<<<>
2>((1+@>?!^%^
.........v

```

Try it online!

```
\\<<<<</<<<<>
2>((1+@>?!^%^
.........v\\<<<<</<<<<>
2>((1+@>?!^%^
.........v\\<<<<</<<<<>
2>((1+@>?!^%^
.........v

```

Try it online!

## Explanation

Lost is a very interesting language for this challenge. The usual Lost technique is to build a "trap". A trap is a section of the program designed to catch all the ips in one place so that their stacks can be cleared and they can be controlled to go in a specific direction. This makes writing programs in Lost a lot more manageable. However since the program is duplicated we need to avoid trap duplication as well. This requires us to design a new trap that works properly but when duplicated only one of the traps works. My basic idea here is the following

```
v<<<<>
>%?!^^

```

While the stack is non-empty the `?` will remove a item and cause it to jump back to the begining if that item is non-zero. The key here is that when this stacks the `^^`s line up

```
v<<<<>
>%?!^^v<<<<>
>%?!^^v<<<<>
>%?!^^v<<<<>
>%?!^^v<<<<>
>%?!^^

```

Meaning that no matter how you enter you will always exit in the same place.

From here we can attempt to implement the same idea from my Klein answer.

```
\\<<<<<v<<<<>
2>((1+@>?!^%^

```

The backbone of our program is the left had side which pushes a number of `2`s. Each time we add a copy of the program another `2` gets added to the backbone of the program meaning an additional 2 is pushed to the stack. Once it goes off the bottom it bounces through `\\>` and executes the code

```
((1+@

```

This removes the first 2 stack items, adds one to the whatever is left, and exits. Once our backbone has 3 2s we will add 1 and get 3, if we have any less than 3 items we will just discard the entire stack and return 1.

Now the only problem left is that the `!` in our program can cause an infinite loop. If the ip starts on `!` going upwards it will jump and land right back where it was. This means we have to add another line underneath to prevent the loop.

```
\\<<<<</<<<<>
2>((1+@>?!^%^
.........^

```

This has the slight problem of putting some slashes in between our `^`s in the trap. However, rather miraculously, everything works out. Our ips bounce around properly so that it doesn't make a difference.

# Answer
> 5 votes
# Python 2,  ~~46 45~~  39 bytes

Inspired by Halvard's answer. I'm glad that my challenge inspired a new one, which I find even more interesting. Saved 6 bytes thanks to Kevin Cruijssen.

```
print open(__file__,"a").tell()/79*3|1#

```

Try it online!

Try it doubled!

Try it tripled!

## How it works (outdated)

```
k=open(__file__,"a").tell() # Read the source code in "append" mode and get its length.
                            # Assign it to a variable k.
;print k>>(k==90)#          # Print k, with the bits shifted to the right by 1 if k
                            # is equal to 90, or without being shifted at all overwise.
                            # By shifting the bits of a number to the right by 1 (>>1),
                            # we basically halve it.

```

When it is doubled, the length becomes **90**, but the new code is ignored thanks to the `#`, so `k==90` evaluates to `True`. Booleans are subclasses of integers in Python, so `k>>True` is equivalent to `k>>1`, which is essentially **k / 2 = 45**. When it is tripled, the new code is again ignored, hence the new length is **135**, which doesn't get shifted because `k==90` evaluates to `False`, so `k>>(k==90) ⟶ k>>(135==90) ⟶ k>>False ⟶ k>>0 ⟶ k`, and **k** is printed as-is.

---

# Python 2, 36 bytes

This was a suggestion by Aidan F. Pierce at 38 bytes, and I golfed it by 2 bytes. I’m not posting this as my main solution because I didn’t come up with it by myself.

```
0and""
True+=1
print True>3and 3or 1

```

Try it online! Try it doubled! Try it tripled!

# Answer
> 5 votes
## C (gcc), 107 bytes

My first submission in C (gcc). Way too long ...

```
i;
#ifdef c
#define c
#ifdef b
i=2;
#else
#define b
#endif
#else
#define c main(){putchar(i+49);}
#endif
c

```

TIO links: single, double, triple.

# Answer
> 5 votes
# , ~~37~~ ~~31~~ 28 bytes

Thanks to Giuseppe for golfing off the final 3 bytes.

```
length(readLines())%/%2*2+1

```

(with a trailing newline).

Try it once!

Try it twice!

Try it thrice!

This uses the `readLines()` trick from Giuseppe's answer to the 8-ball challenge, where `stdin` redirects to the source file. This code basically just counts up how many lines exist below the first line and outputs `1` if there are 1 or 3 lines (i.e. code is single or doubled), or `3` if there are 5 lines (i.e. code is tripled).

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

```
\5 n;
\\1

```

Try it online!

Try it doubled!

Try it tripled!

I found this sort of by luck, using the philosophy that "if you make the fish's path convoluted enough, eventually something will work". The original and doubled versions print a 5, and the tripled version prints 1 then 5 to make 15 = 3×5. Here are the multiplied versions, for your perusal:

```
\5 n;
\\1\5 n;
\\1

```

```
\5 n;
\\1\5 n;
\\1\5 n;
\\1

```

# Answer
> 4 votes
# Stax, 5 bytes

```
|dhH^

```

Run and debug online! · Doubled · Tripled

## Explanation

```
|dhH^
|d       Push Current stack depth `d`, originally 0
         Doubled -> 1, Tripled -> 2
  hH^    Map d to 2*(floor(d/2))+1
         Implicit print

```

# Answer
> 4 votes
# C (gcc), ~~95~~ ~~91~~ 85 bytes

```
#ifndef a
#define a-1
main(){puts(3
#include __FILE__
?"1":"3");}
#define a
#endif
a

```

Try it online!

# Answer
> 4 votes
# Perl 5, ~~18~~ ~~15~~ ~~13~~ ~~12~~ 11 bytes

-3 bytes thanks to nwellnhof

```
say 1|
+.7#

```

Once Try it online!

Twice Try it online!

Thrice Try it online!

# Answer
> 4 votes
# Japt, ~~8~~ ~~6~~ 5 bytes

*-1 byte thanks to @ETHproductions*

```
°U-v

```

## Explanation:

```
°U-v
 U     # variable U=0                # U=0
°U     # ++U                         # U=1
  -    # minus:
   v   #   1 if U is divisible by 2
       #     else
       #   0                         # U=1

```

This evaluates to `1-0 = 1`

Doubled evaluates to `2-1 = 1`

Tripled evaluates to `3-0 = 3`

# Answer
> 4 votes
# \>\<\>, ~~10 9~~ 8 bytes

```
562gn|

```

Try it online!

Try it doubled!

Try it tripled!

~~I'm sure there's an 8 byte solution somewhere out there.~~

The unprintable at the end has ASCII value 1, and is only fetched by the `g`et command on the third iteration. For the first two it prints `05`, and then prints `15`.

# Answer
> 4 votes
# Pure Bash (no `wc` or other external utils), 27

```
trap echo\ $[a++&2|1] EXIT

```

# Answer
> 3 votes
# JavaScript, ~~81 77 74~~ 70 bytes

Saved 4 bytes thanks to Shaggy

```
var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)
```

Pretty lame JS solution. Consumes the values from the `[3,1,1]` array from the right (`pop()`). Registers a timeout to display the current value in the future. If a timeout was already registered, cancel it. Relies on the dirty nature of `var`, which hoists variable declarations.

## Two times:

```
var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)

var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)
```

## Three times:

```
var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)

var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)

var t,i=(i||[3,1,1]),a=i.pop()
clearTimeout(t)
t=setTimeout(alert,9,a)
```

# Answer
> 3 votes
# Labyrinth, ~~12~~ ~~11~~ 9 bytes

```
:#%!@
 7

```

TIO (1x), TIO (2x), TIO (3x)

# Answer
> 3 votes
# C (gcc), ~~53~~ 52 bytes

Note the space after `#endif`.

```
n;main(){putchar(n+49);}
#if __LINE__>7
n=2;
#endif

```

Try it online!

# Answer
> 3 votes
# Lost, 27 bytes

```
\\<<<<//<<<>
2>((1+@>((%^
v

```

Try it online!

Try it doubled!

Try it tripled!

This is mostly an improvement of Post Left Garf Hunter's answer that removes all the pesky no-ops from that last line,

To do this, we have to remove the `!`, otherwise the program always gets stuck in a loop. So we change the clearing section from `>?!^%^` to `>))%^`' since there can only be a max of two elements on the stack anyway. Unfortunately, this means that the path from the extra copies to the original is broken, so we place an extra `/` in the first line to compensate. This forces the pointer to go through the clearing section for all copies of the program until it reaches the first one, where the `^` instead redirects it to the `>` instead.

# Answer
> 2 votes
# Charcoal, 12 bytes

```
⎚≔⁺ι¹ιＩ⁻ι⁼ι²

```

Try it online! Link is to verbose code.

Try it doubled!

Try it tripled!

### Explanation

```
⎚             Clear
 ≔⁺ι¹ι        Assign plus(i, 1) to i
       Ｉ      Cast (and implicitly print)
         ⁻ ⁼ι² Subtract equals(i, 2) from
          ι    i

```

# Answer
> 2 votes
# PowerShell, ~~54~~ ~~48~~ ~~45~~ 44 bytes

```
if(99-gt(gc $PSCOMMANDPATH|wc -c)){1;exit}3#

```

Try it online!

Try it doubled!

Try it tripled!

Gets its own invocation path with `$PSCOMMANDPATH` and performs a `g`et-`c`ontent on the file. `If` the character count of that file is less than `99` (checked via `wc -c` from coreutils), then we output `1` and `exit` (i.e., stop execution). That accounts for the original code and the doubled code. Otherwise we output `3` and exit. The actual code that's in the doubled or tripled sections is meaningless, since either we'll `exit` before we get to it, or it's behind a comment `#`.

*Saved 6 bytes thanks to Mr. Xcoder*
*Saved ~~3~~ 4 bytes thanks to Pavel*

# Answer
> 2 votes
# JavaScript, ~~43~~ 40 Bytes

```
var t=t?--t:~!setTimeout`t=alert(1|~t)`;
```

2x:

```
var t=t?--t:~!setTimeout`t=alert(1|~t)`;var t=t?--t:~!setTimeout`t=alert(1|~t)`;
```

3x:

```
var t=t?--t:~!setTimeout`t=alert(1|~t)`;var t=t?--t:~!setTimeout`t=alert(1|~t)`;var t=t?--t:~!setTimeout`t=alert(1|~t)`;
```

# Answer
> 2 votes
## C# (178 Bytes)

```
Console.WriteLine(1+2*4%int.Parse(System.Configuration.ConfigurationManager.AppSettings["z"]=(int.Parse(System.Configuration.ConfigurationManager.AppSettings["z"]??"0"))+1+""));

```

crazy C# solution, but I am happy it's possible in one line in C# at all. :)

For me the hardest part was having valid C# that would either intialize or increment the same variable, so I ended up abusing the ConfigurationManager because I needed a global static NameValueCollection and ConfigurationManager was the only one I could think of that I could update in memory. EnvironmentVariables was another option I Iooked at but it doesn't have an indexer so I am not sure how to do that in one line that can be copy pasted to produce the required output as per the spec.

# Answer
> 2 votes
# Ruby, ~~31~~ 25 bytes

```
p [*DATA][3]?3:1
__END__

```

Try it online!

Try it online!Try it online!

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

### Explanation:

`__END__` is not part of the code and everything that follows it is returned by the iterator `DATA` as lines of text, simply count those lines and check if there are enough of them to switch from 1 to 3.

# Answer
> 2 votes
# Runic Enchantments, 35 bytes

```
^w3'\
    f
    1
/1@
/
 '54\w
/yyy

```

Try it online!

Working on this one allowed me to find an error in my parser dealing with the new delay modifier characters, although the final result ends up not being affected by it, as I ended up not needing them.

Functions due to the fact that the final line does not have a trailing newline (or for that matter, trailing spaces), allowing the duplicate IPs to spawn in a different place. The top-left one ends up making a large loop around the grid while the second IP performs a Reflection operation to replace the `\` on the 6th line with a . This IP then will loop forever and do nothing.

The third IP also makes this same replacement at the same time, but because it's situated on the *13th* line, its copy of that reflector sends it upwards and it executes the `1f'3w` sequence present in the upper right corner, which replaces the `1` with a `3` on the 14th line, just before the original IP executes it, causing the tripled program to output `3` instead of `1` (values could also be `2` and `6`, `3` and `9`, `4` and `12`, or `5` and `15` due to the availability of `a-f` numerical constants; `1` and `3` were chosen arbitrarily). It is then left in an endless loop performing more reflection commands that do nothing.

Try it in triplicate!

# Answer
> 1 votes
# Zsh, 25 bytes

```
<<<$[`wc -c<$0`>70?3:1] #

```

Zsh lets you use here-docs and here-strings in place instead of regular commands, so we can replace a call to `echo` with `<<<` which saves two bytes.

-2 thanks to Digital Trauma

# Answer
> 1 votes
# Bash, 26 bytes

```
exit $[`wc -c<$0`>70?3:1];

```

Includes trailing newline.

Outputs via exit code.

Very similar to my zsh answer.

`exit` instead of `echo` means instead of `<space>#` at the end, we only have a single `;`.

-2 bytes thanks to Digital Trauma

# Answer
> 1 votes
# Perl 5, ~~28~~ 25 bytes

-3 bytes thanks to @neil!

```
print"\e[D$a"if(++$a!=2);

```

Moves the cursor backwards (does nothing on start of line) and prints the value of `$a`, first and third time (i.e., the third time a 1 is printed, the cursor moves, and a 3 is printed on the position of the 1).

# Answer
> 1 votes
# Haskell (runhaskell), 46 bytes

*-8 bytes thanks to BMO.*

```
main=do x<-readFile"a";print$length x`gcd`3 --

```

Try it online!

Needs the file name to be `a`. Apparently GHC needs the file to end with `.hs`, but `runhaskell` doesn't care.

# Answer
> 1 votes
# DOS .BAT, 60 Bytes

```
@cls&find /n " " %0|findstr /b .^3>nul&&set/p=^1<nul&echo 5

```

# Answer
> 1 votes
# QBasic, 19 bytes

```
CLS
x=2^x
?x-1OR 1

```

The source should include a trailing newline.

### Explanation

We want output of `1`, `1`, `3`. Observe that these numbers are one less than powers of 2. So:

```
CLS      ' CLear Screen of any output from previous copies of the code

x        ' Numeric variables are preset to 0...
 =2^x    ' so as this statement is repeated, the value of x goes 1, 2, 4

 x-1     ' Therefore x-1 goes 0, 1, 3...
    OR 1 ' and we bitwise OR it with 1 to change the 0 to 1...
?        ' and print.

```

# Answer
> 1 votes
# Perl 6, 17 bytes

```
0 x 0;say .++ +|1

```

Try it online!

Try it doubled!

Try it tripled!

# Answer
> 1 votes
# Python 2, 38 bytes

```
1
id=id<3and-~id
exec"print id|1"*0**0

```

Try it online! (doubled, tripled)

Outputs 1, 1, or 3.

---

# Python 2, 33 bytes

```
1
True+=1
exec"print 7%True"*0**0

```

Try it online! (doubled, tripled)

Outputs 1,1,3. Uses the `True`-modifying idea by Aidan F. Pierce from Xcoder's solution.

# Answer
> 1 votes
# PHP, 29 bytes

```
<?=filesize(__FILE__)<86?:3;#

```

Try it online!

Try it doubled!

Try it tripled!

## How it works

* `<?=` -- Opens a PHP tag and echos whatever's inside. It's a shorthand for `<?php echo`.
* `filesize(__FILE__)` -- Gets the size of the current file.
* `<86` -- Checks that the size is less than 86 since when the code is triplicated, it's 87 bytes long.
* `?:3;` -- If the condition is true, it outputs `1` since the middle of the ternary is omitted. If not, then output 3.
* `;#` -- PHP supports shell-style comments (`#`) and they're less bytes than the C++ style comment (`//`). This just makes the compiler ignore the other two copies of code.

# Answer
> 1 votes
# Klein 000 or 010, 8 bytes

```
\((1+@
2

```

Try it online!

```
\((1+@
2\((1+@
2

```

Try it online!

```
\((1+@
2\((1+@
2\((1+@
2

```

Try it online!

## Explanation

The backbone of our program is the left had side which pushes a number of `2`s. Each time we add a copy of the program another `2` gets added to the backbone of the program. Once it goes off the bottom it executes the code

```
((1+@

```

Which removes the first 2 stack items and adds one to the remainder. Once our backbone has 3 2s we will add 1 and get 3, if we have any less we will just discard the entire stack and return 1.

# Klein 001 or 011, 8 bytes

```
\(1+@2
.

```

Try it online!

```
\(1+@2
.\(1+@2
.

```

Try it online!

```
\(1+@2
.\(1+@2
.\(1+@2
.

```

Try it online!

## Explanation

The 010 and 011 topologies work a little differently. When the ip goes of the bottom on the left it comes down on the right. Here we do something very similar except our ending bit is

```
\(1+@

```

which will output 1 until the stack is two high. The `.` causes the `2` to be cut off when we extend the program meaning we only pick up our second `2` when we reach the third iteration of the program.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 23 bytes

```
Once[c=0];c++//1-#+#^2&

```

Try it online!

Try it doubled!

Try it tripled!

### Explanation:

In Wolfram Language `Once` evaluates the contained expression once in each session, always returning the result from the first evaluation. This lets me set an anchor point for `c`. Now it's just a matter of math.

# Answer
> 1 votes
# Perl 5, 10 bytes

```
say+0|++$i

```

Try it once!

Try it twice!

Try it thrice!

# Answer
> 1 votes
# Attache, 34 bytes

```
Echo@Sum@ProperDivisors@`#<|1
'1??

```

Try it online! Implements A001065. There are probably shorter ways, but this was fun.

Prints A001065(# of repetitions + 1).

## Doubled program

## Tripled program

# Answer
> 1 votes
# Powershell, 14 bytes

Sum array elements. An operator `+` can work as a unary and binary operator.

```
+(1,0,2)[$i++]

```

Test script:

```
+(1,0,2)[$i++]

$i=0 # or start new powershell session

+(1,0,2)[$i++]+(1,0,2)[$i++]

$i=0 # or start new powershell session

+(1,0,2)[$i++]+(1,0,2)[$i++]+(1,0,2)[$i++]

```

Note: `$i=0` emulates a new session. You can `type three times` in a new powershell terminal window to start a pure test instead.

Output:

```
1
1
3

```

# Answer
> 1 votes
# Befunge-98 (PyFunge), ~~12~~ ~~9~~ 6 bytes (by Jo King)

```
3g.@
`

```

Try it once!

Try it doubled!

Try it tripled!

---

Old solution:

```
2g' `4\kc.@

```

Try it online!

# Answer
> 1 votes
# TI-Basic, 14 bytes

```

A+1→A
1+2(Ans=3

```

There is a newline at the beginning.

---

### 19 bytes

```

Ai+not(A→A
2-real(Ans)-imag(Ans

```

There is a newline at the beginning.

# Answer
> 0 votes
## Batch, 28 bytes

```
@cmd/cset/a1+2*!(%~z0%%3)
:

```

Conveniently the file length is not a multiple of 3 until the file is tripled, so it remains to take the remainder modulo 3, take the logical not, double that, and add 1.

# Answer
> 0 votes
# SmileBASIC, 18 bytes

```
X=X+1CLS?(X>2)*2+1

```

# Answer
> 0 votes
# Charcoal, 10 bytes

```
Ｐ§311Ｌ⊞Ｏυω

```

Try it online! Based on my answer to I double the source, you double the output! but I cyclically look up the appropriate character to print instead of just printing the current length cast to string. (The 3 is first because the iteration numbers are 1-indexed but Charcoal's string indexing is 0-indexed.)

# Answer
> 0 votes
# sed, 37 bytes

```
g
s/^/1/
H
s/\n//g
s/1111/3/
s/11/1/

```

Using the pattern space to preserve state is the key here.

Try it online!

# Answer
> 0 votes
# 05AB1E, 4 bytes

```
X3Ur

```

Try it online!, doubled, tripled.

```
X           # push X on the stack (X defaults to 1)
 3U         # set X = 3
   r        # reverse the stack

```

---
Tags: code-golf, source-layout
---


title: Build the stove controller (physically)

text:
# Question
Title: Build the stove controller (physically)
## Challenge

Build the Wheat Wizard's stove using 2-input NAND gates. The solution with the fewest NAND gates wins.

Externally, it works in the following way: (the first line is added from the original spec for physical output)

* It has 10 levels, from 0 to 9. The display has 9 lights, and if the current level is L, exactly L lights from the left are on and the rest are off.
* Two buttons, labeled `+` and `-`, are used to control the temperature level.
* Pressing `+` changes the level as follows:
    + 0 becomes 9
    + 9 becomes 0
    + any other number is incremented
* Pressing `-` changes the level as follows:
    + 0 becomes 4
    + any other number is decremented

In summary, the circuit must behave as a sequential circuit with two inputs (the buttons) and 9 outputs (the lights).

## Conditions

* You can use a clock signal generator if you want, at no cost in score.
* You don't need to make the power-up behavior correct.
* You will need at least a few latches or flip-flops in your circuit, in order to keep track of the current temperature level. Different latches/flip-flops cost different number of NAND gates, which is included in your score. It is your job to choose the flip-flop that gives the fewest NAND gates overall.
* One button press must affect the level exactly once, but you can choose exactly when the level changes according to input, e.g.
    + when the button is pressed
    + when the button is released
    + at the first clock tick (you can choose rising or falling edge) while the button is pressed (that button is disabled until release) - you can assume the clock cycle is short enough for this to register
* You may assume both buttons won't be pressed simultaneously.

# Answer
> 10 votes
# CircuitVerse, 455 NANDs

* 1x NOT (1 NANDs)
* 2x AND (4 NANDs)
* 3x OR (9 NANDs)
* 1x 4-bit 2x4 multiplexer (96 NANDs)
* 1x 4x1 Decoder (6 NANDs)
* 1x 4-bit adder (108 NANDs)
* 1x 2-bit Memory (54 NANDS)
* 1x 4-bit Memory (108 NANDs)
* 1x (4-bit) Is 1 (9 NANDs)
* 1x (4-bit) Is 10 (8 NANDs)
* 1x (4-bit) Is neg (2 NANDs)
* 1x 1-9 encoder (50 NANDs)

Total = 455

Try it out online! (version 1.1)

version 1.0 (NANDs 543)

---
Tags: atomic-code-golf, logic-gates
---


title: Calculate e^x and ln(x)

text:
# Question
Title: Calculate e^x and ln(x)
Given a floating point `x` (`x<100`), return `e^x` and `ln(x)`. The first 6 decimal places of the number have to be right, but any others after do not have to be correct.

You cannot have any "magic" constants explicitly stated (e.x. `a=1.35914` since `1.35914*2 ~= e`), but you can calculate them. Only use `+`, `-`, `*`, and `/` for arithmetic operators.

If x is less than or equal to 0, output `ERROR` instead of the intended value of ln(x).

Test Cases:

```
input: 2
output: 7.389056 0.693147
input: 0.25
output: 1.284025 -1.386294
input: 2.718281828
output: 15.154262 0.999999  (for this to output correctly, don't round to 6 places)
input: -0.1
output: 0.904837 ERROR

```

Shortest code wins.

# Answer
> 3 votes
## JavaScript, 103 101 99 97 93 90

This implementation is based on primo's comprehensive description of the algorithm he used.

```
for(e=l=x=prompt(g=1e5);--g;y=x-1,l=(x>1?y/=x:-y)*l+y/g)
    e=1+e/g*x;
alert([e,x>0?l:"ERROR"])

```

Edit:
\- Trying to catch Perl. Stole a byte back from primo by copying his branch. :)
\- 2 more bytes courtesy of primo.
\- Finally, caught primo's version! With primo's help, of course... :)
\- Simplified the assignment to L. Shaved 3 more bytes.

# Answer
> 10 votes
## PHP ~~109~~ 107 bytes

```
<?for($g=1e4;--$g;$l=$y/$g+abs($y=$x>1?1-1/$x:$x-1)*$l)$e=1+$e/$g*$x.=fgets(STDIN);echo"$e ",$x>0?$l:ERROR;

```

\\$e^x\\$ is a fairly straight-forward calculation. I use a nested form of the sum of inverse factorials, which not only increases the convergence rate, but also allows for exponentiation at the same time:

$$e^x = 1 + x \left( 1 + \frac x 2 \left( 1 + \frac x 3 \left( 1 + \frac x 4 \bigg( 1 + \dots \bigg)\right)\right)\right)$$

\\$\ln x\\$ is slightly more complicated. All convergent series seem to work for \\$x \le 1\\$ or \\$x \ge 1 \\$, but not both (Newton's iteration does not have this limitation, but requires the calculation of \\$e^{x\_n}\\$ each step). This isn't really a problem, though, given the log identity:

$$\ln x = -\ln \frac 1 x$$

This means that if, for example, the iteration you're using only works on \\$0 \< x \le 1\\$ and \\$x \> 1\\$, you can use the multiplicative inverse of \\$x\\$ and negate the result. Because I was using a nested identity for \\$e^x\\$, I also chose to use a nested identity for \\$\ln x\\$:

$$\ln(1 + x) = x\left(1 - x\left(\frac 1 2 - x\left(\frac 1 3 - x\left(\frac 1 4 - \dots \right)\right)\right)\right)$$

where \\$0 \< x \le 1\\$

Or equivalently, as demonstrated by Paul Walls' implementation:

$$\ln(1 + x) = x - x\left(\frac x 2 - x\left(\frac x 3 - x\left(\frac x 4 - \dots \right)\right)\right)$$

I define the \\$0 \< x \le 1\\$ case as \\$x-1\\$ (which is necessarily negative), using the absolute value for the inner product, and then allowing a bare \\$x\\$ value in the fraction to correct the sign.

Sample I/O:

```
$ echo 2 | php exp_ln.php
7.3890560989307 0.69314718055995

$ echo 0.25 | php exp_ln.php
1.2840254166877 -1.3862943611199

$ echo 2.718281828 | php exp_ln.php
15.154262234523 0.99999999983113

$ echo -0.1 | php exp_ln.php
0.90483741803596 ERROR

```

---

## Perl ~~95~~ ~~93~~ 89 bytes

```
$e=1+$e/$?*($x.=<>),$l=$_/$?+$l*abs,$_=$x>1?1-1/$x:$x-1while--$?;print"$e ",$x>0?$l:ERROR

```

Nearly identical to the PHP solution above, with a slightly larger iteration (`65535` down to `0`).

Edits:

* Both 2 byte improvements due to Paul Walls.
* Four more bytes saved in Perl by (ab)using `$?`, which is stored internally as an unsigned short, and by using `$_` to save parentheses in `abs`.

# Answer
> 4 votes
## Python 2 (168 char)

basic implementation of power series

I need to learn a golfing language =/

I increased the bound to 1e-14 (twice from 1e-7) since some values were off a bit in 6 decimal places, works well for input from 1e-5 to 100 (slows down at input approaches 0)

```
x=input();t,r,i=1,0,1.
while abs(t)>=1e-14:t,r,i=t*x/i,r+t,i+1
if x<=0:s='Error'
else:z=(x-1.)/(x+1);t,s,i=2*z,0,1
while abs(t/i)>=1e-14:t,s,i=t*z*z,s+t/i,i+2
print r,s

```

# Answer
> 4 votes
## Haskell, 166 (89 without I/O)

```
s=1e-7
e x|x>s=1/e(-x)|x>0=1+x|y<-e$x+s=y-y*s
l x|x<1=0-l(1/x)|1>0=sum$map(s/)[1,1+s..x]
n x|x<0="ERROR"|1>0=show$l x
main=interact$unwords.(\x->[show$e x,n x]).read

```

Takes an alternative approach: we use that

*∂/∂x ex* = *ex*

and solve the differential equation numerically, with a simple euler method. Similarly, use

ln *x* = 1*x* 1/*x* d*x*

and calculate the integral with the rectangular method.

Example:

> $ echo 2 | ./exp-and-log
> 7.389056835370484 0.6931472554471929
> $ echo 0.25 | ./exp-and-log
> 1.284025432730133 -1.3862944228194163
> $ echo 2.718281828 | ./exp-and-log
> 15.15426430695358 1.0000000576151333
> $ echo -0.1 | ./exp-and-log
> 0.9048374135134576 ERROR

It's quite amazingly inefficient, in fact it uses about 4 GB of memory even for these examples (since it's non-tail–recursive... you need to compile (in GHC) with `-with-rtsopts=-K2G` so it even accepts such a ridiculous stack size).

# Answer
> 1 votes
# R (101 bytes)

Note that $$e^{x} = \lim\_{n \to \infty}\left(1 + \frac{x}{n}\right)^n.$$ Then, for large enough n, we can approximate e by a product.

```
n=1e+08;prod(rep(1+x/n,n))

```

Similarly, note that $$\log(x) = \int\_{1}^{x}\frac{1}{t}dt \leq \Delta t \cdot \sum \frac{1}{t+\Delta t}$$

```
dt=0.1;sign(x-1)*sum((1/seq(min(1,x),max(1,x),by=dt))*dt))

```

Combined into one **answer** (80 bytes):

```
n=1e+08;c(prod(rep(1+x/n,n)),sign(x-1)*sum((1/seq(min(1,x),max(1,x),by=1/n))/n))

```

Will produce `-Inf` instead of `ERROR` in case `x < 0`.

```
[1] 7.3890560 0.6931472
[1]  1.284025 -1.386294
[1] 15.15426  1.00000
[1] 0.9048374      -Inf

```

---

Or, with the `ERROR` handling, `101 bytes`:

```
n=1e+08;gsub("-Inf","ERROR",c(prod(rep(1+x/n,n)),sign(x-1)*sum((1/seq(min(1,x),max(1,x),by=1/n))/n)))

```

```
[1] "7.38905602540599"  "0.693147188059945"
[1] "1.28402541433558"  "-1.38629438611989"
[1] "15.154261581541"  "1.00000000372749"
[1] "0.904837420549773" "ERROR"

```

---
Tags: code-golf, math
---


# Question
Title: Cause maximal disruption to a Straw Poll
## Context

Straw Poll is a website that is meant for the creation of simple/informal polls. Provided with a list of options, the user can select their choice(s), and the votes are tallied up. There's two very important features of a Straw Poll:

* It is possible to view the current results before voting
* It is often possible to select multiple options, which is treated the same way as if you voted multiple times, one for each option.

The one thing that's more fun than making Straw Polls is messing with the results. There's two main types of disruption:

* Simple disruption, in which you vote for all the options
* Advanced disruption, in which you strategically pick which options to vote for in order to maximize the effect.

In this challenge, you will write a program for *advanced* disruption.

## The Math

To simply things mathematically, we can say that *the higher the entropy of the votes, the more disrupted a poll is.* This means that a poll where a single option has all the votes isn't disrupted at all, while a poll where every option has an equal number of votes is maximally disrupted (this being the ultimate goal).

The entropy of a list of numbers \\$\[x\_1, x\_2, \dots x\_n\]\\$ is given by the following equation from Wikipedia. \\$P(x\_i)\\$ is the probability of \\$x\_i\\$, which is \\$\frac {x\_i} {\sum^n\_{i=1} x\_i}\\$. If an option has received zero votes so far, it is simply not included in the summation (to avoid \\$\log(0)\\$). For our purposes, the logarithm can be in any base of your choice.

$$H(X) = \sum^n\_{i=1} P(x\_i) I(x\_i) = -\sum^n\_{i=1} P(x\_i) \log\_b P(x\_i)$$

As an example, the entropy of \\$\[3,2,1,1\]\\$ is approximately \\$1.277\\$, using base \\$e\\$.

The next step is to determine what voting pattern leads to the greatest increase in entropy. I can vote for any subset of options, so for example my vote could be \\$\[1,0,1,0\]\\$. If these were my votes, then the final tally is \\$\[4,2,2,1\]\\$. Recalculating the entropy gives \\$1.273\\$, giving a *decrease* in entropy, which means this is a terrible attempt at disruption. Here are some other options:

```
don't vote
[3,2,1,1] -> 1.277

vote for everything
[4,3,2,2] -> 1.342

vote for the 1s
[3,2,2,2] -> 1.369

vote for the 2 and 1s
[3,3,2,2] -> 1.366

```

From this, we can conclude that the **optimal voting pattern** is \\$\[0,0,1,1\]\\$ since it gives the greatest increase in entropy.

## Input

Input is a non-empty list of non-increasing, non-negative integers. Examples include \\$\[3,3,2,1,0,0\]\\$, \\$\[123,23,1\]\\$, or even \\$\[4\]\\$. Any reasonable format is allowable.

## Output

Output is a list (the same length as input) of truthy and falsey values, where the truths represent the options for which I should vote if I desired to cause maximal disruption. If more than one voting pattern gives the same entropy, either one can be output.

## Winning Criterion

This is code-golf, fewer bytes are better.

## Test Cases

```
[3,2,1,1] -> [0,0,1,1]  (from 1.227 to 1.369)

[3,3,2,1,0,0] -> [0,0,0,1,1,1] (from 1.311 to 1.705)

[123,23,1] -> [0,1,1] (from 0.473 to 0.510)

[4] -> [0] OR [1] (from 0 to 0)

[7,7,6,6,5] -> [0,0,1,1,1] (from 1.602 to 1.608)

[100,50,1,1] -> [0,1,1,1] (from 0.707 to 0.761)

```

# Answer
# Mathematica, ~~19~~ 44 bytes

...(loud complaining)

```
(x=Median@#[[;;Mod[Length@#,2]-3]];#≤x&/@#)&

```

Test:

```
{Test, data, goes, here};
(x=Median@#[[;;Mod[Length@#,2]-3]];#≤x&/@#)&
%%+Boole/@%

```
> 4 votes

# Answer
# Pyth - 25 bytes

```
hosm*FlBcdsGfT=G+VQN^U2lQ

```

Test Suite.
> 3 votes

# Answer
# MATL, 24 bytes

```
FTinZ^tG+!ts/tYl*s4#X<Y)

```

This works with version 13.0.0 of the language/compiler, which is earlier than the challenge.

**Try it online!**

### Explanation

```
FT        % array [0 1]
in        % take input and push its length
Z^        % Cartesian power. This gives all possible vote patterns, each on a row
t         % duplicate (will be indexed into at the end to produce the result)
G         % push input again
+         % element-wise addition with broadcast
!         % transpose
ts/       % duplicate. Divide each column by its sum
tYl       % duplicatte. Take natural logarithm
*         % element-wise multiplication
s         % sum of each column. Gives minus entropy produce by each vote pattern
4#X<      % arg max
Y)        % index into original array of voting patterns. Implicitly display

```

### Example

Here's an example of how it works. For input `[3 2 2]`, the array of possible voting patterns (produced by `Z^`) is

```
[ 0 0 0
  0 0 1
  0 1 0
  0 1 1
  1 0 0
  1 0 1
  1 1 0
  1 1 1 ]

```

where each row is a pattern. This is added to the original `[3 2 0]` with broadcast (`G+`). That means `[3 2 0]` is replicated `8` times vertically and then added element-wise to give

```
[ 3 2 2
  3 2 3
  3 3 2
  3 3 3
  4 2 2
  4 2 3
  4 3 2
  4 3 3 ]

```

This is transposed and each column is divided by each sum (`!ts/`):

```
[ 0.4286    0.3750    0.3750    0.3333    0.5000    0.4444    0.4444    0.4000
  0.2857    0.2500    0.3750    0.3333    0.2500    0.2222    0.3333    0.3000
  0.2857    0.3750    0.2500    0.3333    0.2500    0.3333    0.2222    0.3000 ]

```

Multiplying by its logarithm and summing each column (`tYl*s`) gives minus the entropy:

```
[ -1.0790   -1.0822   -1.0822   -1.0986   -1.0397   -1.0609   -1.0609   -1.0889 ]

```

The minus entropy is minimized (`4#X<`) by the `4`th vote pattern, which corresponds (`Y)`) to the final result `[0 1 1]`.
> 2 votes

# Answer
# Jelly, 17 bytes

```
LØ.ṗ+ḟ0÷SḋÆl$ƊɗÐṂ

```

Try it online!

## How it works

```
LØ.ṗ+ḟ0÷SḋÆl$ƊɗÐṂ - Main link. Takes a list A on the left
L                 - Length of A
 Ø.ṗ              - Cartesian power of [0, 1] to the length of A
              ɗÐṂ - Output the bitlist B with the minimum value f(B, A):
    +             -   Add the elements of B to A
     ḟ0           -   Remove any zeros
             Ɗ    -   Last 3 links as a monad g(A+B \ {0}):
       ÷S         -     Divide each by the sum
            $     -     Last 2 links as a monad h([A+B \ {0}] ÷ sum):
          Æl      -       Natural log of each
         ḋ        -       Dot product

```
> 2 votes

---
Tags: code-golf, math, statistics
---


title: Fibonacci-like gap formula

text:
# Question
Title: Fibonacci-like gap formula
## Background

The recurrence of the Fibonacci sequence is defined as

$$ f(n+2) = f(n+1) + f(n) $$

From this recurrence alone, the following *gap formulae* (recurrences relating three terms with certain amount of gaps) can be derived:

$$ f(n+4) = 3f(n+2) - f(n) \\ f(n+6) = 4f(n+3) + f(n) \\ f(n+8) = 7f(n+4) - f(n) $$

You might have seen the \\$n+6\\$ formula if you have worked on Project Euler #2 hard enough :)

In general, for any \\$a \in \mathbb{Z}^+\\$ (positive integers), there exist unique integer coefficients \\$\alpha, \beta\\$ of the generalized gap formula

$$ f(n+2a) = \alpha f(n+a) + \beta f(n) $$

which holds for all \\$n\\$.

We can generalize the Fibonacci recurrence itself too:

$$ f'(n+2) = uf'(n+1) + vf'(n) $$

Then it can be shown that, for any \\$a \in \mathbb{Z}^+\\$ and \\$u,v \in \mathbb{Z}\\$, there exists a fully general gap formula with integer coefficients:

$$ f'(n+2a) = \alpha f'(n+a) + \beta f'(n) \tag{1}\label{eq1} $$

Note that such a formula is not unique for some values of \\$u, v, a\\$.

## Challenge

Given the values of \\$a, u, v\\$, calculate the pair of values of \\$\alpha\\$ and \\$\beta\\$ in the equation \\$\eqref{eq1}\\$. You don't need to handle cases where the answer is not unique.

All three inputs are guaranteed to be integers. \\$a\\$ is strictly positive.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
For u = 1, v = 1
a = 1 -> alpha = 1, beta = 1
a = 2 -> alpha = 3, beta = -1
a = 3 -> alpha = 4, beta = 1
a = 4 -> alpha = 7, beta = -1

For u = -2, v = 3
a = 1 -> alpha = -2, beta = 3
a = 2 -> alpha = 10, beta = -9
a = 3 -> alpha = -26, beta = 27
a = 4 -> alpha = 82, beta = -81

For u = 3, v = -9
a = 1 -> alpha = 3, beta = -9
a = 2 -> alpha = -9, beta = -81
a = 3 -> undefined (not unique)
a = 4 -> alpha = -81, beta = -6561
a = 5 -> alpha = 243, beta = -59049
a = 6 -> undefined (not unique)

```

# Answer
# Pari/GP, 37 bytes

Saved 13 bytes thanks to @xnor.

```
(u,v,n)->[-(-v)^n,trace([0,1;v,u]^n)]

```

Try it online!
> 9 votes

# Answer
# Python 3.8 (pre-release), ~~60~~ 58 bytes

```
lambda u,v,a:[(p:=u/2-(u*u/4+v)**.5)**a+(u-p)**a,-(-v)**a]

```

Try it online!

*¯2 thanks to @tsh*

Originally based on @tsh's answer (now removed due to no complex number support)
> 6 votes

# Answer
# Jelly, ~~13~~ 12 bytes

```
Ø.,æ*ÆḊN,ÆṭƲ

```

Try it online!

Takes input as `[v, u]` on the left, and `a` on the right. Outputs as `[β, α]`

-1 byte thanks to ovs!

Uses xnor's formula that

$$\alpha = \operatorname{tr} \left( \begin{bmatrix} 0 & 1 \\ v & u \end{bmatrix}^a \right) \\ \beta = -(-v)^a = - \det \left( \begin{bmatrix} 0 & 1 \\ v & u \end{bmatrix}^a \right)$$

## How it works

```
Ø.,æ*ÆḊN,ÆṭƲ - Main link. Takes [v, u] on the left, a on the right
Ø.           - Yield [0, 1]
  ,          - Pair; [[0, 1], [v, u]]
   æ*        - Matrix power to a; Call this M
           Ʋ - Last 4 links as a monad f(M):
     ÆḊ      -   Determinant of M
       N     -   Negated
         Æṭ  -   Trace of M
        ,    -   Pair; [-det(M), tr(M)]

```
> 6 votes

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

```
(u,v,a)=>[A=(F=n=>n<2?n^m:u*F(n-1)+v*F(n-2))(a+a,m=0)/F(a),F(a+a,m=1)-A*F(a)]

```

Try it online!

Let

$$ f\_1\left(0\right)=0 \\ f\_1\left(1\right)=1 \\ f\_1\left(n+2\right)=u\cdot f\_1\left(n+1\right)+v\cdot f\_1\left(n\right) $$

Calculate

$$ p=f\_1(2a) \\ q=f\_1(a) $$

Let

$$ f\_2\left(0\right)=1 \\ f\_2\left(1\right)=0 \\ f\_2\left(n+2\right)=u\cdot f\_2\left(n+1\right)+v\cdot f\_2\left(n\right) $$

Calculate

$$ r=f\_2(2a) \\ s=f\_2(a) $$

We have

$$ p=\alpha\cdot q \\ r = \alpha \cdot s + \beta $$

Solve

$$ \alpha=\frac{p}{q} \\ \beta=r-\alpha \cdot s $$

---

Try to undelete this question since all failed testcases currently known had been been excluded from the question. Maybe this one is correct, but I'm not quite sure.
> 4 votes

# Answer
# , 59 bytes

Or **\>=4.1, 52 bytes** by replacing the word `function` with `\`.

```
function(u,v,a)c((p=u/2-(u^2/4+v+0i)^.5)^a+(u-p)^a,-(-v)^a)

```

Try it online!

Based on @xnor's formula and @PyGamer0's answer.

Outputs complex numbers - for pretty integers add 4 bytes for wrapping result in `Re`.
> 4 votes

# Answer
# 05AB1E, ~~23~~ 22 bytes

```
0L‚©IF®øδ*O}Å\O¹θ(Im(‚

```

Port of *@cairdCoinheringaahing*'s Jelly answer, but without matrix power/multiplication, trace, nor determinant builtins. It uses a slight modification of *@xnor*'s formula:

\\$\alpha = \operatorname{tr} \left( \begin{bmatrix} u&v\\1&0 \end{bmatrix}^a \right) \\ \beta = -(-v)^a\\$

Inputs as `[u,v]` and `a`.

Try it online or verify all test cases.

**Explanation:**

```
0L          # Push [1,0]
  ‚         # Pair it with the (implicit) input-pair: [[u,v],[1,0]]
   ©        # Store it in variable `®` (without popping)
    IG      # Loop the second input `a` - 1 amount of times:
      ®     #  Push the matrix from variable `®`
       ø    #  Zip/transpose it; swapping rows/columns
        δ   #  Apply double-vectorized over the two matrices:
         *  #   Multiply them together
          O #  And then sum each inner-most list
     }Å\    # After the loop: pop the matrix and push its main diagonal
        O   # Sum it together
¹           # Push the first input-pair again
 θ          # Pop and only leave the last item (`v`)
  (         # Negate it
   Im       # Take it to the power of the second input `a`
     (      # Negate that again
‚           # Pair the two integers together
            # (after which this pair [α,β] is output implicitly as result)

```
> 3 votes

# Answer
# Charcoal, 38 bytes

```
ＮθＮη⊞υ²⊞υθＦ⊖Ｎ⊞υ⁺×θ§υ±¹×η§υ±²Ｉ⟦⊟υ±Ｘ±ηＬυ

```

Try it online! Link is to verbose version of code. Explanation: Uses @xnor's formula.

```
ＮθＮη

```

Input `u` and `v`.

```
⊞υ²⊞υθ

```

Push `2` and `u` to the predefined empty list.

```
Ｆ⊖Ｎ⊞υ⁺×θ§υ±¹×η§υ±²

```

Calculate `a-1` more terms so that the last term is now the `a`th term.

```
Ｉ⟦⊟υ±Ｘ±ηＬυ

```

Remove and output the `a`th term, then calculate the power using the remaining length which is now `a`.
> 2 votes

---
Tags: code-golf, math, fibonacci
---


title: Not too hard to code this right?

text:
# Question
Title: Not too hard to code this right?
You have to write a program or a function in any language that outputs this pattern:

```
~|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||~
|~|||||||||||||||||||||||||||||||||||||||||||||||||||||||||~|
||~|||||||||||||||||||||||||||||||||||||||||||||||||||||||~||
|||~|||||||||||||||||||||||||||||||||||||||||||||||||||||~|||
||||~|||||||||||||||||||||||||||||||||||||||||||||||||||~||||
|||||~|||||||||||||||||||||||||||||||||||||||||||||||||~|||||
||||||~|||||||||||||||||||||||||||||||||||||||||||||||~||||||
|||||||~|||||||||||||||||||||||||||||||||||||||||||||~|||||||
||||||||~|||||||||||||||||||||||||||||||||||||||||||~||||||||
|||||||||~|||||||||||||||||||||||||||||||||||||||||~|||||||||
||||||||||~|||||||||||||||||||~|||||||||||||||||||~||||||||||
|||||||||||~|||||||||||||||||~|~|||||||||||||||||~|||||||||||
||||||||||||~|||||||||||||||~|||~|||||||||||||||~||||||||||||
|||||||||||||~|||||||||||||~|||||~|||||||||||||~|||||||||||||
||||||||||||||~|||||||||||~|||||||~|||||||||||~||||||||||||||
|||||||||||||||~|||||||||~|||||||||~|||||||||~|||||||||||||||
||||||||||||||||~|||||||~|||||||||||~|||||||~||||||||||||||||
|||||||||||||||||~|||||~|||||||||||||~|||||~|||||||||||||||||
||||||||||||||||||~|||~|||||||||||||||~|||~||||||||||||||||||
|||||||||||||||||||~|~|||||||||||||||||~|~|||||||||||||||||||

```

The output is composed of 20 lines of 61 characters each.

# Rules

* Standard loopholes are forbidden
* There may be a single trailing newline at the end of the output
* There may not be any trailing whitespace on any line of the output

Without a trailing newline, the md5 checksum of the output is `fde4e3b4606bf9f8c314131c93988e96`.

With a trailing newline, the md5 checksum of the output is `1f0b43db4fec6594be202c8339024cb7`.

This is , so the shortest code in bytes wins.

# Answer
> 15 votes
# C (gcc), ~~97~~ ~~82~~ ~~81~~ 80 bytes

Golfed 15 bytes after learning that `abs` is a builtin in C, an additional byte thanks to Rogem for pointing out that the declarations of my variables can be moved to the function, and another byte thanks to ceilingcat for suggesting `x=31;--x+31` instead of `x=-31;++x<31`.

```
f(x,y){for(y=21;--y;puts(""))for(x=31;--x+31;)printf(abs(10-abs(x))-y?"|":"~");}

```

Try it online!

This outputs with a trailing newline. The function `f` does the outputting.

### Explanation

The output can be stated as a graph.

```
~|||||||||||||||||||||||||||||+|||||||||||||||||||||||||||||~
|~||||||||||||||||||||||||||||+||||||||||||||||||||||||||||~|
||~|||||||||||||||||||||||||||+|||||||||||||||||||||||||||~||
|||~||||||||||||||||||||||||||+||||||||||||||||||||||||||~|||
||||~|||||||||||||||||||||||||+|||||||||||||||||||||||||~||||
|||||~||||||||||||||||||||||||+||||||||||||||||||||||||~|||||
||||||~|||||||||||||||||||||||+|||||||||||||||||||||||~||||||
|||||||~||||||||||||||||||||||+||||||||||||||||||||||~|||||||
||||||||~|||||||||||||||||||||+|||||||||||||||||||||~||||||||
|||||||||~||||||||||||||||||||+||||||||||||||||||||~|||||||||
||||||||||~|||||||||||||||||||+|||||||||||||||||||~||||||||||
|||||||||||~|||||||||||||||||~+~|||||||||||||||||~|||||||||||
||||||||||||~|||||||||||||||~|+|~|||||||||||||||~||||||||||||
|||||||||||||~|||||||||||||~||+||~|||||||||||||~|||||||||||||
||||||||||||||~|||||||||||~|||+|||~|||||||||||~||||||||||||||
|||||||||||||||~|||||||||~||||+||||~|||||||||~|||||||||||||||
||||||||||||||||~|||||||~|||||+|||||~|||||||~||||||||||||||||
|||||||||||||||||~|||||~||||||+||||||~|||||~|||||||||||||||||
||||||||||||||||||~|||~|||||||+|||||||~|||~||||||||||||||||||
|||||||||||||||||||~|~|||||||||||||||||~|~|||||||||||||||||||
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

```

(The `+`s are only shown for explanation purposes and represent the axes.)

The equation of this graph is \\$y=\text{abs}(10-\text{abs}(x))\\$ as can be seen here in this link to a Desmos graph.

```
abs(10 - abs(x))
abs(           )            Reflect whatever is beneath the x-axis to above the x-axis
    10 - abs(x)             This forms the central triangle-like structure

```

In function `f`, we have two for-loops that iterate through every coordinate in this graph. `y` goes from `20` to `1` and x goes from `-30` to `30`.

For every `x`, we check if `abs(10-abs(x))` equals `y` by doing `abs(10-abs(x))-y` in a ternary. If they are equal, this yields `0`, a falsey value in C, otherwise it will evaluate to some positive value. Then in the ternary `abs(10-abs(x))-y?"|":"~"`, we `printf` accordingly.

And after each line, we output a newline using `puts("")`, and that is how the function outputs with a trailing newline.

# Answer
> 11 votes
# Charcoal, ~~16~~ 15 bytes

-1 byte thanks to notjagan

```
↘×~²⁰↗↗×~χ‖ＯＵＢ|

```

Try it online!

# Answer
> 4 votes
# , ~~70~~ 67 bytes

3 bytes thanks to Giuseppe.

```
write(c("|","~")[outer(abs(10-abs(-30:30)),20:1,"==")+1],"",61,,"")

```

Try it online!

# Answer
> 3 votes
# Python 2.7, ~~163~~ ~~138~~ ~~135~~ ~~133~~ ~~113~~ 91 bytes

```
l,t=S='|~'
for s in range(20):a=[l]*61;a[s]=a[60-s]=t;a[40-s]=a[20+s]=S[s>9];print`a`[2::5]

```

Try it online!

Edit 1: -25 bytes: changed the algorithm after I felt a bit ambitious. :P

Edit 2: -3 bytes: courtesy Felipe Nardi Batista

Edit 3: -2 bytes: courtesy shooqie

Edit 4: -20 bytes: courtesy notjagan

Edit 5: -22 bytes: courtesy Leaky Nun

# Answer
> 3 votes
# Jelly, ~~18~~ 16 bytes

```
⁵×3ŒRAạ=þḤṚị⁾~|Y

```

Try it online!

```
⁵×3ŒRAạ=þḤṚị⁾~|Y  Main link. No arguments.

⁵                 Set the argument and the return value to 10.
 ×3               Multiply by 3 to yield 30.
   ŒR             Balanced range; yield [-30, -29, ..., 29, 30].
     A            Take absolute values.
      ạ           Take absolute differences with 10.
         Ḥ        Unhalve; yield 20.
       =þ         Table equals; compare each result with each k in [1, ..., 20].
          Ṛ       Reverse the resulting 2D array.
           ị⁾~|   Index into "~|", yielding '~' for 1 and '|' for 0.
               Y  Separate by linefeeds.

```

# Answer
> 3 votes
# ///, 231 bytes

```
/3/|~//2/\/\///1/!!20/|
2-/&#2,/|#2'/"""2&/||2%/1|2#/&~2"/1!2!/&&|/~'%,
3'1#0#'1~&
,'!,&0-'!3&&
!~'-!
!3'#!0!#'~!&
!,""%#!&0!-""%~!&&
1~"-"-1
%~"#3"#%
1#"~,"~%0%#%#!~%#%&
%,%~!#%~%&0"~!-!-!-"
"3!#%~!#"0"#!~%#!~"&
",,"~,"&0"-3"#3"&&

```

Try it online! Or, view it interactively here!

# Answer
> 3 votes
# WendyScript, 65 bytes (exclude newline)

```
<<a=>(x)?x<0/>-x:/>x
#y:20->0{#x:-30->31?a(10-a(x))==y@"~":@"|"""}

```

Try it online!

Follows the same principle as the C answer given above. The first line is the `abs` function, second line runs two for loops and outputs `~` or `|` based on the graph. The last `""` is used to output a newline after each loop on `y`.

# Answer
> 2 votes
# Vim, 59 Bytes

```
2i~^[59i|^[qqYpi|^[f~l2xA|^[q18@q11G31|qqr~jlq9@qF~2lqqr~klq8@q

```

Where `^[` is the `<ESC>` key

# Answer
> 2 votes
# Japt, 32 bytes

```
20ç|
AÆhX'~
VméA
VpWUVmw)c ê z ·

```

Try it online! Be sure to expand the output box.

## Explanation

```
20ç|

```

Set `U` to `|` repeated 20 times.

```
AÆhX'~

```

Set `V` to the range `[0,9]` () mapped by:
`U` (implicit) with the character at index `X` (current value) set to (`h`) `~`.

```
VméA

```

Set `W` to `V` with each line rotated 10 (`A`) chars right.

```
VpWUVmw

```

Create array: `V, W, U`, and `V` with each line reversed (`w`). This is now the left half of the shape, rotated 90° left.

```
c ê z ·

```

Flatten the array (`c`), palendromize it (`ê`), rotate 90° right (`z`), and join with newlines (`·`).

# Answer
> 2 votes
# **Octave, ~~157~~ ~~57~~ 54 bytes**

Golfed it further down, thanks to the other answers and the comments.

```
a=zeros(20,61);for i=-30:30;a(21-abs(10-abs(i)),i+31)=2;end
a=char(a+124)

```

I just approached it like the other answer with the abs(10-abs(x)) function and then used the right ASCII characters to print out the image.

# Answer
> 2 votes
# Paintbrush, 36 bytes

### non-competing

```
b|20{s~>v}10{>^s~}9{>vs~}>v20{>^s~}▁

```

## Explanation

```
b|20{s~>v}10{>^s~}9{>vs~}>v20{>^s~}▁  Program
b|                                    Sets the background character to `|`
  20{    }                            Executes function 20 times
     s~                               Sets the current character to `~`
       >v                             Moves one space right and one space down
          10{    }                    Executes function 10 times
             >^                       Moves one space right and one space up
               s~                     Sets the current character to `~`
                  9{    }             Executes function 9 times
                    >v                Moves one space right and one space down
                      s~              Sets the current character to `~`
                         >v           Moves one space right and one space down
                           20{    }   Executes function 20 times
                              >^      Moves one space right and one space up
                                s~    Sets the current character to `~`
                                   ▁  Cuts off the last line (because it pads an extra line when the pointer moves near the edge)

```

This reminds me, I need to add a mirror operation.

# Answer
> 1 votes
# Pyth, 22 bytes

```
j_t.tm+*\|aTa30d\~61\|

```

Try it online!

# Answer
> 1 votes
# , 30 bytes

```
i~³°|19ñÙé|$xñ22|òr~klòÎæ$0Px

```

Try it online!

# Answer
> 1 votes
# Jelly, 18 bytes

```
61Rạ31ạ⁵Ṭ€z0Ṛị⁾~|Y

```

Try it online!

# Answer
> 1 votes
# Bubblegum, 90 bytes

```
00000000: 9dcb a10d 0040 08c5 50cf cc4d 673f 85ab  .....@..P..Mg?..
00000010: b880 22fd 7972 3f07 ef98 e1cc 85e1 ca05  ..".yr?.........
00000020: 8623 97d5 78c2 abf1 8457 e305 b31a 0f78  .#..x....W.....x
00000030: f507 0fcc 54fc 6ed3 794b b6d2 c1ed 163a  ....T.n.yK.....:
00000040: b8dd 42c7 68b7 d031 f757 3ab8 dd42 07b7  ..B.h..1.W:..B..
00000050: 5be8 e076 0b1d dcaf 060f                 [..v......

```

Try it online!

# Answer
> 1 votes
# MathGolf, 22 bytes

```
I{S╒xñ♂-±Iï--mÆ┬û|~§yp

```

Try it online!

## Explanation

It's probably possible to golf away 2-3 bytes from this, I'll see what I can do.

```
I                        push 20
 {                       start block or arbitrary length
  S                      push 30
   ╒                     range(1,n+1)
    x                    reverse int/array/string
     ñ                   pop(a), push palindromize(a) string/list/number
      ♂                  push 10
       -                 pop a, b : push(a-b)
        ±                absolute value
         I               push 20
          ï              index of current loop, or length of last loop
           -             pop a, b : push(a-b)
            -            pop a, b : push(a-b)
             m           explicit map
              Æ          start block of length 5
               ┬         check if equal to 0
                û|~      string "|~"
                   §     get from array/string
                    y    join array without separator to string or number
                     p   print with newline

```

# Answer
> 1 votes
# C (gcc), 75 bytes

```
f(x){for(x=1240;--x;)putchar(x%62?x/62+1-abs(10-abs(x%62-31))?124:126:10);}

```

Try it online!

Totally changed from Cows quack's answer

# Answer
> 1 votes
# 05AB1E, ~~20~~ 19 bytes

```
20F„|~20Ýû31∍ûNQèJ,

```

Try it online.

**Explanation:**

```
20F               # Loop 20 times:
   „|~            #  Push the string "|~"
   20Ý            #  List of range [0,20]
      û           #  Palindromize [0..20..0]
       31∍        #  Shorten to length 31 [0..20..10]
          û       #  Palindromize again [0..20..10..20..0]
           NQ     #  Check if the loop index is equal to it
             è    #  And index it into the string
              J   #  Then join the list of characters together
               ,  #  And print with trailing newline

```

`20Ýû31∍û` generates the list:

```
[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,19,18,17,16,15,14,13,12,11,10,11,12,13,14,15,16,17,18,19,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0]

```

# Answer
> 1 votes
# PowerShell, 64 bytes

```
0..19|%{$y=$_
-join(0..20+19..10+11..19+20..0|%{'|~'[$_-eq$y]})}

```

Try it online!

The four-part diagram with a linear function `y=x`

# Answer
> 0 votes
# Positron, 165 bytes

```
i=0;while(i<20)do{k='|'*(59-2*i);if(i==10)then{j='|'*19;k=j+'~'+j;};if(i>10)then{q=39-2*i;j='|'*q;q=2*i-21;k=j+'~'+'|'*q+'~'+j;}print@('|'*i+'~'+k+'~'+'|'*i);i=i+1;}

```

Try it online!

I think Positron has too many bugs in it. I should get it updated to TIO because then `++` will actually work.

# Answer
> 0 votes
## Mathematica, ~~78~~ 75 bytes

```
Print[""<>Riffle[Array[If[#+Abs[10-Abs[31-#2]]==21,"~","|"]&,{20,61}],"\n"]]

```

except the `\n` is replaced by an actual newline. Try it online! (There are extra spaces at the starts of the lines in Mathics for some reason, but it works fine in Mathematica.)

I came up with a submission of my own, but then Kritixi Lithos added an explanation of theirs and it was quite similar to mine but using a slightly cleverer formula, so now this is just a port of that answer. (Go and read that one and upvote it!)

# Answer
> 0 votes
# Bubblegum, 93 bytes

```
00000000: 9dcb 390e 4301 10c2 d09e 335b 9c3d 5d56  ..9.C.....3[.=]V
00000010: e72f 4c35 327a 65bf 86ee 9830 f342 5879  ./L52ze....0.BXy
00000020: 8130 f202 848d 9797 a613 262c bc7c 6a3a  .0........&,.|j:
00000030: 60c2 552e 9858 bcdc a2f9 55ac 9916 5e6f  `.U..X....U...^o
00000040: a285 d79b 6819 eb4d b4cc fe99 165e 6fa2  ....h..M.....^o.
00000050: 85d7 9b68 e1d5 26da 782f 3578 00         ...h..&.x/5x.

```

Try it online!

# Answer
> 0 votes
# Tcl, 104 bytes

```
time {incr j
set i 0
time {puts -nonewline [expr 21-abs(abs([incr i]-31)-10)-$j?"|":"~"]} 61
puts ""} 20

```

Try it online!

---

~~Tcl, 105 bytes
```
time {incr j
set i 0
time {puts -nonewline [expr $j==21-abs(abs([incr i]-31)-10)?"~":"|"]} 61
puts ""} 20

```
Try it online!
~~

---

~~Tcl, 109 bytes
```
time {incr j;set i 0;time {append s [expr $j==21-abs(abs([incr i]-31)-10)?"~":"|"]} 61;set s $s\n} 20
puts $s

```
Try it online!
Tcl, ~~143 133 123~~ 110 Still much ungolfed, but I will evolve it after:
```
time {incr j;set i 0;time {incr i;append s [expr $j==21-abs(abs($i-31)-10)?"~":"|"]} 61;set s $s\n} 20
puts $s

```
demo~~

# Answer
> 0 votes
# JavaScript (ES6), 87 bytes

```
for(a=Math.abs,y=20;y--;console.log(s))for(s='',x=-30;x<31;x++)s+=a(10-a(x))+~y?'|':'~'
```

# Answer
> 0 votes
## Lua, 193 bytes

```
m={}function g(x,y)if(x<62)then
m[x+y*61]="~"if(x==31or x==21or x==41)then
b=not b
end
g(x+1,y+((b and-1)or 1))end
end
g(1,0)for y=0,19 do
s=""for x=1,61 do
s=s..(m[x+y*61]or"|")end
print(s)end
```

Note that Lua cannot print something out without creating a new line. For this reason, I have to break one of the rules.

Minimally minified to a large extent:

```
map={}
o=20
p=61
--b is true means go up
function bounce(x,y,c)
    if (x~=p)then
        map[x+y*p]=c
        if(x==31 or x==21 or x==41)then
            b=not b

        end
        bounce(x+1,y+((b and -1) or 1),c)
    end
end
bounce(1,0,"~")
--map[2+60] = "h"
for y=0,o-1 do
    str = ""
    for x=1,p do
        str = str..(map[x+y*p] or "|")
    end
    print(str)
end

```

Some changes where made during minification, all of which makes the program less extendable but smaller.

Try it: https://tio.run/##PY7LCoMwEEX3@YqQVVJTcWwRCp0vKV1oNa1QJ0UjGPr49TRq6eoO91wOcx/LEDp8vs1IF9da4lc5aa9aI6djkSt3a4h1pynxmwLOKD5iJog7sD2Pmf9yD@u0QrKOV6yhmkVTAtonUla8pHoLKm5BqZmtHHSmTCw9ZhoOvLZsQCHMogRdwNoMaSr/L9hevMSiePQtOTnMdwhf

I'm not sure if anyone has done this before, but I tried minifying by loading the program as a string and using gsub(search/replace). Unfortainitly, it made the program bigger. However, if this program was big enough, it would yield in less bytes.

```
g=string.gsub
loadstring(g(g(g('m={}function g(x,y)if(x<62vm[x+y*61]="~"if(x==31zx==21zx==41vb=not beg(x+1,y+((b and-1)z1))eeg(1,0)fzy=0,19 do s=""fzx=1,61 do s=s..(m[x+y*61]z"|")eprint(s)e','e',' end '),'v',')then '),'z','or '))()
```

Due to its relative closeness with the real result(240 bytes, only 41 more), I figured I'd post it. If this program where 350+ bytes, there would have likely been a reduction.

# Answer
> 0 votes
# Java 8, 113 bytes

```
v->{String r="";for(int i=-1,j;++i<20;r+="\n")for(j=61;j-->0;)r+=j==i|j+i==60|i>9&(j-i==20|j+i==40)?"~":"|";return r;}

```

I have the feeling the checks (`j==i|j+i==60|i>9&(j-i==20|j+i==40)` can definitely be golfed by somehow combining multiple checks into one.

**Explanation:**

Try it here.

```
v->{                    // Method with empty unused parameters and String return-type
  String r="";          //  Result-String
  for(int i=-1,j;       //  Index integers
      ++i<20;           //  Loop (1) from 0 to 20 (exclusive)
      r+="\n")          //    After every iteration: append a new-line to the result-String
    for(j=61;           //   Reset `j` to 61
        j-->0;)         //   Inner loop (2) from 60 down to 0 (inclusive)
      r+=               //    Append the result-String with:
         j==i           //     If `j` and `i` are equal (top-right /),
         |j+i==60       //     or `j` + `i` is 60 (top-left \),
         |i>9           //     or we're at the bottom halve
          &(j-i==20     //      and `j` - `i` is 20 (bottom left \),
            |j+i==40)?  //      or `j` + `i` is 40 (bottom right /)
          "~"           //       Append a literal "~" to the result-String
         :              //     Else:
          "|";          //      Append a literal "|" to the result-String
                        //   End of inner loop (2) (implicit / single-line body)
                        //  End of loop (1) (implicit / single-line body)
  return r;             //  Return the result-String
}                       // End of method

```

# Answer
> 0 votes
# Perl 5, 79 bytes

```
push@a,[('|')x61]for 1..21;map$a[20-abs 10-abs][$_+30]='~',-30..30;say@$_ for@a

```

Try it online!

# Answer
> 0 votes
# Python 3, 90 bytes

1 byte smaller than the other Python answer :)

Outputs with a trailing newline.

```
for y in range(20):print(''.join('~'if 20-y==abs(10-abs(x))else'|'for x in range(-30,31)))

```

Try it online!

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---