# Question
Title: Convert Japanese Mario titles to American titles
The naming conventions for games in the Super Mario series is very strange, and don't match up between regions.

```
| Japanese Name       | American Name                      |
|---------------------|------------------------------------|
| Super Mario Bros.   | Super Mario Bros.                  |
| Super Mario Bros. 2 | Super Mario Bros.: The Lost Levels |
| Super Mario USA     | Super Mario Bros. 2                |
| Super Mario Bros. 3 | Super Mario Bros. 3                |
| Super Mario Bros. 4 | Super Mario World                  |

```

What a mess!

---

# Challenge:

Given a string consisting of the Japanese name of a Super Mario game, output the corresponding American name. You may input the Japanese string through any reasonable method, and output the American string (with an optional newline) through any reasonable method.

You must use the exact strings shown above. Standard loopholes are forbidden!

The shortest code (in bytes) is the winner.

# Answer
# sed, 52

* 1 byte saved thanks to @MikeScott

Straightforward replacement:

```
s/ 2/: The Lost Levels/
s/USA/Bros. 2/
s/B.*4/World/

```

Try it online.
> 15 votes

# Answer
# Retina, 43

* 1 byte saved thanks to @MikeScott

Direct port of my sed answer:

```
 2
: The Lost Levels
USA
Bros. 2
B.*4
World

```

Try it online.
> 6 votes

# Answer
# JavaScript (ES6), ~~82~~ 81 bytes

```
s=>s.replace(/ 2|o.*4|USA/,(_,i)=>['Bros. 2',': The Lost Levels','o World'][i&3])

```

Try it online!

### How?

There are three patterns to look for and replace. We search all of them at once and use the position \\$i\\$ of the match to deduce the substitution string.

```
Pattern | Found in              | Position in string | Position MOD 4 | Replaced with
--------+-----------------------+--------------------+----------------+--------------------
/ 2/    | "Super Mario Bros. 2" |                 17 |              1 | ": The Lost Levels"
/o.*4/  | "Super Mario Bros. 4" |                 10 |              2 | "o World"
/USA/   | "Super Mario USA"     |                 12 |              0 | "Bros. 2"

```
> 6 votes

# Answer
# PHP, 81 Bytes

```
<?=str_replace([" 2",USA,"Bros. 4"],[": The Lost Levels","Bros. 2",World],$argn);

```

Try it online!
> 5 votes

# Answer
# Python 2, ~~96~~ 92 bytes

```
lambda s:r(r(r(s,' 2',': The Lost Levels'),'USA','Bros. 2'),'Bros. 4','World')
r=str.replace

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 84 bytes

```
s=>s[r='replace'](' 2',': The Lost Levels')[r]('USA',(b='Bros. ')+2)[r](b+4,'World')

```

```
f=
s=>s[r='replace'](' 2',': The Lost Levels')[r]('USA',(b='Bros. ')+2)[r](b+4,'World')

console.log(
    f('Super Mario Bros.'),
    f('Super Mario Bros. 2'),
    f('Super Mario USA'),
    f('Super Mario Bros. 3'),
    f('Super Mario Bros. 4')
)
```
> 3 votes

# Answer
# Japt, 48 bytes

```
d" 2"`: T” Lo¡ Levels`"USA"`Bžs. 2``Bžs. 4``WŽld

```

Try it online!

## Explanation:

```
 d" 2"`: T” Lo¡ Levels`"USA"`Bžs. 2``Bžs. 4``WŽld

U                                //  Implicit U = Input
 d                               //  Replace:
   " 2"                          //    " 2" with
       `...`                     //    ": The Lost Levels" decompressed,
            "USA"                //    "USA" with
                 '...'           //    "Bros. 2" decompressed,
                      '...'      //    "Bros. 4" decompressed with
                           '...' //    "World" decompressed

```

Japt uses the shoco library for string compression. Backticks are used to decompress strings.
> 2 votes

# Answer
## R, 86 bytes

```
function(x)sub("Bros. 4","World",sub("USA","Bros. 2",sub(" 2",": The Lost Levels",x)))

```
> 2 votes

# Answer
# Jelly,  ~~44~~  43 bytes

```
⁹
HḂ+2⁹Ḳ¤ḣK;⁸ị“¥ḄḞ“ḋṗYP8ḷẇ?Ṅ“¡Ạ ṙṗ%»¤
0ịVĊŀ

```

A full program that prints the result.

**Try it online!**

### How?

```
⁹ - Link 1: yield right argument: number a, list of characters b
⁹ - link's right argument, b

HḂ+2⁹Ḳ¤ḣK;⁸ị“¥ḄḞ“ḋṗYP8ḷẇ?Ṅ“¡Ạ ṙṗ%»¤ - Link 0: change a name: number a, list of characters b
                   ...Note: at this point a will be 0, 2 or 4 for USA, 2 and 4 respectively
H                                   - halve a (0,1, or 2)
 Ḃ                                  - mod 2   (0,1, or 0)
  +2                                - add 2   (2,3, or 2)
      ¤                             - nilad followed by link(s) as a nilad:
    ⁹                               -   link's right argument, b
     Ḳ                              -   split at spaces
       ḣ                            - head (first two for USA or 4, first three for 2)
        K                           - join with spaces
                                  ¤ - nilad followed by link(s) as a nilad:
          ⁸                         -   link's left argument a
            “¥ḄḞ“ḋṗYP8ḷẇ?Ṅ“¡Ạ ṙṗ%»  -   list of dictionary/string compresions:
                                    -     [" World",": The Lost Levels"," Bros. 2"]
           ị                        - index into (1-based & modular; respectively [4,2,0])

0ịVĊŀ - Main link: list of characters, J
0ị    - index 0 into J - gets the last character '.', '2', 'A', '3', or '4'
  V   - evaluate as Jelly code - the evaluations are:
      -     "Super Mario Bros." :  . - literal 0.5
      -   "Super Mario Bros. 2" :  2 - literal 2
      -       "Super Mario USA" :  A - absolute value (default argument is 0) = 0
      -   "Super Mario Bros. 3" :  3 - literal 3
      -   "Super Mario Bros. 4" :  4 - literal 4
   Ċ  - ceiling - changes a 0.5 to 1 and leaves others as they were
    ŀ - call link at that index as a dyad (left = the evaluation, right = J)
      -   this is one based and modular so 1 & 3 go to Link 1, while 0, 2 & 4 go to Link 0.

```
> 1 votes

# Answer
# Mathematica, 80 bytes

```
#~StringReplace~{" 2"->": The Lost Levels","USA"->"Bros. 2","Bros. 4"->"World"}&

```

Anonymous function. Takes a string as input and returns a string as output.
> 1 votes

# Answer
# Python 3: 111 bytes

```
from re import sub as r
print(r(" USA","Bros. 2",r(" 2",": The Lost Levels",r("Bros. 4","World",input()))))

```

Gets user input, runs a series of regex-based substitutions, and prints the result.
> 1 votes

# Answer
# Go, 134 bytes

```
import."strings"
func f(s string)string{r:=Replace;return r(r(r(s," 2",": The Lost Levels",1),"USA","Bros. 2",1),"Bros. 4","World",1)}

```

Try it online!

Since Go doesn't support default values for arguments, you have to manually pass `1` every time.
> 0 votes

# Answer
# Batch, ~~237~~ 99 bytes

*Assuming input is in exact format in the question*

```
@set s=%*
@set s=%s: 2=: The Lost Levels%
@set s=%s:USA=Bros. 2%
@set s=%s:Bros. 4=World%
@echo %s%

```
> 0 votes

# Answer
# Pascal (FPC), ~~184~~ 182 bytes

```
const s='Super Mario ';b='Bros.';m=s+b;var t:string;z:array[0..4]of string=(m+' 2',m+' 3',m,s+'World',m+': The Lost Levels');begin read(t);write(z[(length(t)+ord(t[19])*2)mod 5])end.

```

Try it online!

### Explanation:

`z` is the array that holds 5 possible outputs, we just need to find the way to index into it. I noticed 2 parameters that can be used to distinguish input. The first part is length of the input:

```
Super Mario Bros.   -> 17
Super Mario Bros. 2 -> 19
Super Mario USA     -> 15
Super Mario Bros. 3 -> 19
Super Mario Bros. 4 -> 19

```

Only 3 inputs have the same length mod 5. The second part is that, at position 19 in the inputs, `2`, `3` and `4` have consecutive code points, so they can be easily used to fill out the rest of the indexes while the remaining 2 inputs are shorter.

The `String` type defaults to `ShortString` and by default has capacity for 255 characters, all initialized with zeroes, so it is safe to use `t[19]` on all strings and its codepoint is 0 for shorter strings, not changing anything for indexing, so shorter strings' indexes are 0 and 2. Therefore, we need indexes 1, 3 and 4 from `2`, `3` and `4`.

```
  | Codepoint |  *2 | +19 | mod 5
2 |        50 | 100 | 119 | 4
3 |        51 | 102 | 121 | 1
4 |        52 | 104 | 123 | 3

```
> 0 votes

# Answer
# 05AB1E, 37 bytes

```
l„ 2“:€€‹×Œä“:'„À"bros. 2"©:®Y4:'‚ï:™

```

Try it online or verify all test cases.

**Explanation:**

```
l                  # Convert the input to lowercase
 „ 2         :     # Replace " 2" with:
    “:€€‹×Œä“      #  ": the lost levels"
 '„À          :    # Then replace "usa" with:
    "bros. 2"      #  "bros. 2"
             ©     # And store the string "bros. 2" in the register
 ®                 # Retrieve "bros. 2" from the register,
  Y4:              # and replace its "2" with "4"
        :          # Then replace "bros. 4" with:
     '‚ï           #  "world"
™                  # Convert the result to title-case (and output implicitly)

```

See this for more information why `“:€€‹×Œä“` is `": the lower levels"`; `'„À` is `"usa"`; and `'‚ï` is `"world"`.
> 0 votes

---
Tags: code-golf, string, kolmogorov-complexity, game
---


title: Take a stand against long lines

text:
# Question
Title: Take a stand against long lines
Recently, someone proposed more stringent limits for Python's default line length:

> Clearly, no program should ever use more than 80 characters per line, for a whole host of reasons. First and foremost, for readability and maintainability, it is important to have a solid standard, so we can adjust the width of our text editors appropriately. As a secondary benefit, code can easily be transferred onto media that may have restrictions, and where adding line-breaks can be distracting, like print pages for review in a meeting, or punch cards.
>
> But is 80 characters too high? Some suggest 79, or even as low as 75, to allow for an 80 character wide terminal to fit the code with a few columns devoted to line numbers. Clearly, ultimately, lower is better, as lower limits allow for the code to be used in more situations without reformatting.
>
> **Introducing the max6 standard**

Your goal is to find and demonstrate the minimum line length required by Your Favorite Language by writing a FizzBuzz variant with the fewest number of characters in any line.

# Input

An integer, *n*, via any desired method.

# Output

Print the numbers from 1 to *n*, (*n* ≥ 1, *n* ∈ ℤ) separated by line breaks, except:

* for multiples of 3 print "Apple"
* for multiples of 5 print "Pie"
* for multiples of both 3 and 5 print "ApplePie"

# Scoring

The maximum line length in bytes, not including the line break (Cr, CrLf, Lf, or other system standard break, specify, as desired), and the total code length in bytes as a tiebreaker.

# Rules

All line breaks must be meaningful. Line breaks that can be removed and adjacent lines directly concatenated without an impact on the output, *must* be removed.

# Answer
## \>\<\>, 1 byte per line, ~~243~~ ~~161~~ 135 bytes

*-26 bytes thanks to Jo King!*

2D languages FTW! Although writing loops and branches using goto instructions instead of the 2D structure is not fun.

```
v
l
:
:
3
%
:
&
0
4
7
*
&
?
.
~
~
"
e
l
p
p
A
"
o
o
o
o
o
$
5
%
:
&
0
a
5
*
&
?
.
~
~
"
e
i
P
"
o
o
o
*
0
@
?
n
?
~
l
{
:
}
=
?
;
a
o
1

```

Try it online!, or watch it at the fish playground!

The fish swims downward along the code, using conditional gotos to skip things depending on what divides the accumulator.

I believe this meets the spec: whatever newlines are removed, the fish always hits the initial `v` (the only direction-changing instruction present), so the fish always swims downwards in the first column. Thus deleting a newline has the effect of simply removing the next character from the fish's path, and I don't think you can remove any of the characters without changing the output.
> 18 votes

# Answer
# Haskell, 3 bytes/line, ~~494 471 470 463 453 450~~ 461 bytes

EDIT:

* -26 bytes: Removed some redundant linebreaks and their associated comment markers, and changed `-1+x` into `x-1`.
* +3 bytes: Oops, needed extra `--` line after `x-`.
* -1 byte: In `f` use `c 47:[]` instead of `[c 47&0]`.
* -7 bytes: Move newline handling to `w`.
* -10 bytes: Inline `a="Apple"` and `p="Pie"` in `#` and use a dummy recursion for the 15 case.
* -3 bytes: Inline `w` in `f`. Remove redundant `--` between `x` and `15`.
* +11 bytes: Oops again! My string gap theory had a hole. Fixed by introducing `%` function. Finally made some automated testing to make sure there were no more surprises.

`f` takes an `Int` and returns a `String`.

```
{;f
n=
--
[--
1..
--
n--
]--
>>=
\
--
x->
--
gcd
x
15#
--
x++
--
c
47:
--
[--
]--
;1#
--
x=
--
n!!
--
(x-
--
1--
)--
;3#
--
_=
--
"A\
\p\
\p\
\l\
\e\
\"&
--
0--
;5#
--
_=
--
"P\
\i\
\e\
\"&
--
0--
;--
15#
--
_=
--
3#
--
0++
--
5#
--
0--
;n=
--
d++
--
[--
s++
--
t|
--
s<-
--
n--
,--
t<-
--
[c
9]:
--
d--
]--
;d=
--
(:
--
[--
]--
)--
<$>
--
[c
8..
--
c
0--
]--
;c
x=
--
[--
"9\
\"%
--
0--
,--
"8\
\"%
--
0..
--
]!!
--
x--
;--
[--
a]%
--
_=
--
a--
;x&
--
y=
--
x}

```

Try it online!

Test source restrictions! (Line 70 is excluded from the testing because removing its newline causes an infinite loop without output.)

Version with the most important squeezing tricks removed:

```
{;f n=[1..n]>>= \x->gcd x 15#x++c 47:[]
;1#x=n!!(x-1)
;3#_="Apple"
;5#_="Pie"
;15#_=3#0++5#0
;n=d++[s++t|s<-n,t<-[c 9]:d]
;d=(:[])<$>[c 8..c 0]
;c x=["9"%0,"8"%0..]!!x
;[a]%_=a
;x&y=x}

```

# How it works

* This code is written in the more rarely used indentation insensitive mode of Haskell, triggered e.g. by surrounding an entire program with `{}`. Since I'm actually defining a function rather than a whole program, I'm not quite sure how to count bytes; I've chosen to defensively count *both* the `{}`s and an extra `;` declaration separator (the latter usually being a newline in normal Haskell mode.)
* The main trick for making newlines "meaningful" is `--` line comments, which make the next newline non-removable, and also a *previous* newline in the case when the previous line ends in an operator character (which is not itself part of a line comment).
* The second trick is "string gaps", a sequence of whitespace between `\` backslashes in string literals, indented for line continuations with possible indentation. A string gap with delimiters is removed from the parsed string.
    + If the newline of a string gap is removed, it becomes an added backslash in the string. For `"Apple"` and `"Pie"` this shows up directly in the output. For `"8"` and `"9"` a pattern match is used to give an error if the string has more than one character.
* The third trick is the `&` and `%` operators, which allow forcing a line to end in an operator character for the first trick. We need this to end string literals, because `\"` is too wide to append `--`.
    + `&` is the general one, defined such that `x&y=x`.
    + `%` is defined such that `[a]%y=a`, allowing it to replace `!!0` and simultaneously enforce that its string argument must have length 1.
* The newline character poses a special problem, as `\n` seems impossible to fit in a string literal with only 3 bytes on the line.
    + Therefore, the more easily defined `c x=["9"%0,"8"%0..]!!x` is used to convert from an `Int` to a character, counting from the digit `'9'` downwards.
* Because `show` is four characters, number output must be implemented by hand.
    + `d` is a list of the digit strings `"1".."9"`.
    + `n` is an infinite list of number representations `["1","2","3",...]` defined recursively using `d`.
* `#` converts an `Int` `x` to its ApplePie form given an extra first argument that is the `gcd` of `x` with 15.
> 18 votes

# Answer
# Jelly, ~~3~~ 2 bytes/line, ~~106~~ ~~80~~ 56 bytes

```
“3
,e
5P
ḍ,
T⁾
ịi
⁾e
AF
ps
,5
⁾¤
pȯ
lµ
,€
⁾Y
”Ỵ
¢Z
¢F
¢v

```

Rows and columns of the string literal get transposed, so removing newlines messes up their order.

The remaining lines are separate links/functions and contain function calls (`¢`), so they can only be concatenated if the function calls are eliminated as well.

Try it online!
> 6 votes

# Answer
# Haskell, 7 bytes/line, 339 bytes

The requirement for line breaks to be meaningful makes this a nontrivial challenge in Haskell. There are almost no ways to insert line breaks that cannot be removed, so everything has to be done with legitimately tiny statements.

```
c=cycle
h=head
i=tail
k=[1..]
s=do
 let
  _=0
  _=0
 putStr
t=take
p=print
u=fst
v=snd
z=zip
n=s"\n"
o 5=do
 s"Pie"
 n
o _=n
5%x=o 5
_%x=p x
3!x=do
 s"App"
 s"le"
 o$u x
_!x=do
 let
  y=u x
  z=v x
 y%z
q x=do
 let
  y=u x
  z=v x
 y!z
g[]=s""
g x=do
 q$h x
 g$i x
a=t 3 k
b=t 5 k
l=z$c a
m=z$c b
f n=do
 let
  x=t n
  y=x k
  z=m y
 g$l z

```

Try it online!
> 6 votes

# Answer
# TI-BASIC, 4 bytes per line

Since the goal is only to minimize the maximum line length, some of the lines are longer than they need to be, but the smallest I could make the longest line was 4 bytes. Therefore I felt it'd make the code easier to read if I merged the lines that could be combined without exceeding 4 bytes.

```
"APP
Ans→Str1
"LE
Str1+Ans
Ans→Str1
"PIE
Ans→Str2
Input N
1→I
While I≤N
fPart(I/3
not(Ans→A
fPart(I/5
not(Ans→B
If A and B
Then
Str1
Ans+Str2
Disp Ans
Else
If A
Then
Disp Str1
Else
If B
Then
Disp Str2
Else
Disp I
End
End
End
I+1
Ans→I
End

```

## Ungolfed

```
"APPLE"→Str1
"PIE"→Str2
Input "N:",N
For(I,1,N)
remainder(I,3)=0→A
remainder(I,5)=0→B
If A and B:Then
Disp Str1+Str2
Else
If A:Then
Disp Str1
Else
If B:Then
Disp Str2
Else
Disp I
End
End
End
End

```

## About the Language and Limitations

TI-BASIC is a tokenized language, and, in this case, each of the tokens are 1 byte with the exception of the `StrN` variables, which are 2 bytes. Also, you can leave off closing parentheses most of the time. The `remainder(` function is 2 bytes, so using it would require at least 5 bytes (one for the function, two for the arguments, and one for the comma in `remainder(I,3`). Instead, I used the `fPart(` and `not(` functions to make it shorter, which are both 1 byte tokens. Also, you can see I used the built-in variable `Ans` quite a lot, since any expression that gets evaluated on a line by itself gets automatically stored to it. So, I can save a few bytes by splitting up the expressions and assignments.

Another strategy was to obviously minimize the string assignments. My method for doing so depended on the maximum line length in the rest of the code. Once I determined it to be 4 bytes, I was able to cram as much of each string on the same line as possible to minimize the amount of assignments I needed. I did this for the sake of readability.

The limiting factors in this code are the assignments to string variables and concatenation with string variables. The lines `Ans→Str1` and `Str1+Ans` both are 4 bytes in total. I would have to find a way to eliminate string variables completely in order to further minimize the maximum line length in my code. Everything else can be shortened to a maximum of 3 bytes or less per line.

The problem there lies in assignments to numeric variables, such as `1→I`. You can't golf that any further without somehow coming up with a solution without variables that doesn't exceed 2 bytes in line length. That happens to be impossible for this challenge.

Binary operators like `+` require the operator symbol and the left and right arguments. So without this, you would not be able to concatenate strings. Without string concatenation, there would be no way to display the strings required for this program to complete the challenge without exceeding 2 bytes in line length. Therefore the theoretical limit for this challenge in this language would be 3 bytes per line, which I was not able to attain.
> 6 votes

# Answer
# Aceto, 1 byte per line, 230 bytes

Well, that wasn't fun to write. As a fungoid, Aceto's control structures heavily rely on its 2D nature, but we can work around that with lots, lots of conditional escapes (```). The only problem with those is that they affect the next command, regardless of its presence (all Aceto programs are squares, internally), which is why we need to align the program at some places by inserting empty lines at some points.

String literals can't really be used, but char literals can (in some places; again, we need to align them).

```
&
p
$
L
Q
`
L
p
`
L
d
`
L
Q
`
L
Q
`
L
x
`

L
M
!
%
5
d
$
L
Q
`
L
Q
`
L
p
`
L
d
`
L
Q
`
L
x
`
L
M
!
%
3
d
$
L
p
`
L
d
`
L
x
`

L
M
!
%
*
5
3
d
[
X
`

n
=
0
l
)
@
(
z
i
r
{
J
s
]
d
s
}
d
[
~
£
A
'
d
p
'

l
'

e
'

{
~
£
P
'

i
'
e
'

```

Called with `20`, this prints:

```
1
2
Apple
4
Pie
Apple
7
8
Apple
Pie
11
Apple
13
14
ApplePie
16
17
Apple
19
Pie

```

> All line breaks must be meaningful. Line breaks that can be removed and adjacent lines concatenated without an impact on the output, must be removed.

This is never the case here because it runs from the bottom to the top.

There's at least one place where we can save 2 bytes (by replacing the  ``X` with a `|` or `#`), but I kept it as it is because of the runtime cost associated with running through a relatively big Hilbert curve.

I also ignored the implicit requirement for using `\r` or `\r\n` newlines because I think it's an unintentional mistake by the OP. If there's an edit or a comment reinforcing this requirement, I can change it without much trouble to use CR newlines instead.

The bytecount is based on Aceto's codegolfing encoding; Latin-7, in which `£` is a single byte.
> 6 votes

# Answer
# C (gcc), 2 bytes per line, ~~374~~ ~~368~~ ~~320~~ ~~310~~ 262 bytes

I assume it can be golfed a bit more. Backslashes escaping newlines makes it sort of trivial.

```
i\
;\
f\
(\
n\
)\
{\
f\
o\
r\
(\
i\
=\
0\
;\
i\
+\
+\
<\
n\
;\
p\
r\
i\
n\
t\
f\
(\
i\
%\
3\
&\
&\
i\
%\
5\
?\
"\
%\
d\
\\
n\
"\
:\
i\
%\
3\
?\
"\
P\
i\
e\
\\
n\
"\
:\
i\
%\
5\
?\
"\
A\
p\
p\
l\
e\
\\
n\
"\
:\
"\
A\
p\
p\
l\
e\
P\
i\
e\
\\
n\
"\
,\
i\
)\
)\
;\
}

```

Try it online!
> 6 votes

# Answer
# Python 3, 4 bytes/line, 113 bytes

```
e=\
exec
def\
f(n\
):i\
=0;\
e('\
pri\
nt(\
i%3\
//2\
*"A\
ppl\
e"+\
i%5\
//4\
*"P\
ie"\
or-\
~i)\
;i+\
=1;\
'*n)

```

Try it online!
> 5 votes

# Answer
# PHP 7, 2 bytes per line

```
(#
c#
.#
r#
.#
e#
.#
a#
.#
t#
.#
e#
.#
_#
.#
f#
.#
u#
.#
n#
.#
c#
.#
t#
.#
i#
.#
o#
.#
n#
)#
(#
'#
'#
,#
g#
.#
l#
.#
o#
.#
b#
.#
a#
.#
l#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
a#
.#
r#
.#
g#
.#
n#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
3#
)#
.#
w#
.#
h#
.#
i#
.#
l#
.#
e#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
i#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
7#
+#
1#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
7#
+#
1#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
4#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
a#
.#
r#
.#
g#
.#
n#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
+#
1#
)#
.#
e#
.#
c#
.#
h#
.#
o#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
i#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
+#
1#
)#
.#
3#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
9#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
i#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
+#
1#
)#
.#
5#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
9#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
i#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
2#
)#
.#
P#
.#
i#
.#
e#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
+#
1#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
2#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
)#
.#
i#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
6#
+#
1#
)#
.#
5#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
9#
)#
.#
A#
.#
p#
.#
p#
.#
l#
.#
e#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
2#
)#
.#
A#
.#
p#
.#
p#
.#
l#
.#
e#
.#
P#
.#
i#
.#
e#
.#
(#
c#
.#
h#
.#
r#
)#
(#
5#
*#
8#
+#
1#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
6#
*#
7#
+#
2#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
4#
*#
8#
+#
2#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
2#
*#
5#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
4#
*#
8#
+#
2#
)#
.#
(#
c#
.#
h#
.#
r#
)#
(#
7#
*#
8#
+#
3#
)#
)#
(#
)#
;#

```
> 5 votes

# Answer
## Perl 5, 2 bytes per line, 182 bytes

```
&
#
{'
Er
0h
|R
hR
o
'#
^#
'I
 O
Ro
3f
+~
'#
.#
(#
p#
|#
Y#
)#
}#
(#
'z
;d
y"
"z
7#
vU
aW
zZ
7#
vU
gW
..
~.
4e
r;
|6
'#
^#
('
xR
~R
KR
fR
QR
/R
$R
cR
QR
/R
vR
UR
%R
xR
$R
'#
.#
4#
))

```

Try it online!

Perl's syntax is very forgiving, so a lot of gaps can be added to the code and comments added, which makes the core idea fairly straightforward. The main aim with this code is to build a string containing the code we want to run, and `eval` it. In Perl, it's possible to call a function using a string or variable with the `&{...}` notation, unfortunately however, `eval` isn't callable in this form, but `evalbytes` is, as long as you call it via the `CORE::` namespace. Building that string was fairly straightforward and the program is passed directly to this call. The strings are built utilising the newlines as part of the XOR, to build these I used this script. To keep this valid, a few places have had to have comments placed, so that removing the newlines would result in non-functioning code.

The FizzBuzz routine was taken from primo's excellent answer.

---

## Perl 5, 1 byte per line, 172 bytes

So, I (now) know *this is invalid*, because a bunch of the newlines can be removed, but since this was my original approach to the problem I'm adding it. It was fun see how far you can push Perl's syntax! I enjoyed this problem on its own merit, even though it's invalid.

```
&
{
(
I
.
'
X
0
o
k
h
~
'
.
(
p
|
Y
)
)
^
'
E
O
0
|
f
s
o
'
}
(
'
x
d
!
K
z
o
Q
U
9
$
Z
o
Q
U
?
v
.
&
%
e
*
$
6
'
^
'

c
~
"
z
f
#
.
/
W
"
c
#
.
/
W
v
U
.
l
x
;
$
4
'
^
p
)

```

Try it online!
> 5 votes

# Answer
# SmileBASIC, ~~9~~ 7 bytes per line, ~~159~~ ~~155~~ ~~154~~ 152 bytes

This was a really fun challenge. Unfortunately, the rule against unnecessary line breaks causes a few problems, (though luckily it doesn't affect the maximum line length here.) I had to add comments between lines like `A%=I/3` and `A=A%*3`, since `A%=I/3A=A%*3` is parsed correctly in SB. I was able to use a trick to leave out some comments, since replacing `A` with `E` makes that line invalid (It has something to do with numbers written using `E` notation, I think. `3E` is considered an invalid number rather than a number and a variable name.)

```
A$="App
B$="le
P$="Pie
INPUT N
R=N
WHILE R
INC I
R=I<N
A%=I/3'
A=A%*3'
A=A==I
B%=I/5
E=B%*5
E=E==I'
?A$*A;
?B$*E;
?P$*E;
C=A+E
WHILE!C
C=1?I;
WEND?
WEND

```

The biggest limitation here is getting input. `INPUT x` is the simplest way allowed, the alternative being to define a function with an input value like `DEF F x` but that is still 7 characters. Making a conditional statement is also hard; I can't think of anything shorter than `WHILE x`.
> 5 votes

# Answer
# JavaScript (ES6), 3 bytes per line

Uses the global variable `top` to access the `window` object, from which we `eval` the following code:

```
n=prompt('')
i=0
for(;++i<=n;console.log(i%5?f||i:f+'Pie'))f=i%3?'':'Apple'

```

You'll have to run it in the console as `top` is inaccessible from a sandboxed Stack Snippet.

---

```
t//
=//
top
t//
[`\
ev\
al\
`//
]//
(`\
n=\
pr\
om\
pt\
('\
')
i=0
fo\
r(\
;+\
+i\
<=\
n;\
co\
ns\
ol\
e.\
lo\
g(\
i%\
5?\
f|\
|i\
:f\
+'\
Pi\
e'\
))\
f=\
i%\
3?\
''\
:'\
Ap\
pl\
e'\
`)

```
> 3 votes

# Answer
## C#, 9 bytes per line, ~~248 242~~ 230 bytes

Since C# doesn't care about linebreaks, it needs a oneline comment at the end of almost (thanks Ørjan Johansen) every line to comply with the rules. This program expects *n* as a command line argument. Here's with as many non-deletable newlines as possible:

```
class
A//
{//
static
void
Main//
(//
string//
[//
]//
a//
)//
{//
for//
(//
var
i//
=//
0//
;//
i++//
<//
int//
.Parse//
(//
a//
[//
0//
]//
)//
;//
)//
{//
var
s//
=//
""//
;//
if//
(//
i//
%//
3//
==//
0//
)//
s//
+=//
"A"+//
"p"+//
"p"+//
"l"+//
"e"//
;//
if//
(//
i//
%//
5//
==//
0//
)//
s//
+=//
"P"+//
"i"+//
"e"//
;//
if//
(//
s//
==//
""//
)//
s//
=//
$"{i}"//
;//
System//
.//
Console//
.//
Write//
(//
s//
+//
@"
"//
)//
;//
}//
}//
}

```

But since the longest line is 9 bytes, other lines can get that long too, shaving off some bytes:

```
class
A{static
void
Main(//
string[//
]a){//
for(var
i=0;i++//
<int.//
Parse(a//
[0]);){//
var
s="";if//
(i%3==0//
)s+=//
"Apple"//
;if(i%5//
==0)s+=//
"Pie";//
if(s==//
"")s=//
$"{i}";//
System.//
Console//
.Write(//
s+@"
");}}}

```
> 3 votes

# Answer
# JavaScript, max of 6 bytes/line, 528 bytes

Idea ripped from here.

Code ripped from here.

Thanks to Anders Kaseorg for `g=eval`, saving a byte per line.

```
a="n"
a+="="
a+="p"
a+="r"
a+="o"
a+="m"
a+="p"
a+="t"
a+="("
a+="'"
a+="'"
a+=")"
a+=";"
a+="f"
a+="o"
a+="r"
a+="("
a+="i"
a+="="
a+="0"
a+=";"
a+="+"
a+="+"
a+="i"
a+="<"
a+="="
a+="n"
a+=";"
a+="c"
a+="o"
a+="n"
a+="s"
a+="o"
a+="l"
a+="e"
a+="."
a+="l"
a+="o"
a+="g"
a+="("
a+="i"
a+="%"
a+="5"
a+="?"
a+="f"
a+="|"
a+="|"
a+="i"
a+=":"
a+="f"
a+="+"
a+="'"
a+="P"
a+="i"
a+="e"
a+="'"
a+=")"
a+=")"
a+="f"
a+="="
a+="i"
a+="%"
a+="3"
a+="?"
a+="'"
a+="'"
a+=":"
a+="'"
a+="A"
a+="p"
a+="p"
a+="l"
a+="e"
a+="'"
g=eval
g(a)

```

Unseperated:

```
n=prompt('');for(i=0;++i<=n;console.log(i%5?f||i:f+'Pie'))f=i%3?'':'Apple'

```
> 2 votes

# Answer
# Ruby, ~~10~~ 5 bytes/line, ~~354~~ 214 bytes

-140 bytes from the raw score from @NieDzejkob.

```
eval\
"pu"\
"ts"\
" ("\
"1."\
".g"\
"et"\
"s."\
"to"\
"_i"\
")."\
"ma"\
"p{"\
"|i"\
"|i"\
"%1"\
"5<"\
"1?"\
":A"\
"pp"\
"le"\
"Pi"\
"e:"\
"i%"\
"5<"\
"1?"\
":P"\
"ie"\
":i"\
"%3"\
"<1"\
"?:"\
"Ap"\
"pl"\
"e:"\
"i}"

```

### How it works

Ruby will automatically concatenate sequences of string literals (except for single-character literals such as `?a`) in the same statement. That means that `x = "a" 'b' "c" %q{d}` is equivalent to `x = "abcd"`. We use this to split the FizzBuzz-like code into much smaller strings for calling `eval` with, since `+` will invalidate the program due to the removing-newlines rule, but the `\` will cause syntax errors if the newlines are taken out!
> 2 votes

# Answer
# Python 2, 5 bytes/line, 93 bytes

The max6 standard is already obsolete.

```
def\
f(n):
 i=0
 \
exec\
'pri\
nt i\
%3/2\
*"Ap\
ple"\
+i%5\
/4*"\
Pie"\
or-~\
i;i+\
=1;'\
*n

```

Try it online!

# Python 2 and 3, 5 bytes/line, 100 bytes

```
def\
f(n):
 i=0
 \
exec\
('pr\
int(\
i%3/\
/2*"\
Appl\
e"+i\
%5//\
4*"P\
ie"o\
r-~i\
);i+\
=1;'\
*n)

```

Try it online!
> 2 votes

# Answer
# PHP, 4 Bytes/line

```
for#
(#
$z=#
${#
ar.#
gn#
};#
$k#
++<#
$z#
;){#
(#
pr.#
in.#
t_.#
r)#
([#
A.#
p.p#
.le#
][#
$k#
%3#
].[#
Pie#
][#
$k#
%5#
]?:#
$k)#
;(#
pr.#
in.#
t_.#
r)#
("
");}

```

Try it online!
> 2 votes

# Answer
# Retina, 4 bytes/line

```
.+
$*      Convert the input number to unary.
1
$`1¶    Count from 1 to the input number.
111
A       Divide by 3.
+`A1
1111    If there was a remainder, restore the original number.
A{5}
AP      If the number is divisible by 3, try to divide by 5.
.*A     The result ends in `AP` if the number is divisible by 15,
Appl    or in `A` if it is only divisible by 3. Replace everything
l       up to the `A` with `Apple`; multiples of 15 become `AppleP`.
le
1{5}    If the number did not divide by 3, try dividing it by 5 anyway.
P
+`P1    If there was a remainder, restore the original number.
6$*1    Otherwise replace the result with `Pie`,
P+      which also fixes multiples of 15.
Pie     If the number was divisible by neither 3 nor 5,
1+      convert it back to decimal.
$.&

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog), 5 bytes per line

```
∇f
A←'A'
p←'p'
p,←p
e←'e'
A,←p
l←'l'
A,←l
A,←e
P←'P'
i←'i'
P,←i
P,←e
{O←''
M←3|⍵
M←0=M
O←M/A
M←5|⍵
M←0=M
M←M/P
O,←M
M←⍴O
M←0=M
M←M/⍵
O,←M
⎕←O⍝
}¨⍳⎕
∇

```

Try it online!
> 2 votes

# Answer
# , 10 bytes per line, 800 bytes

The "meaningful linebreaks" rule made this challenging. Currently this just spells out fizzbuzz code into a string and then executes it.

```
a="x"
a[2]="="
a[3]="y"
a[4]="="
a[5]="1"
a[6]=":"
a[7]="s"
a[8]="c"
a[9]="a"
a[10]="n"
a[11]="("
a[12]=")"
a[13]=";"
a[14]="y"
a[15]="["
a[16]="3"
a[17]="*"
a[18]="x"
a[19]="]"
a[20]="="
a[21]="'"
a[22]="A"
a[23]="p"
a[24]="p"
a[25]="l"
a[26]="e"
a[27]="'"
a[28]=";"
a[29]="y"
a[30]="["
a[31]="5"
a[32]="*"
a[33]="x"
a[34]="]"
a[35]="="
a[36]="'"
a[37]="P"
a[38]="i"
a[39]="e"
a[40]="'"
a[41]=";"
a[42]="y"
a[43]="["
a[44]="1"
a[45]="5"
a[46]="*"
a[47]="x"
a[48]="]"
a[49]="="
a[50]="'"
a[51]="A"
a[52]="p"
a[53]="p"
a[54]="l"
a[55]="e"
a[56]="P"
a[57]="i"
a[58]="e"
a[59]="'"
a[60]=";"
a[61]="w"
a[62]="r"
a[63]="i"
a[64]="t"
a[65]="e"
a[66]="("
a[67]="y"
a[68]="["
a[69]="x"
a[70]="]"
a[71]=","
a[72]="'"
a[73]="'"
a[74]=")"
t=toString
g=gsub
o=", "
l=""
f=t(a)
r=g(o,l,f)
P=parse
p=P(t=r)
eval(p)

```

Try it online!

Here is the concatenated ApplePie code (adapted from MickyT's golf here).

```
x=y=1:scan()
y[3*x]='Apple'
y[5*x]='Pie'
y[15*x]='ApplePie'
write(y[x],'')

```

And the ungolfed version of the parsing code:

```
eval(t=parse(gsub(", ", "", toString(a))))

```

Here I use `toString` to concatenate the list of symbols `a` into a single string. However, the default behavior is to separate each symbol with `,`, so we call `gsub` to replace them with nulls. Then we pass it to `parse` and `eval` to do the dirty work.

It's possible that there's an approach that doesn't use this string parsing method and just straight up implements fizzbuzz, but it seems to me that using `for` or `while` or defining a `function` needs longer lines than the current approach.
> 2 votes

# Answer
# Julia 0.6, 5 bytes per line, 168 bytes total

```
f=#
n->#
((i,#
a=#
"A"*#
"p"*#
"p"*#
"l"*#
"e",#
p=#
"P"*#
"i"*#
"e"#
)->#
["$i
","$a
","$p
",a*#
p*"
"][#
1+(i#
%3<1#
)+2(#
i%5<#
1)]#
|>[#
print
sin#
][1]#
).(#
1:n)

```

Try it online!

The `print` brings this unavoidably (afaict) into the 5 bytes per line territory.

Ungolfed:

```
function f_ungolfed(n)
  inner = (i,
           a="Apple",
           p="Pie") -> ["$i\n",
                        "$a\n",
                        "$p\n",
                        a*p*"\n"][
                                    1 + (i%3 < 1) + 2(i%5 < 1)
                                   ] |> [print; sin][1]
  inner.(1:n)
end

```

`*` is the string concatenation operator, so `a*p*"\n"` forms "ApplePie\n". `|>` is the function chaining (/piping) operator, so the chosen string gets sent as the argument to `print`. The `sin` is not used, it's just there because `print` needs to be in an array to have significant whitespace after it (using the `#` trick after it will bring the per line max byte count to 6).

---

If simply returning the output as an array is allowed, it can be done with 4 bytes max per line:

## Julia 0.6, 4 bytes per line, 152 bytes total

```
f=#
n->#
((i#
,a=#
"A"#
*#
"p"#
*#
"p"#
*#
"l"#
*#
"e"#
,p=#
"P"#
*#
"i"#
*#
"e"#
)->#
[i,#
a,p#
,a*#
p][#
1+(#
i%3#
<1#
)+#
2(i#
%5<#
1)]#
).(#
1:n#
)

```

Try it online!

A function that takes n and returns an array containing the expected output. Max line length here is constrained by `n->` \- Julia needs that in a single line to parse it properly as the start of a lambda.
> 1 votes

# Answer
# Pascal (FPC) `-Sew`, 6 bytes per line, ~~348~~ 320 bytes

```
var
n,i://
word//
;begin
read//
(n);//
for
i:=1to
n do
if 0=i
mod
15then
write{
$}(//
'A',//
'p',//
'p',//
'l',//
'e',//
'P',//
'i',//
'e',//
#10)//
else
if 0=i
mod
3then
write{
$}(//
'A',//
'p',//
'p',//
'l',//
'e',//
#10)//
else
if 0=i
mod
5then
write{
$}(//
'P',//
'i',//
'e',//
#10)//
else
write{
$}(i//
,#10//
)end.

```

Try it online!

Utilises FPC to get 6 bytes per line; without it, the result would be much worse. This is the smallest possible line width since after `write` must be either `;` or `(` (or unnecessary whitespace), so a special comment is inserted to avoid this. The features from FPC which influenced this answer are:

1. `//` \- starting one-line comments.
2. Block comments in form `{$<something>...}` are compiler directives. If the directive does not exist, FPC will issue a warning (and on `{$ ...}` as well). In this program, `{` and `$` are separated with a newline which will issue the warning when deleted.
3. `-Sew` \- Compiler also halts after warnings so that `{` and `$` joined stop the compilation.
> 1 votes

# Answer
# Japt, 3 bytes per line

Nearly managed to get it down to two bytes per line, but the return from map breaks if it's followed by a newline.
The FizzBuzz implementation itself is from the canonical FizzBuzz thread.

```

`A
p
p
l
e
`y
Vx
`P
i
e
`y
Xx
ò1\
 Ë\
;W\
pD\
v3\
)+\
Yp\
Dv\
5)\
ªD\
Ã·

```

Try it online!
> 1 votes

# Answer
# LOLCODE, ~~18~~ 8 bytes per line, 303 bytes total

```
HAI 1.2
I HAS A…
B ITZ 0
IM IN…
YR L
B R SUM…
OF B AN…
1
MOD OF…
B AN 15
WTF?
OMG 0
VISIBLE…
"Apple"…
"Pie"
OMGWTF
MOD OF…
B AN 5
WTF?
OMG 0
VISIBLE…
"Pie"
OMGWTF
MOD OF…
B AN 3
WTF?
OMG 0
VISIBLE…
"Apple"
OMGWTF
VISIBLE…
B
OIC
OIC
OIC
BOTH…
SAEM B…
AN 100
O RLY?
YA RLY
GTFO
OIC
IM…
OUTTA…
YR L
KTHXBYE

```

Try it online!

*-10 bytes per line using the line-continuation character , thanks to Ørjan Johansen!*
> 1 votes

# Answer
# Python 2, 5 bytes/line

```
exec\
'f\
o\
r\
 \
x\
 \
i\
n\
 \
x\
r\
a\
n\
g\
e\
(\
1\
,\
i\
n\
p\
u\
t\
(\
)\
+\
1\
)\
:\
\n\
 \
i\
f\
 \
x\
%\
1\
5\
=\
=\
0\
:\
s\
="\
A\
p\
p\
l\
e\
P\
i\
e"\
\n\
 \
e\
l\
i\
f\
 \
x\
%\
5\
=\
=\
0\
:\
s\
="\
P\
i\
e"\
\n\
 \
e\
l\
i\
f\
 \
x\
%\
3\
=\
=\
0\
:\
s\
="\
A\
p\
p\
l\
e"\
\n\
 \
e\
l\
s\
e\
:\
s\
=\
x\
\n\
 \
p\
r\
i\
n\
t\
(\
s\
)'

```

Try it online!
> 0 votes

# Answer
# JavaScript (ECMAScript6), 2 bytes per line

```
'\
'[
'\
b\
i\
g'
][
'\
c\
o\
n\
s\
t\
r\
u\
c\
t\
o\
r'
][
'\
c\
a\
l\
l'
](
0,
`\
n\
=\
p\
r\
o\
m\
p\
t\
(\
'\
'\
)\
;\
i\
=\
0\
;\
f\
o\
r\
(\
;\
+\
+\
i\
<\
=\
n\
;\
c\
o\
n\
s\
o\
l\
e\
.\
l\
o\
g\
(\
i\
%\
5\
?\
f\
|\
|\
i\
:\
f\
+\
'\
P\
i\
e\
'\
)\
)\
f\
=\
i\
%\
3\
?\
'\
'\
:\
'\
A\
p\
p\
l\
e\
'\
`)
()
```

---

## TLDR - Short*er* explanation

I'm accessing the new Function(code) constructor to parse the string instead of eval(code). This constructor is available at every native function by doing anyFunction.constructor, like `alert.constructor===Function`. I'm using a function/method inside the String.prototype.big `String.prototype.big.constructor.call(null, /*string*/)` But accessing it directly from a string literal `"".big` and turned it to bracket notation. `""['big']['constructor']['call'](0, CODE)` to be able to break it using the `\`.

## Long explanation

The way we can make lines shorter is transforming code into a string and escaping the line ends, this will impose a limit of 2bytes per line.

So `alert(1)` becomes

```
"\
a\
l\
e\
r\
(\
1\
)"

```

But now your code is a string so we need to execute the string as code. I know at least 4 ways you can execute string as code:

1. eval(code). Which takes at least 5 bytes to call `eval(`
2. setTimeout(code, timeout). Runs function asyncronously, but optionally if you pass a string it will invoke eval internally.
3. You can take advantage of the DOM and put your code inside a `onclick=""` attribute, but I could not manage to make the element creation part short.
4. Invoking the Function constructor new Function() will parse your code into a anonymous function which you can call later (I used this).

All the native functions lives inside the window object and in javascript you can access object properties using the dot notation so `eval()` becomes `window.eval()`, or you can access properties using the bracket notation `window['eval']()`. You can take advantage of this to break the `eval` in multiple lines using the method described before. But you still have to type the window, one trick is that if you're not inside a frame, the top variable is also window, so window.eval becomes top.eval (3 bytes less).

```
w=top
w['eval']

You can shorten the assignment using parenthesis
w=(
top
)
w[
'e\
av\
al'
](
/*string*/
)

```

So this will make the code minimum of 3 bytes. To make the code 2 bytes I used the `new Function(/*string*/);` constructor, but I had to be creative to access it without having to type it.

First, the Function constructor allows you to call it as a function omitting the new keyword, this reduce 4 bytes but it is also important for another reason. Calling the constructor as a function still returns a instance this allows us to turn `new Function(code)` to `Function(code)`. Another importante thing is that the Function constructor have a `call` method that allows you to call any function but overriding the this reference, and the Function constructor itself being a function you can call a method on it self like `Function.call(null, code)`.

All native functions are instances of the Function constructor, and all objects in javascript have a constructor property. So you can have access Function constructor on any native function like `alert.constructor`, and using the call method we can execute the constructor as a function. Now we have alert.constructor.call(null, code) returns a function.

combining the previous thechiniques we can turn it into `alert['constructor']['call'](null, code)`

Now we just need to find a short named function or method, so I choose the big() method inside the String constructor. So I can access it directly from a empty string `"".big`

```
"".big.constructor.call(null, "code")();
''['big']['constructor']['call'](0,'/* code */')()

```

Then I just broke every thing in 2 bytes
> 0 votes

# Answer
# Pip, 3 bytes per line, 72 bytes total

```
V@Y
YUW
Y"L
a
P
S
T
[
`
A
p
p
l
e
`
`
P
i
e
`
]
X
!
*
+
+
i
%
^
3
5
|
i"

```

Try it online!

Pip is exceedingly flexible about whitespace, so the only strategy that seems feasible is to create a string, modify it in a way that requires the newlines not to be disturbed, and eval it.

We create a string where every other character is a newline, and take every other character of it using `UW` (unweave) and unary `@` (get first element):

```
UW"abcdef"  => ["ace" "bdf"]
@UW"abcdef" => "ace"

```

The result of `@UW` should be our ApplePie code, adapted from the FizzBuzz solution here. If any newlines in the string are deleted, this will not result in the full code, giving either a syntax error or incorrect output.

There are still two newlines outside the string. We made these mandatory by using the `Y` (yank) operator--which here acts as a no-op--together with the way Pip parses runs of uppercase letters:

```
YUW   => Y UW
YUW Y => Y UW Y
YUWY  => YU WY

```

So if these newlines are deleted, the program parses differently and doesn't do what it's supposed to.
> 0 votes

# Answer
# Java 8, 7 bytes per line, 171 bytes

A void lambda taking an `int`. I suspect this obeys the requirement regarding newlines, but I can't prove it, and verifying it by brute force would take about a month on my computer. So it goes.

```
a->{//
System
s=//
null;//
for(int
i=0;i//
<a;)s//
.out.//
print//
((++i//
%3*(i//
%5)<1//
?(i%3//
<1?//
"App"//
+"le"//
:"")+//
(i%5<//
1?//
"Pie"//
:"")://
i)+//
"\n");}

```

Try It Online

Pretty boring due to the line comments. The only interesting thing here is the use of a null `System` reference, which seems to be necessary in order to print to standard out in under 8 bytes per line. Note also that the `print` method call is the bottleneck.

## Ungolfed with no comments:

```
a -> {
    System s = null;
    for (int i = 0; i < a; )
        s.out.print(
            (++i % 3 * (i % 5) < 1 ?
                (i % 3 < 1 ? "App"+"le" : "")
                    + (i % 5 < 1 ? "Pie" : "")
                : i
            ) + "\n"
        );
}

```
> 0 votes

---
Tags: code-challenge, restricted-source, source-layout
---


title: Missing numbers in arithmetic sum

text:
# Question
Title: Missing numbers in arithmetic sum
**Challenge**

Giving a valid arithmetic sum with some missing numbers, output the full expression.

Example:

```
    1#3                 123
+   45#     =>     +    456
--------            --------
    579                 579

```

**Input**

* Expression format can be an array `["1#3", "45#", "579"]`, a string `"1#3+45#=579"`, or 3 inputs `f("1#3","45#","579")`

**Output**

* Same as input
* You don't need to output the result

**Notes**

* The missing numbers are going to be represented using `#` or any other constant non-numeric character you want
* Assume result wont have a missing number
* Assume Input/Output consist in 2 terms and a final result
* Assume both term \> 0 and result \>= 2
* There might be multiple solutions. You can output anyone as long as the sum result match

**Test Cases with possibly outputs (pretty format)**

```
    #79                     879
+   44#         =>      +   444
--------                --------
    1323                   1323

    5#5                     555
+   3#3         =>      +   343
--------                --------
    898                     898

      #                       1
+     #         =>      +     1
--------                --------
      2                       2

    ###                     998
+   ###         =>      +     1     PD: there are a lot of possible outputs for this one
--------                --------
    999                     999

    123                     123
+     #         =>      +     1
--------                --------
    124                     124

      9                       9
+    #6         =>      +    46
--------                --------
     55                      55

    #123651                     1123651
+      #98#         =>      +      7981
------------                -----------
    1131632                     1131632

```

---

Standard rules apply

# Answer
# Brachylog, ~~22~~ 16 bytes

```
{Ṣ∧Ị∋|}ᵐ²ịᵐ.k+~t

```

Try it online!

-6 bytes thanks to @Fatelize

## Explanation

```
{Ṣ∧Ị∋|}ᵐ²ịᵐ.k+~t
{     }ᵐ²                   #   for each letter in each string
 Ṣ∧Ị∋                       #       if " " return a digit; else input
     |                      #
         ịᵐ                 #   cast each string to number
            k+              #   the sum of all but the last one
              ~t            #       is equal to the last one
           .                #   output that list

```
> 9 votes

# Answer
# JavaScript (ES6), ~~74~~ 57 bytes

Takes input as `(a)(b)(result)`, where ***a*** and ***b*** are strings with `.` for unknown digits and ***result*** is an integer. Returns an array of 2 integers.

```
a=>b=>F=(c,n)=>`${r=[c,n]}`.match(`^`+[a,b])?r:F(c-1,-~n)

```

Try it online!

### Commented

```
a => b =>                // a, b = term patterns (e.g. a = ".79", b = "44.")
  F = (c,                // c = expected result (e.g. 1323)
          n) =>          // n = guessed value of b, initially undefined
    `${r = [c, n]}`      // we coerce r = [c, n] to a string (e.g. "879,444")
                         // if n is still undefined, this gives just c followed by a comma
    .match(`^` + [a, b]) // we coerce [a, b] to a string, prefixed with "^" (e.g. "^.79,44.")
    ?                    // this is implicitly turned into a regular expression; if matching:
      r                  //   return r
    :                    // else:
      F(c - 1, -~n)      //   decrement c, increment n and do a recursive call

```
> 8 votes

# Answer
## Matlab, 143 134 132 119 115 bytes

```
function[m]=f(x,y,r),p=@(v)str2num(strrep(v,'#',char(randi([48,57]))));m=[1,1];while sum(m)-r,m=[p(x),p(y)];end;end

```

-4 bytes thanks to @Luismendo

Try it Online

---

Pretty big and pretty stupid. It simply replaces all `#` with random digits until it finds the correct ones.
> 7 votes

# Answer
# , ~~67~~ 51 bytes

Rock simple and scales horribly, just grep all the sum combinations. Use "." for unknown digits. It won't find the same answer as test case number 4, but it will give **a** possible answer, which follows the letter of the rules as given.

-16 bytes by grepping after forming the output and replacing `paste` with the `?` operator.

```
function(x,y,z,`?`=paste)grep(x?y,1:z?z:1-1,v=T)[1]

```

Try it online!
> 5 votes

# Answer
# Charcoal, 32 bytes

```
Ｆ²⊞υ0Ｗ⁻ζΣＩυ≔Ｅ⟦θη⟧⭆κ⎇⁼μ#‽χμυ←Ｅυ⮌ι

```

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

```
Ｆ²⊞υ0

```

Push two string `0`s to the predefined empty list `u` to get the while loop going.

```
Ｗ⁻ζΣＩυ

```

Repeat while the sum of casting the values in `u` to integer is not equal to the desired result.

```
≔Ｅ⟦θη⟧

```

Create an array of the two inputs and map over it.

```
⭆κ⎇⁼μ#‽χμυ

```

Replace each `#` with a random digit and assign the result back to `u`.

```
←Ｅυ⮌ι

```

Print the result right justified. (Left justified would be just `υ` for a 4-byte saving.)
> 3 votes

# Answer
# Jelly, 20 bytes

```
ØDṛċ¡V€)ŒpḌð€ŒpS⁼¥ƇḢ

```

Try it online!
> 3 votes

# Answer
# 05AB1E (legacy), ~~23~~ 20 bytes

```
[²³«εð9ÝΩ:}²gôJDO¹Q#

```

-3 bytes thanks to *@Emigna*.

Unknown digits are spaces (). Input order should be: expected result; longest string; shortest string.

Try it online.

**Explanation:**

```
[                 # Start an infinite loop
 ²³«              #  Take the second and third inputs, and merge them together
               #   i.e. " 79" and " 4 " → " 79 4 "
    ε     }    #  Map each character to:
     ð   :     #   Replace a space with:
      9ÝΩ      #   A random digit in the range [0,9]
               #    i.e. " 79 4 " → ['3','7','9','2','4','3']
               #    i.e. " 79 4 " → ['5','7','9','7','4','4']
²g             #  Get the length of the second input
               #   i.e. " 79" → 3
  ô            #  And split it into two numbers again
               #   i.e. ['3','7','9','2','4','3'] and 3 → [['3','7','9'],['2','4','3']]
               #   i.e. ['5','7','9','7','4','4'] and 3 → [['5','7','9'],['7','4','4']]
   J           #  Join each list together to a single number
               #   i.e. [['3','7','9'],['2','4','3']] → [379,243]
               #   i.e. [['5','7','9'],['7','4','4']] → [579,744]
    D          #  Duplicate this list
     O         #  Sum the list
               #   i.e. [379,243] → 622
               #   i.e. [579,744] → 1323
      ¹Q#      #  If it's equal to the first input: stop the infinite loop
               #  (and output the duplicate list implicitly)
               #   i.e. 1323 and 622 → 0 (falsey) → continue the loop
               #   i.e. 1323 and 1323 → 1 (truthy) → stop the loop and output [579,744]

```
> 3 votes

# Answer
# Perl 6, ~~81~~ 74 bytes

*-7 bytes thanks to nwellnhof!*

```
{first {try S/\=/==/.EVAL},map {$^a;S:g[\#]=$a[$++]},[X] ^10 xx.comb('#')}

```

Try it online!

Anonymous code block that takes input as a string containing an arithmetical expression e.g. "12#+45#=579". Substitutes each `#` with possible permutations of digits, substitutes the`=` with `==` and finds the first valid result.

### Explanation:

```
{  # Anonymous code block                                                      }
 first   # Find the first of:
                                                               ^10  # The range of 0 to 9
                                                                   xx.comb('#') # Multiplied by the number #s in the code
                                                          ,[X]  # The cross-product of these lists
                          map   # Map each crossproduct to:
                              {$^a;.trans: "#"=>{$a[$++]}}  # The given string with each # translated to each element in the list
      {try S/\=/==/.EVAL}, # Find which of these is true when = are changed to == and it is eval'd

```
> 3 votes

# Answer
# APL (Dyalog Unicode), 22 bytes

```
{'#'⎕R{⍕?10}t}⍣{⍎⍺}t∘←

```

Try it online!
> 2 votes

# Answer
# Java 10, ~~203~~ ~~198~~ 193 bytes

```
(a,b,c)->{int A=0,B=0,l=a.length();for(a+=b,b="";A+B!=c;A=c.valueOf(b.substring(0,l)),B=c.valueOf(b.substring(l)),b="")for(var t:a.getBytes())b+=t<36?(t*=Math.random())%10:t-48;return A+"+"+B;}

```

Try it online.

**Explanation:**

```
(a,b,c)->{           // Method with 2 Strings & integer parameters and String return-type
  int A=0,B=0,       //  Result-integers, starting both at 0
      l=a.length();  //  Length of the first String-input
  for(a+=b,          //  Concat the second String-input to the first
      b="";          //  Reuse `b`, and start it as an empty String
      A+B!=c         //  Loop as long as `A+B` isn't equal to the integer-input
      ;              //    After every iteration:
       A=c.valueOf(b.substring(0,l)),
                     //     Set `A` to the first String-part as integer
       B=c.valueOf(n.substring(l)),
                     //     Set `B` to the second String-part as integer
       b="")         //     Reset `b` to an empty String
    for(var t:a.getBytes())
                     //   Inner loop over the characters of the concatted String inputs
      b+=t<36?       //    If the current character is a '#':
          (t*=Math.random())%10
                     //     Append a random digit to `b`
         :           //    Else (it already is a digit):
          t-48;      //     Append this digit to `b`
  return A+"+"+B;}   //  After the loop, return `A` and `B` as result

```
> 2 votes

# Answer
# Python 3, ~~121~~ ~~155~~  ~~152~~  149 bytes

```
import re
def f(i,k=0,S=re.sub):s=S('#','%s',i)%(*list('%0*d'%(i.count('#'),k)),);print(s)if eval(S('=','==',S('\\b0*([1-9])','\\1',s)))else f(i,k+1)

```

Try it online!

*+34 New solution with regex to circumvent the fact that python doesn't support numbers with leading zeroes.*

*-3 thanks to @Jonathan Frech*

---

**The old solution doesn't work if # is the first character in any number (because eval doesn't accept leading zeroes) and is therefore invalid :(**

```
def f(i,k=0):
 s=i.replace('#','%s')%(*list('%0*d'%(i.count('#'),k)),)
 print(s)if eval(s.replace('=','=='))else f(i,k+1)

```

Try it online!
> 1 votes

# Answer
# C# .NET, ~~225~~ ~~220~~ 196 bytes

```
(a,b,c)=>{int A=0,B=0,l=a.Length;for(a+=b,b="";A+B!=c;A=int.Parse(b.Substring(0,l)),B=int.Parse(b.Substring(l)),b="")foreach(var t in a)b+=(t<36?new System.Random().Next(10):t-48)+"";return(A,B);}

```

Port of my Java 10 answer.
(I'm very rusty in C# .NET golfing, so can defintely be golfed..)

-3 bytes implicitly thanks to *@user82593* and this new C# tip he added.
-29 bytes thanks to *@hvd*.

Try it online.

**Explanation:**

```
(a,b,c)=>{        // Method with 2 string & int parameters and int-tuple return-type
  int A=0,B=0,    //  Result-integers, starting both at 0
      l=a.Length; //  Length of the first string-input
  for(a+=b,       //  Concat the second string-input to the first
      b="";       //  Reuse `b`, and start it as an empty string
      A+B!=c      //  Loop as long as `A+B` isn't equal to the integer-input
      ;           //    After every iteration:
       A=int.Parse(b.Substring(0,l)),
                  //     Set `A` to the first string-part as integer
       B=int.Parse(b.Substring(l)),
                  //     Set `B` to the second string-part as integer
       b="")      //     Reset `b` to an empty string
    foreach(var t in a)
                  //   Inner loop over the characters of the concatted string inputs
      b+=(t<36?   //    If the current character is a '#':
           new System.Random().Next(10)
                  //     Use a random digit
          :       //    Else (it already is a digit):
           t-48)  //     Use this digit as is
         +"";     //    And convert it to a string so it can be appended to the string
  return(A,B);}   //  After the loop, return `A` and `B` in a tuple as result

```
> 1 votes

# Answer
# C (gcc), ~~228~~ ~~213~~ ~~203~~ ~~172~~ 170 bytes

**-15** Bytes thanks to *@ceilingcat*. I've never used `index` before.

**-10** Bytes thanks to *@Logem*. Preprocessor magic

refactored call to `exit(0)` with puts as parameter.

```
char*c,*p[9],k;main(i,v)int**v;{for(i=X[1],35))||X[2],35))?p[k++]=c,main(*c=57,v):k;!c*i--;)47==--*p[i]?*p[i]=57:Y[1])+Y[2])^Y[3])?main(i,v):exit(puts(v[2],puts(v[1])));}

```

Try it online!
> 1 votes

# Answer
# Powershell, 91 byte

The script finds all solutions. The total number of iterations is 10 power the number of characters `#`. The recursion depth is equal to the number of characters `#`.

```
filter f{$h,$t=$_-split'#',2
if($t){0..9|%{"$h$_$t"}|f}elseif($h-replace'=','-eq'|iex){$h}}

```

Test script:

```
filter f{$h,$t=$_-split'#',2
if($t){0..9|%{"$h$_$t"}|f}elseif($h-replace'=','-eq'|iex){$h}}

@(
    ,('1#3+45#=579','123+456=579')
    ,('#79+44#=1323','879+444=1323')
    ,('5#5+3#3=898','505+393=898 515+383=898 525+373=898 535+363=898 545+353=898 555+343=898 565+333=898 575+323=898 585+313=898 595+303=898')
    ,('#+#=2','0+2=2 1+1=2 2+0=2')
    ,('9+#6=55','9+46=55')
    ,('123+##=124','123+01=124')
    ,('#123651+#98#=1131632','1123651+7981=1131632')
    ,('##+##=2','00+02=2 01+01=2 02+00=2')
    ,('##+##=99','00+99=99 01+98=99 02+97=99 03+96=99 04+95=99 05+94=99 06+93=99 07+92=99 08+91=99 09+90=99 10+89=99 11+88=99 12+87=99 13+86=99 14+85=99 15+84=99 16+83=99 17+82=99 18+81=99 19+80=99 20+79=99 21+78=99 22+77=99 23+76=99 24+75=99 25+74=99 26+73=99 27+72=99 28+71=99 29+70=99 30+69=99 31+68=99 32+67=99 33+66=99 34+65=99 35+64=99 36+63=99 37+62=99 38+61=99 39+60=99 40+59=99 41+58=99 42+57=99 43+56=99 44+55=99 45+54=99 46+53=99 47+52=99 48+51=99 49+50=99 50+49=99 51+48=99 52+47=99 53+46=99 54+45=99 55+44=99 56+43=99 57+42=99 58+41=99 59+40=99 60+39=99 61+38=99 62+37=99 63+36=99 64+35=99 65+34=99 66+33=99 67+32=99 68+31=99 69+30=99 70+29=99 71+28=99 72+27=99 73+26=99 74+25=99 75+24=99 76+23=99 77+22=99 78+21=99 79+20=99 80+19=99 81+18=99 82+17=99 83+16=99 84+15=99 85+14=99 86+13=99 87+12=99 88+11=99 89+10=99 90+09=99 91+08=99 92+07=99 93+06=99 94+05=99 95+04=99 96+03=99 97+02=99 98+01=99 99+00=99')
) | % {
    $s,$e = $_
    $r = $s|f
    "$($e-eq$r): $r"
}

```

## Powershell, 'Assume both term \> 0' is mandatory, 110 bytes

```
filter f{$h,$t=$_-split'#',2
if($t){0..9|%{"$h$_$t"}|f}else{$a,$b,$c=$_-split'\D'
$_|?{+$a*+$b*!(+$a+$b-$c)}}}

```
> 0 votes

# Answer
# PHP, 112 bytes

lame brute force solution

```
for(;$s=$argn;eval(strtr($s,['='=>'==','#'=>0]).'&&die($s);'))for($k=$n++;$k;$k=$k/10|0)$s[strpos($s,35)]=$k%10;

```

takes string as input, stops at first solution. Run as pipe with `-nR` or try it online.
> 0 votes

---
Tags: code-golf, arithmetic, integer
---


# Question
Title: Who can get more points? (Card game KoTH)
A few days ago, I came up with a fun card game to play with my friends. We were having fun playing it, when I thought, "Why not make this a KoTH?" So, here it is!

## Overview

In this game, the objective is to get the most points. Your bot starts with 0 points and 20 energy. Every turn (500 in a game), both bots play one card. Some earn you points, some take the opponent's points.

## Cards

```
A=Add 5 points to your score     [Costs 0.1 energy]
R=Remove 5 points from opponent  [Costs 0.1 energy]
H=Half your next score           [Costs 1 energy]
Y=Half opponent's next score     [Costs 1 energy]
D=Double your next score         [Costs 2 energy]
T=Double opponent's next score   [Costs 2 energy]
N=Negate your next score         [Costs 3 energy]
O=Negate opponent's next score   [Costs 3 energy]
S=Shield for 5 turns             [Costs 15 energy]
X=Take five energy from opponent [Gives opponent 10 points]
E=Refill five energy             [Costs 10 points]

```

## How it works

First how would halving your next score or doubling your opponent's next score come in handy? Well, imagine you get 5 points taken away on your next turn. Instead, 2.5 points get taken away. Cool, right? Or, negating your next score would give you 5. If you think your opponent will give themself points, negate their next move!

The order of operations for modifying point values is:

1. Add all positive or negative point changes
2. Half if necessary
3. Double if necessary
4. Negate if necessary
5. If shielding and result is negative, change to 0

Attempting to lower the opponent's **energy** past 0 does not work. There is no upper limit to energy, or lower limit to points. Energy reducing cards are played before other cards, so if Bot A with 17 energy runs shield and Bot B runs take 5 energy, Bot A cannot shield.

## Creating a bot

In **Javascript**, create a new function with whatever name you wish. This function should take 3 parameters:

```
Array of Numbers (Your coins, Opponent's coins)
Array of Numbers (Your energy, Opponent's energy)
Object (Use for storage between rounds)

```

Note that there is no way of knowing what cards have been played. You must teach the bot to figure it out by itself!

The way you select a card is by `return`ing a string, containing the letter of the card in uppercase or lowercase. Note that Standard Loopholes (obviously) aren't allowed. If any other value is returned, your bot just does nothing.

## Scoring

Every bot will be run against each other bot once. The loser will get 0 points, anbd the winner will get the difference in points added to its total score (Between all rounds). The top 8 will compete in a tournament. In other words, they will each fight one other bot, the four winners will fight another bot, and the two remaining bots will fight for first.

## Controller

```
var botDataList = [
    {
        name: "",
        desc: "",
        run: function(){

        }
    }, {
        name: "",
        desc: "",
        run: function(){

        }
    }
];

function playGame() {
    botSetup();
    for (var i = 0; i < 500; i++) {
        runBots();
    }
    var botA = botDataList[0];
    var botB = botDataList[1];
    console.log("Bot " + botA.name + ": " + botA.points);
    console.log("Bot " + botB.name + ": " + botB.points);
}

function botSetup() {
    for (var b, i = 0; i < 2; i++) {
        b = botDataList[i];
        b.points = 0;
        b.energy = 20;
        b.storage = {};
        b.affectAdd = [];
        b.affectAct = [];
        b.shield = 0;
    }
}

function runBots() {
    var botA = botDataList[0];
    var botB = botDataList[1];
    var resA = botA.run([botDataList[0].points, botDataList[1].points], [botDataList[0].energy, botDataList[1].energy], botDataList[0].storage).toLowerCase();
    var resB = botB.run([botDataList[1].points, botDataList[0].points], [botDataList[1].energy, botDataList[0].energy], botDataList[1].storage).toLowerCase();
    var modA = 0;
    var modB = 0;
    if (resA == 'a' && botA.energy >= 0.1) {
        botA.energy -= 0.1;
        modA += 5;
    } else if (resA == 'r' && botA.energy >= 0.1) {
        botA.energy -= 0.1;
        modB -= 5;
    } else if (resA == 'h' && botA.energy >= 1) {
        botA.energy -= 1;
        botA.affectAdd.push('h');
    } else if (resA == 'y' && botA.energy >= 1) {
        botA.energy -= 1;
        botB.affectAdd.push('h');
    } else if (resA == 'd' && botA.energy >= 2) {
        botA.energy -= 2;
        botA.affectAdd.push('d');
    } else if (resA == 't' && botA.energy >= 2) {
        botA.energy -= 2;
        botB.affectAdd.push('d');
    } else if (resA == 'n' && botA.energy >= 3) {
        botA.energy -= 3;
        botA.affectAdd.push('n');
    } else if (resA == 'o' && botA.energy >= 3) {
        botA.energy -= 3;
        botB.affectAdd.push('n');
    } else if (resA == 's' && botA.energy >= 15) {
        botA.energy -= 15;
        botA.shield += 5;
    } else if (resA == 'x') {
        modB += 10;
        botB.energy = (botB.energy >= 5) ? botB.energy - 5 : 0;
    } else if (resA == 'e' && botA.points >= 10) {
        modA -= 10;
        botA.energy += 5;
    }
    if (resB == 'a' && botB.energy >= 0.1) {
        botB.energy -= 0.1;
        modB += 5;
    } else if (resB == 'r' && botB.energy >= 0.1) {
        botB.energy -= 0.1;
        modA -= 5;
    } else if (resB == 'h' && botB.energy >= 1) {
        botB.energy -= 1;
        botB.affectAdd.push('h');
    } else if (resB == 'y' && botB.energy >= 1) {
        botB.energy -= 1;
        botA.affectAdd.push('h');
    } else if (resB == 'd' && botB.energy >= 2) {
        botB.energy -= 2;
        botB.affectAdd.push('d');
    } else if (resB == 't' && botB.energy >= 2) {
        botB.energy -= 2;
        botA.affectAdd.push('d');
    } else if (resB == 'n' && botB.energy >= 3) {
        botB.energy -= 3;
        botB.affectAdd.push('n');
    } else if (resB == 'o' && botB.energy >= 3) {
        botB.energy -= 3;
        botA.affectAdd.push('n');
    } else if (resB == 's' && botB.energy >= 15) {
        botB.energy -= 15;
        botB.shield += 5;
    } else if (resB == 'x') {
        modA += 10;
        botA.energy = (botA.energy >= 5) ? botA.energy - 5 : 0;
    } else if (resB == 'e' && botB.points >= 10) {
        modB -= 10;
        botB.energy += 5;
    }
    if (botA.affectAct.includes('h')) {
        modA *= 0.5;
    }
    if (botA.affectAct.includes('d')) {
        modA *= 2;
    }
    if (botA.affectAct.includes('n')) {
        modA *= -1;
    }
    if (botA.shield > 0) {
        modA = (modA < 0) ? 0 : modA;
        botA.shield--;
    }
    botA.points += modA;
    botA.affectAct = botA.affectAdd;
    botA.affectAdd = [];
    if (botB.affectAct.includes('h')) {
        modB *= 0.5;
    }
    if (botB.affectAct.includes('d')) {
        modB *= 2;
    }
    if (botB.affectAct.includes('n')) {
        modB *= -1;
    }
    if (botB.shield > 0) {
        modB = (modB < 0) ? 0 : modB;
        botB.shield--;
    }
    botB.points += modB;
    botB.affectAct = botB.affectAdd;
    botB.affectAdd = [];
}

/*  A=Add 5 points to your score     [Costs 0.1 energy]
    R=Remove 5 points from opponent  [Costs 0.1 energy]
    H=Half your next score           [Costs 1 energy]
    Y=Half opponent's next score     [Costs 1 energy]
    D=Double your next score         [Costs 2 energy]
    T=Double opponent's next score   [Costs 2 energy]
    N=Negate your next score         [Costs 3 energy]
    O=Negate opponent's next score   [Costs 3 energy]
    S=Shield for 5 turns             [Costs 15 energy]
    X=Take five energy from opponent [Gives opponent 10 points]
    E=Refill five energy             [Takes 10 points]           */

```

# Answer
# Doom: OX (Negate opponent - Take energy) Combo

```
function(coins, energy, obj) {
    let mycoin = coins[0]
    let yourcoin = coins[1]
    let myenergy = energy[0]
    let yourenergy = energy[1]
    if (obj.last === 'O') obj.last = 'X'
    else if (myenergy >= 3 && (yourcoin > 0 || yourenergy > 0)) obj.last = 'O'
    else if (mycoin >= 10 && myenergy < 3) obj.last = 'E'
    else obj.last = 'A'
    return obj.last
}

```

If a player has zero points AND zero energy, it can do absolutely nothing. This bot, named "Doom", aims to put the opponent in this doomed state, and then happily accumulates its own score.

Here is a run against The Classic. Doom wins against Classic with around 1600 - 1800 score, while Classic is always stuck at 0 score and 0 energy.

Doom is arguably the strongest among the four bots posted so far (Classic, Greedy, Greedier and Doom), but my guess is it's still susceptible to some kind of anti-Doom.
> 3 votes

# Answer
# Doom-RX

```
function(coins, energy, obj) {
    let mycoin = coins[0]
    let yourcoin = coins[1]
    let myenergy = energy[0]
    let yourenergy = energy[1]
    if(!obj.last) obj.last = ' RXRX';
    if(obj.last.length > 1) obj.last = obj.last.substring(1, 5)
    else if (obj.last === 'O') obj.last = 'X'
    else if (myenergy >= 3 && (yourcoin > 0 || yourenergy > 0)) obj.last = 'O'
    else if (mycoin >= 10 && myenergy < 3) obj.last = 'E'
    else obj.last = 'A'
    return obj.last.substring(0,1)
}

```

Almost entirely derivative of Bubbler's answer, but with a hardcoded opening sequence that counters that specific entry. Here's this run against Doom.

Essentially, using R has less energy cost than O, so when both play OX against each other after the 4th turn Doom is stuck at 0/0, while Doom-RX survives at -30/1.8 and is able to recover.

RXRX isn't the only sequence that works against Doom, but it does look to be among the most robust 4-letter sequences and I liked it best aesthetically. I'm sure there's a more effective approach to this than hard coding, though.

Overall OX seems overbearingly powerful; I'd be surprised if an entry that didn't use it could beat this kind of strategy.
> 3 votes

# Answer
# Greedy

```
function(coins, energy, obj) {
    if (energy[0] < 0.2) return 'E';
    else return 'A';
}

```

I'm probably misunderstanding the game, but I don't see any reason not to just increase your own points every round.
> 2 votes

# Answer
# Greedier: NE (Negate self - Refill energy) Combo

```
function(coins, energy, obj) {
    let mycoin = coins[0]
    let myenergy = energy[0]
    if (mycoin >= 10 && (obj.last === 'N' || myenergy <= 3.1)) obj.last = 'E'
    else if (mycoin >= 20 && myenergy >= 8) obj.last = 'N'
    else obj.last = 'A'
    return obj.last
}

```

### How it (may) work

```
N : Energy -= 3
E : Energy += 5; Points += -(-10)
---------------------------------
    Energy += 2; Points += 10

```

So we don't even need to worry about being out of energy.

Here is the result against Greedy. Greedy gets only 2410 since it has to refill its energy from time to time. On the other hand, Greedier achieves full 2500 score if the opponent doesn't interfere.

The code above includes a bit of anti-failure measures:

* If it's getting out of energy somehow, force refill energy (E).
* If it's out of points, try getting some basic points (A).
* Use negate (N) only if it has enough energy to run it even if the opponent plays drain energy (X) i.e. `3 + 5 = 8`, AND it has enough coins to run E next turn even if the opponent plays double opponent (T) + reduce opponent 5 (R) i.e. `10 + 5 * 2 = 20`.
> 2 votes

# Answer
# Doom EX (Rock, paper, scissors!)

```
function(coins, energy, obj) {
    let mycoin = coins[0]
    let yourcoin = coins[1]
    let myenergy = energy[0]
    let yourenergy = energy[1]
    if(!obj.last) obj.last = ' EXEX';
    if(obj.last.length > 1) obj.last = obj.last.substring(1, 5)
    else if (obj.last === 'O') obj.last = 'X'
    else if (myenergy >= 3 && (yourcoin > 0 || yourenergy > 0)) obj.last = 'O'
    else if (mycoin >= 10 && myenergy < 3) obj.last = 'E'
    else obj.last = 'A'
    return obj.last.substring(0,1)
}

```

All credit goes to @Bubbler and @ripkoops, I just wanted to point this out. This version manages to beat Doom RX, but loses to Doom OX. Looks like this KOTH is rock paper scissors in disguise...

RX vs EX
> 2 votes

# Answer
# The Classic (aka Random Player)

```
function(coins, energy, obj) {
    if (energy[0]<1) return ['A','R','X'][(Math.random()*3)|0];
    else if (energy[0]<2) return ['A','R','H','Y','X'][(Math.random()*5)|0];
    else if (energy[0]<3) return ['A','R','H','Y','D','T','X'][(Math.random()*7)|0];
    else if (energy[0]<10) return ['A','R','H','Y','D','T','X','N','O'][(Math.random()*9)|0];
    else if (energy[0]<15) return ['A','R','H','Y','D','T','X','N','O','E'][(Math.random()*10)|0];
    else return ['A','R','H','Y','D','T','X','N','O','E','S'][(Math.random()*11)|0];
}

```
> 1 votes

---
Tags: king-of-the-hill, javascript
---


title: Traceless Busy Beaver

text:
# Question
Title: Traceless Busy Beaver
All those busy beavers made quite a mess. They wrote all over the tape. At this rate, our neighbour will stop lending us unbounded tapes.

We need a new way to play the busy beaver game, one that doesn't ruin every tape we use.

# The Rules

Brainfuck only. Memory tape is unbounded both ways. Input instruction will always read \\$0\\$, so it can be used to clear a value.

50 bytes source limit.

At the end of execution, memory must be all \\$0\\$s.

Score is distance between the memory pointer's starting location and final location - if it takes \\$n\\$ move instructions to go between them, your score is \\$n\\$. Higher is better. Provide an exact value if you can, otherwise provide an estimate.

# Example

## 32 bytes, \\$2^{255}-1\\$

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

```

## Explanation

```
-                                Initialize the list to [255].
 [                             ] Repeat as long as the list is not empty.
 [-                            ] Decrement the left end. We need to shrink the numbers so it ends eventually.
 [ [                         ] ] Skip if 0 already.
 [ [[>]                      ] ] Move to the cell past the right end.
 [ [   +                     ] ] Make this cell 1.
 [ [    >                    ] ] Go right again.
 [ [     +                   ] ] Make this cell 1. We've now appended [1, 1].
 [ [      [<]>               ] ] Go back to the first nonzero cell on the left.
 [ [          -              ] ] And decrement it.
 [ [           [            ]] ] We will need to transfer the rest of the number from the left to the right, so keep looping.
 [ [           [[>]<        ]] ] Go to the last nonzero cell on the right.
 [ [           [    +<+     ]] ] Increment this and the one on the left. These are the cells we appended earlier. We transfer to them.
 [ [           [       [<]> ]] ] Go back to the first nonzero cell on the left, which we are transferring from.
 [ [           [           -]] ] Decrement here on the left to balance out the incrementing on the right.
 [                            >] We end the iteration on a now empty cell. Move right, the new left end is there.

```

We begin with the list \\$\[255\]\\$. At each iteration, we consume the value \\$n\\$ on the left of the list, and if \\$n\>1\\$, we append \\$\[n-1, n-1\]\\$ to the right. The numbers appended \\$(n-1)\\$ are lower than the original \\$(n)\\$, so they will get smaller until they are \\$1\\$, at which point they are consumed without expanding. Thus, the process ends eventually, with all \\$0\\$s in memory. However, at each step, the number of copies of the number doubles. The score of this program initialized with the list \\$\[n\]\\$ is \\$2^n-1\\$.

This example is meant to show some of the techniques used in creating a submission. It's not competitive for its size.

# Answer
> 10 votes
## Score: \\$ A(255, 2) - 1 = (2 \uparrow^{253} 5) - 4 \\$

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

```

\\$ A \\$ here is the Péter-Ackermann formulation of the Ackermann function, while the other score expression uses Knuth up-arrow notation. The 35-byte main loop `[-[<+>>[-<[->+<]+>>]+<-]>[>]+[<]+<]` can be used to compute \\$ A(m,n) \\$ by placing on the tape the values `1 - m, m, 1 <n times>` and entering the loop with the pointer on the `m` cell. After the loop terminates, the nonzero tape contents are \\$ A(m,n) \\$ ones starting immediately to the right of the pointer.

I used the following Python program for modeling the behavior of the program:

```
def a(M, N):
    assert M > 0
    m = [-M + 1, M]
    n = N
    while m[-1]:
        while m[-1] > 1:
            m[-1] -= 1
            m[-2] += 1
            while n:
                m.insert(-1, 1)
                n -= 1
            n = 1
        n += 2
        m.pop()
    return n

```

---
Tags: code-challenge, brainfuck, busy-beaver
---


title: Converting ISBN-13 to ISBN-10

text:
# Question
Title: Converting ISBN-13 to ISBN-10
### Introduction

In this challenge your task is to generate the ISBN-10 code for books given its ISBN-13 code, assuming that such a code exists. Such an ISBN-13 code consists of several parts separated by `-`:

```
978-GG-PPPP-TTT-C

```

The letters `G` (group), `P` (publisher), `T` (title) and `C` (checksum) all stand for one digit. For the purpose of this challenge the grouping and the computation of `C` (see this challenge) are not interesting and we'll drop all hyphens to make this task simpler.

An ISBN-10 number has a very similar layout:

```
GG-PPPP-TTT-c

```

The letters `G`,`P` and `T` are the same as for the 13 digits ISBN, however `c` is different (and is computed using a different algorithm). The digit `c` is chosen in a way such that the following equivalence holds (digits in order):

```
10*G + 9*G + 8*P + … + 3*T + 2*T + 1*c = 0 (mod 11)

```

### Example

Let us consider the ISBN number `9780345391803`: To get its corresponding ISBN-10 code we simply drop the leading `978` and the checksum `3` yielding `034539180`.

Next we need to compute the new checksum:

```
10*0 + 9*3 + 8*4 + 7*5 + 6*3 + 5*9 + 4*1 + 3*8 + 2*0 = 185

```

The next number divisible by `11` is `187`, so the new checksum is `2` and thus the resulting ISBN-10 code `0345391802`.

### Rules

* Your input will always have a corresponding ISBN-10 number (ie. it is exactly 13 digits long and starts with `978`)
* The input doesn't necessarily have to be a valid ISBN-13 (eg. `9780000000002`)
* You're guaranteed that the resulting ISBN won't end with `X`
* You may take input as an integer or string (with or without hyphens) however a precomputed list of digits are not allowed
* Your output must be a valid ISBN-10 number (with or without hyphens)
* Your output may be an integer or string (again no lists of digits)

### Testcases

```
9780000000002 -> 0000000000
9780201882957 -> 0201882957
9781420951301 -> 1420951300
9780452284234 -> 0452284236
9781292101767 -> 1292101768
9780345391803 -> 0345391802

```

Note the leading zeroes!

# Answer
> 10 votes
## Retina,  ~~44~~  ~~39~~ 28 bytes

```
>,L3,-2`.+
.
$.>`**
_{11}

_

```

Try it online!

### Explanation

Time to show off some new Retina features. :)

```
>,L3,-2`.+

```

We match the entire input with `.+`, return that match `L`, but select only the characters 3 (zero-based) to -2 (penultimate), inclusive. We also print the result without a trailing linefeed (`>`).

Now, subtracting things in Retina is a bit annoying. But luckily, we're working modulo 11, so we can just invert the coefficients of the linear combination (mod 11) and add everything up. In other words, if the constraint is:

```
10*G + 9*G + 8*P + … + 3*T + 2*T + 1*c = 0 (mod 11)

```

then we get:

```
c = 1*G + 2*G + 3*P + … + 8*T + 9*T (mod 11)

```

That simplifies things a lot here:

```
.
$.>`**

```

We replace each character with that thing at the bottom. `*` is Retina's repetition operator. It's right-associative and it has implicit operands `$&` on the left and `_` on the right, so the substitution is actually short for `$.>`*$&*_`. `$&*_` creates a string of **d** underscores, where **d** is the digit we're currently replacing. Then `$.>`` is the length of the string up to and including the match.1 Hence, the entire expression results in a unary representation of the **n**th term of our linear combination.

```
_{11}

```

Doing the actual modulo is trivial in unary: we just drop all complete sets of 11 underscores.

```
_

```

Finally, we count how many underscores remain and print the result, which completes the ISBN-10.

---

1 How does `$.>`` give the length of the string up to and including the match? You might be familiar with `$`` in regex substitutions, which gives you the string up to (but excluding) the match. By inserting a `>`, we can shift the context of the `$`` to the *separator* between the current match and the next (which is an empty string between the current digit and the next). That separator's `$`` will include the current match. So `$>`` is a shorter way to write `$`$&`. Finally, for all `$x`-type substitution elements, Retina lets you insert a `.` after the `$` to get its length.

# Answer
> 6 votes
# 05AB1E, ~~17~~ ~~15~~ ~~13~~ 12 bytes

```
¦¦¦¨DSƶO11%«

```

Try it online!

**Explanation**

```
¦¦¦            # remove the first 3 characters
   ¨           # remove the last character
    D          # duplicate
     S         # split to list of digits
      ƶ        # multiply each by its 1-based index
       O       # sum
        11%    # mod by 11
           «   # concatenate

```

# Answer
> 5 votes
# PowerShell, ~~96~~ 84 bytes

```
$y=-(([char[]]($x="$args"-replace'^978|.$')|%{--$a*[int]"$_"})-join'+'|iex)%11;$x+$y

```

Try it online!

Takes input `"$args"`, does a regex `-replace` to get only the pertinent part, stores that into `$x` as a string. Then we cast that as a `char`-array and loop through each letter. Inside the loop, we pre-decrement `$a` (which defaults to `0`) and multiply out according to the checksum calculation. Note the cast to `int`, else this would use ASCII values.

We then `-join` those numbers together with `+` and pipe that to `iex` (`Invoke-Expression` and similar to `eval`). We take that `%11` and store that checksum into `$y`. Finally, we string concatenate `$x + $y`, and leave that on the pipeline. Output is implicit.

*Saved 12 bytes thanks to Emigna.*

# Answer
> 5 votes
# Octave, ~~46 41 39~~ 37 bytes

```
@(a)[c=a(4:12) 48+mod(7+c*(1:9)',11)]

```

Try it online!

The code takes input as a string, and returns a string.

The code breaks down as follows:

`@(a)` creates an anonymous function.

With `[c=a(4:12) ... ]` we extract the characters that form the main code, saving a copy to `c` for later use, and adding another copy to the final output string.

Based on @MartinEnter's clever way of swapping `10:-1:2` into `1:10`, we can easily generate that range and transpose it to get a column vector. `c*(1:10)'` does array multiplication of the row vector `c` and range column vector. This is equivalent to doing an element-wise multiplication then summing.

The checksum would normally be `mod(11-sum,11)` to calculate the number required for the sum to be a multiple of 11. However, because `c` was a character string, the sum will actually be larger than it should be by 2592 (48\*54) because we multiplied by numbers that were 48 larger than the actual value.

When we perform the modulo, it will automatically get rid of all but 7 of that 2592. As such, and accounting for the negation of the range, the actual calculation becomes `48+mod(7+sum,11)`. We add on 48 to the result to convert back to an ASCII character.

The checksum character is appended to the end of the result, and the value returned.

# Answer
> 5 votes
# Jelly, 12 bytes

```
ṫ4ṖȮV€xJS%11

```

This is a full program that uses strings for I/O.

Try it online!

### How it works

```
ṫ4ṖȮV€xJS%11  Main link. Argument: s (string of length 13)

ṫ4            Tail 4; discard the first three characters.
  Ṗ           Pop; discard the last characters.
   Ȯ          Output; print the result to STDOUT and return it.
    V€        Eval each; turn digit characters into digits.
       J      Indices; yield [1, ..., 13].
      x       Repeat the first digit once, the second digit twice, etc.
        S%11  Take the sum, modulo 11.
              (implicit) Print the checksum to STDOUT.

```

# Answer
> 4 votes
# JavaScript (ES6), ~~59~~ 56 bytes

```
s=>(s=s.slice(3,-1))+[...s].reduce(n=>n+s[i++]*i,i=0)%11

```

```
f=
s=>(s=s.slice(3,-1))+[...s].reduce(n=>n+s[i++]*i,i=0)%11
//s=>(s=s.slice(3,-1))+(n=0,[...s].map((c,i)=>n+=c*-~i),n)%11
//s=>(s=s.slice(3,-1))+(n=0,[...s].map(c=>n+=c*i++,i=1),n)%11
//s=>(n=0,[...(s=s.slice(3,-1))].map((c,i)=>n+=c*-~i),s+n%11)
//s=>(s=s.slice(3,-1,n=i=0))+eval(`for(c of s)n+=c*-~i++`)%11

console.log(...[
  '9780000000002',
  '9780201882957',
  '9781420951301',
  '9780452284234',
  '9781292101767',
  '9780345391803'
].map(f))
```

-3 bytes thanks to @Shaggy's suggestion.

# Answer
> 3 votes
# Perl 5, 49 + 1 (`-p`) = 50 bytes

```
s/^...|.$//g;$\=(eval s/./"-$&0+".$i++*$&/ger)%11

```

Try it online!

# Answer
> 3 votes
# K (oK), ~~29~~ ~~25~~ ~~24~~ 23 bytes

**Solution:**

```
x,$11!7+/(1+!9)*x:-1_3_

```

Try it online!

**Examples:**

```
x,$11!7+/(1+!9)*x:-1_3_"9780000000002"
"0000000000"
x,$11!7+/(1+!9)*x:-1_3_"9780345391803"
"0345391802"
x,$11!7+/(1+!9)*x:-1_3_"9781292101767"
"1292101768"
x,$11!7+/(1+!9)*x:-1_3_"9780452284234"
"0452284236"

```

**Explanation:**

Evaluation is performed right-to-left.

Two tricks taken from other solutions:

* multiply by 1 2 3... instead of 10 9 8...
* multiply ASCII values and then add 7 to the sum to balance out

Breakdown:

```
x,$11!7+/(1+!9)*x:-1_3_ / the solution
                     3_ / drop three items from the start
                  -1_   / drop one item from the end
                x:      / save this as variable x
               *        / multiply by
         (    )         / all this together
            !9          / til, !9 => 0 1 2 3 4 5 6 7 8
          1+            / add 1 => 1 2 3 4 5 6 7 8 9
      7+/               / sum (+) over (/), start from 7
   11!                  / mod by 11
  $                     / convert back to a string
x,                      / join with x

```

**Notes:**

* **-4 bytes** thanks to Martin Enders's "*just invert the coefficients*" magic.
* **-1 byte** thanks to Tom Carpenter for removing the need to convert to integers (by adding `7` to the sum)
* **-1 byte** start the accumulator at 7

# Answer
> 3 votes
# Pyth, 16 bytes

```
%s.e*ksbpP>Q3hT

```

**Try it here!**

# Pyth, 17 bytes

```
%s*VsMKpP>Q3SlK11

```

**Try it here!**

### Explanation

```
%s.e*hksbpP>Q3hT || Full program. Uses string for input and output.

            Q    || The input.
           > 3   || With elements at indexes smaller than 3 trimmed.
          P      || Pop (remove the last item).
         p       || Print the result without a linefeed, but also return it.
  .e             || Enumerated map. For each (index, value), assign two variables (k, b).
       sb        || b converted to an integer.
    *hk          || And multiplied by k + 1.
 s               || Summation.
%                || Modulo by:
               T || The literal 10.
              h  || Incremented by 1.

```

# Answer
> 3 votes
# C (gcc), ~~96 95 87 86~~ 85 bytes

(-1 thanks to ceilingcat)

```
*f(s,r,c,d)char*s,*r;{for(d=13;--d;s+=*++s<48)r=d>8?c=3,s:r,c-=~d**s;*s=58-c%11;s=r;}

```

Try it online!

To be called as `f(s)`, where `s` is a pointer to the first element of a modifiable character array. Modifies the input array, returns a pointer into the input array.

# Answer
> 3 votes
# Hexagony, ~~77~~ 61 bytes

```
,,,,'~'11=\.A&.=\./';"-'"{4.8}}\'.A.>.,<\'+'%!@}/=+'+{./&{{&/

```

Try it online!

---

Colored:

---

Here is a larger version. There are some path crossings, but because all of those cells are `.` (no-op in Hexagony), you don't need to worry about them:

(I also tried to keep the old mirrors, but sometimes I need to change something)

The linear command executed is:

```
,,,,'48}}
,
while memory > 0:
    ';"-'"{+'+{=A&=''A
    if memory < 0:
        undefined behavior
    &{{&}
    ,
'"''+~'11='%!@

```

---

Explanation: Instead of keeping a counter and do multiplication at each digit, this program:

* keep a "partial sum" variable and "total sum" variable (`p` and `t`)
* for each digit read: add it to partial sum, and add the partial sum to total sum.
* print `(-p-t)%11`, where `%` always return positive results.

# Answer
> 3 votes
# Japt, ~~16~~ 15 bytes

Came up with this down the pub the other night and forgot all about it.

```
s3J
U+¬x_*°TÃuB

```

Try it

# Answer
> 2 votes
# Jelly, 14 bytes

```
ṫ4ṖµV€×JS%11;@

```

Test suite!

# Jelly, 17 bytes

```
Ṛḣ⁵µVD×JḊSN%11;ḊṚ

```

Try it online! or Test suite!

Takes input and outputs as a string.

# Answer
> 2 votes
# Python 2, 62 bytes

```
lambda n:n[3:12]+`-sum(i*int(n[13-i])for i in range(2,11))%11`

```

Try it online!

Takes a string as input; and outputs a string.

# Answer
> 2 votes
# ECMAScript 6, ~~86~~ 67 bytes

```
a=>(c=a.substr(3,9))+([...c].map(v=>g+=--i*v,e=i=g=11)?(e-g%e)%e:0)

```

Try it online!

---

Thanks for Arnauld's comment, switched from `reduce` to `map` and got rid of `return` keyword.

# Answer
> 2 votes
# Retina 0.8.2, ~~72~~ 51 bytes

```
...(.*).
$1¶$1
r`.\G
$&$'
r`.\G
$*
1{11}

¶(1*)
$.1

```

Try it online! Because I haven't learned Retina 1.0 yet. Explanation:

```
...(.*).
$1¶$1

```

Delete the unwanted characters and make a second copy of the appropriate digits.

```
r`.\G
$&$'

```

Suffix each digit in the second copy with its suffix. This effectively repeats each digit in the suffix by its position.

```
r`.\G
$*

```

Convert the digits in the second copy to unary thus adding them together.

```
1{11}

```

Reduce modulo 11. (There are only 9 digits in the first copy, so this can never affect it.)

```
¶(1*)
$.1

```

Convert the result back to decimal and remove the newline again.

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~26~~ 24 bytes

```
∊⍕¨(⊢,11|⊢+.×⍳∘≢)3↓¯1↓⍎¨

```

Try it online!

Tacit prefix function. Takes input as string.

2 bytes saved thanks to @ngn.

### How?

```
∊⍕¨(⊢,11|⊢+.×⍳∘≢)3↓¯1↓⍎¨    ⍝ Main function.
                       ⍎¨    ⍝ Execute each; turns the string into a vector of digits.
                 3↓¯1↓       ⍝ Drop (↓) the last (¯1) and the first 3 digits.
   (           ≢)            ⍝ Tally; returns the number of digits in the vector.
             ⍳∘               ⍝ Then (∘) index (⍳) from 1
            ×                ⍝ Multiply the resulting vector [1..9]
         ⊢+.                 ⍝ Dot product with sum with the original vector;
                             ⍝ This will multiply both vectors, and sum the resulting vector.
      11|                    ⍝ Mod 11
     ,                       ⍝ Concatenate
    ⊢                        ⍝ With the original vector
 ⍕¨                          ⍝ Format each; returns a vector of digits as strings.
∊                            ⍝ Flatten to get rid of the spaces.

```

# Answer
> 1 votes
# Ruby, ~~69 68~~ 64 bytes

```
->n{v=n[3,9];c=11;v+"#{(c-v.chars.map{|i|i.to_i*c-=1}.sum)%11}"}

```

Try it online!

# Answer
> 1 votes
# Clean, ~~104~~ ~~102~~ 98 bytes

```
import StdEnv
$s#s=s%(3,11)
#i=sum[digitToInt d*p\\d<-s&p<-[10,9..]]+10
=s++[toChar(i/11*11-i+58)]

```

Try it online!

# Answer
> 1 votes
# Kotlin, 83 bytes

```
i.drop(3).dropLast(1).let{it+(11-(it.mapIndexed{i,c->(10-i)*(c-'0')}.sum()%11))%11}

```

## Beautified

```
i.drop(3).dropLast(1).let {
    it + (11 - (it.mapIndexed { i, c -> (10 - i) * (c - '0') }.sum() % 11)) % 11
}

```

## Test

```
data class Test(val input: String, val output: String)

fun f(i: String) =

i.drop(3).dropLast(1).let{it+(11-(it.mapIndexed{i,c->(10-i)*(c-'0')}.sum()%11))%11}

val tests = listOf(
        Test("9780000000002", "0000000000"),
        Test("9780201882957", "0201882957"),
        Test("9781420951301", "1420951300"),
        Test("9780452284234", "0452284236"),
        Test("9781292101767", "1292101768"),
        Test("9780345391803", "0345391802")
)

fun main(args: Array<String>) {
    for (c in tests) {
        val answer = f(c.input)
        val good = answer == c.output
        println("$good ${c.input} -> ${c.output} | $answer")
    }
}

```

## TIO

TryItOnline

# Answer
> 1 votes
# PHP, 64 bytes

Unfortunately, in PHP `(-$c)%11` is the same as `-($c%11)`; so I have to get the difference to at least the largest sum possible (55\*9 = 495 = 45\*11) instead of just using `-$c%11`.

```
for($f=11;--$f>1;print$d)$c+=$f*$d=$argn[13-$f];echo(495-$c)%11;

```

or

```
for($c=45*$f=11;--$f>1;print$d)$c-=$f*$d=$argn[13-$f];echo$c%11;

```

Run as pipe with `-nR` or try them online.

# Answer
> 0 votes
# Java 10, 110 bytes

```
l->{var s=l+"";int c=0,i=3;for(;i<12;)c+=(13-i)*(s.charAt(i++)-48);return(l-(long)978e10)/10*10+(11-c%11)%11;}

```

Takes input and outputs as a `long` integer. Try it online here.

Ungolfed version:

```
l -> { // lambda taking a long as argument
    var s = l + ""; // convert the input to a String
    int c = 0, // the check digit
    i = 3; // variable for iterating over the digits
    for(; i < 12 ;) // go from the first digit past 978 to the one before the check digit
        c += (13 - i) * (s.charAt(i++) - 48); // calculate the check sum
    return (l - (long) 978e10) // remove the leading 978
           /10 *10 // remove the original check digit
           + (11 - c % 11) % 11; // add the new check digit
}

```

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