title: Optimize my Nullifiers

text:
# Question
Title: Optimize my Nullifiers
I am a big fan of the game Creeper World, and especially the sequel. You don't need to know how this game works to answer the question, I just wanted to mention where my question originated from.

In the game, your objective is to destroy the Emitters that are spawning Creeper, using a weapon known as a nullifier.

Nullifiers can destroy any emitter in this radius:

```
 eee
eeeee
eenee
eeeee
 eee

```

Each nullifier CAN target multiple Emitters.

**Your objective**

Given an array simulating a 2D map consisting of *nothing* and *emitters* with whatever characters you like, could be *spaces* and *e* or numbers - just be sure they are distinguishable, output the same map with the optimal amount of nullifiers *n* (or what you would like) placed, so that the emitters are destroyed with the least amount of nullifiers.

If there are multiple optimal ways of doing it, just outputting one would be fine. If, however, the task is not solvable, say there are so many emitters that no layout will ever hit all of them, you must output a distinguishably different something, null will suffice

**Quick Rules:**

* Input: multidimensional array
* Input will contain two characters, meaning *nothing* and *emitter*, include what is what in your answer
* Output: multidimensional array
* Output will contain three characters, meaning *nothing*, *emitter* and *nullifier* OR a distinguishable output if the input is unsolvable
* You may only replace the *nothing* character with a nullifier
* A nullifier can hit multiple emitters, and will always hit all that are in range
* A nullifier can hit in the area specified above, and will always hit all emitters that it can target
* Shortest answers in bytes win
* standard loopholes forbidden

**Examples**

Input:

```
[[ , ,e, , ],
 [ , , , , ],
 [e, , , ,e],
 [ , , , , ],
 [ , ,e, , ]]

```

Output:

```
 [[ , ,e, , ],
  [ , , , , ],
  [e, ,n, ,e],
  [ , , , , ],
  [ , ,e, , ]]

```

Input:

```
[[e,e,e,e,e],
 [e, , , ,e],
 [e, , , ,e],
 [e, , , ,e],
 [e,e,e,e,e]]

```

Output:

```
[[e,e,e,e,e],
 [e, ,n, ,e],
 [e, , , ,e],
 [e, ,n, ,e],
 [e,e,e,e,e]]

```

Input:

```
[[e, , , , , , ,e, ,e, , , ,e, ,e, ,e, ,e],
 [ , ,e, , ,e, , , ,e,e, , , , ,e, , , , ],
 [ , ,e, , , ,e, ,e, ,e, ,e, ,e, ,e, , , ],
 [e, , , ,e, ,e, , , , , , , , , , , ,e, ],
 [e, , ,e, , , , , ,e, ,e, ,e, ,e, , , ,e],
 [ , , ,e, ,e, ,e, , , , , , , , , ,e, , ],
 [ ,e,e, ,e, , , ,e, ,e,e, ,e, ,e, ,e, , ],
 [ , ,e, , , ,e, , , , , , , , ,e,e, ,e, ],
 [ , , ,e, , , , ,e,e, , , , , , , , ,e, ],
 [e, , , , , , ,e, , , ,e,e, ,e, , , , , ],
 [ ,e,e, , ,e, , , , ,e, , , , , , ,e, , ],
 [ , , ,e,e, ,e, ,e, , , ,e,e, ,e, ,e, ,e],
 [e,e, , , , ,e, , , ,e, , , , , , , , , ],
 [ , , ,e, , , , , ,e, , ,e, ,e, ,e, ,e, ],
 [ , , , ,e, ,e, , , , , , , , , , , , , ],
 [e,e, , ,e,e, , ,e, , ,e, ,e, ,e, ,e, ,e],
 [e, ,e, ,e, , ,e,e,e, , ,e, , , ,e, , ,e],
 [ , , , ,e, , , , , ,e, , , ,e, , , , , ],
 [ , ,e, , , ,e, ,e, , , ,e, , , , ,e, , ],
 [ , , ,e, ,e, ,e, , ,e,e, , ,e,e, , ,e, ]]

```

Output (This output is hand-made, and might not be the optimal output):

```
[[e, , , , , , ,e, ,e, , , ,e, ,e, ,e, ,e],
 [ , ,e, , ,e, , ,n,e,e, , , ,n,e, , , , ],
 [ ,n,e, , ,n,e, ,e, ,e, ,e, ,e, ,e, ,n, ],
 [e, , , ,e, ,e, , , , , , , , , , , ,e, ],
 [e, , ,e, , , , , ,e, ,e, ,e, ,e, , , ,e],
 [ , ,n,e, ,e, ,e, , , ,n, , , , , ,e, , ],
 [ ,e,e, ,e, ,n, ,e, ,e,e, ,e, ,e,n,e, , ],
 [ , ,e, , , ,e, , , , , , , , ,e,e, ,e, ],
 [ , , ,e, , , , ,e,e, , , , , , , , ,e, ],
 [e, ,n, , , , ,e, , , ,e,e, ,e, , , , , ],
 [ ,e,e, , ,e,n, , ,n,e, , , ,n, , ,e,e, ],
 [ , , ,e,e, ,e, ,e, , , ,e,e, ,e, ,e, ,e],
 [e,e, , , , ,e, , , ,e, , , , , , , , , ],
 [ , , ,e, ,n, , , ,e, , ,e, ,e, ,e, ,e, ],
 [ ,n, , ,e, ,e, , , , , , , ,n, , , ,n, ],
 [e,e, , ,e,e, , ,e,n, ,e, ,e, ,e, ,e, ,e],
 [e, ,e, ,e, , ,e,e,e, , ,e, , , ,e, , ,e],
 [ , , , ,e, , , , , ,e, ,n, ,e, , ,n, , ],
 [ , ,e, ,n, ,e, ,e, , , ,e, ,n, , ,e, , ],
 [ , , ,e, ,e, ,e, ,n,e,e, , ,e,e, , ,e, ]]

```

Input:

```
[[e,e],
 [e,e]]

```

Output:

```
null

```

# Answer
> 4 votes
# Python 3, ~~558~~ ~~511~~ 509 bytes

```
from itertools import*
E=enumerate
L=len
def s(s):
 q=[(x,y)for y,r in E(s)for x,k in E(r)if k==w]
 for i in range(1,L(q)):
  for c in combinations(q,i):
   m=[l*1for l in s]
   for p in c:
    m[p[1]][p[0]]=n
    for y,r in E([list(r) for r in' xxx ,xxxxx,xxnxx,xxxxx, xxx '.split(',')]):
     for x,k in E(r):
      o=(p[0]-x+2,p[1]-y+2)
      if k==d and-1<o[0]<L(m[0])and-1<o[1]<L(m)and m[o[1]][o[0]]==e:
       m[p[1]-y+2][p[0]-x+2]=d
   if e not in ','.join([''.join(r)for r in m]):return(m)
print(s(m))

```

Try it online!

It's very loopy, but I don't know enough about Python to optimize it further. I did learn some things from ovs's answer, so that was fun.

The input (modified to make it easier to write test cases) expects ' ' or 'e', while the output uses ' ', 'n' for nullifier, and 'x' for a nullified emitter. The function takes the expected input that was described in the question.

I set the e, w, n, and d variables outside because they could be easily replaced with numbers and, if the input and output were modified to use numbers as well, it would print out the same thing. I used letters because they made it more readable while working on it.

Fun question, OP! Creeper World is great and it was a cool inspiration for the question :)

Edit: -47 bytes thanks to Erik the Outgolfer

# Answer
> 3 votes
# Python 2, ~~267~~ 263 bytes

```
from itertools import*
m=input()
E=enumerate
e=[(x,y)for y,a in E(m)for x,e in E(a)if e]
for n in count():
 for p in combinations(e,n):
	k=[l*1for l in m]
	for x,y in p:k[y][x]=2
	all(e+any(8>(y-Y)**2+(x-X)**2for X,Y in p)for y,a in E(m)for x,e in E(a))>0>exit(k)

```

Try it online!

`0` for emitter, `2` for nullifier and `1` for empty space.

# Answer
> 2 votes
# Wolfram Language (Mathematica), ~~173~~ 168 bytes

```
t=ToExpression@$ScriptInputString
P=Position
p=t~P~0
q=t~P~2
Print@ReplacePart[t,Thread[p->LinearProgramming[1&/@p,(xBoole[Norm[x-#]^2<6]&/@p)/@q,1&/@q,0,Integers]]]

```

Try it online!

Solves the largest test case in 1 second.

Full program. As a function, it's shorter, only 130 bytes.

Use `0` for , `1` for `n` and `2` for `e`.

This program can be used to convert from the input format in the challenge.

If there are no solution it will print error message `lpdim` like this, or `lpsnf` like this.

Version using `Outer` (although more readable) is 2 bytes longer, despite the short name of `Outer`: Try it online!

---

Explanation.

Note that this can be reduced to an integer linear programming problem.

Each `e` cell is fixed at 2, each empty cell is an integer variable, which can be either `0` (empty) or `1` (nullifier). The list of coordinates of variables are stored in variable `p`. (the `Position`s in `t` that is `0`)

The objective is to minimize the number of nullifier used, so the sum of those integer variables must be minimized. (`1&/@p`, a vector consists of all `1` and with length equal to `p`'s length, indicates the objective function)

The constraints are, for each emitter (`2`) (their positions are stored in `q`), there must be at least a nullifier in the range around it, or to be precise, have an Euclidean distance to it of at most \\$\sqrt 6\\$.

This is formulated with the matrix `m` = `(xBoole[Norm[x-#]^2<6]&/@p)/@q` (for each element in `q`, create a row with elements being `1` if the squared distance (`Norm`) to the corresponding coordinate in `p` is less than `6`) and the vector `b` = `1&/@q`.

After that `ReplacePart` and `Thread` "applies" the variable values to `t` and print it.

---
Tags: code-golf, array
---


title: Two Dimensional Waterflow problem

text:
# Question
Title: Two Dimensional Waterflow problem
The one dimensional twitter waterflow problem is this:

You are given an array that represents a hill in the sense that the ith entry is the height of the ith location of the hill. When it rains, water logs in the hills, and you need to figure out how much water would log.

For example, after raining, the array `2 5 3 4 3 2 5 5 3 4 2 2 2` looks like this,

and 9 units of water have accumulated.

---

The challenge is to solve the 2D version of this. To clarify, you will be given a 2D matrix of land heights, and you will have to output the total amount of rainwater it can collect. Water cannot flow out through diagonals, but only the four cardinal directions.

# Answer
# Python 3, ~~O(h × w × d)~~ 296 bytes, O(h × w × d')

```
def f(a):
 w=0;b=[len(a[0])*[0]];a=b+a+b;a=[[0]+x+[0]for x in a];b=sorted(set(sum(a,[])))
 for[i,j]in zip(b,b[1:]+[1+max(b)]):
  c=[[0,0]]
  while c:
   [x,y]=c.pop()
   if x<len(a)and x>=0and y<len(a[0])and y>=0and a[x][y]<=i:w+=i-a[x][y];a[x][y]=j;c+=[[x+1,y],[x,y+1],[x-1,y],[x,y-1]]
 return w

```

Try it online! Where d' represents the number of distinct values in the input. Edit: Saved 3 bytes thanks to @Mr.Xcoder.
> 0 votes

---
Tags: code-challenge, fastest-algorithm
---


title: Dennis numbers 2.0

text:
# Question
Title: Dennis numbers 2.0
PPCG user and elected mod, @Dennis just became the second ever user to earn over 100k rep!

This is a totally original idea, that I did not get from anybody else, but let's make a challenge based off of his user ID, `12012` as a tribute!

Looking at it, you'll notice that there are two distinct "sections" to his ID.

> 12

and

> 012

Both of these sections add up to a 3. That's a pretty interesting property.

Let's define a "Dennis 2.0 number" as any positive integer where every maximal subsequence of strictly increasing digits sums to the same number. For example,

```
123

```

is a Dennis 2.0 number because there is only one maximal sublist of strictly increasing digits, and it sums to 6. Additionally, 2,846,145 is also a Dennis 2.0 number because the three maximal sublists of increasing digits, namely

```
28
46
145

```

All sum to `10`. Additionally, numbers that just repeat the same digit *must* be Dennis 2.0 numbers because, for example, `777` can be broken down into

```
7
7
7

```

which *clearly* all sum to seven.

A number such as `42` is *not* a Dennis 2.0 number, since it is broken down into

```
4
2

```

which clearly do not sum to the same number.

# The challenge

You must write a program or function to determine if a given number is a Dennis 2.0 number or not. You can take input and output in any reasonable input format, e.g. as a string, as a number, from a file, funtion arguments/return, from STDIN/STDOUT, etc. and then return a truthy value if this number is a Dennis 2.0 number, and a falsy value if it is not. For reference, here is every Dennis 2.0 number up to 1,000:

```
1
2
3
4
5
6
7
8
9
11
12
13
14
15
16
17
18
19
22
23
24
25
26
27
28
29
33
34
35
36
37
38
39
44
45
46
47
48
49
55
56
57
58
59
66
67
68
69
77
78
79
88
89
99
101
111
123
124
125
126
127
128
129
134
135
136
137
138
139
145
146
147
148
149
156
157
158
159
167
168
169
178
179
189
202
222
234
235
236
237
238
239
245
246
247
248
249
256
257
258
259
267
268
269
278
279
289
303
312
333
345
346
347
348
349
356
357
358
359
367
368
369
378
379
389
404
413
444
456
457
458
459
467
468
469
478
479
489
505
514
523
555
567
568
569
578
579
589
606
615
624
666
678
679
689
707
716
725
734
777
789
808
817
826
835
888
909
918
927
936
945
999

```

Standard loopholes apply, and the shortest answer measured in bytes wins!

# Answer
> 15 votes
# Jelly, ~~13~~ 12 bytes

*1 byte thanks to @Dennis.*

```
DIṠ’0;œṗDS€E

```

Try it online!

### Explanation

```
DIṠ’0;œṗDS€E    Main link. Argument: N
D               Convert N to its digits.
 I              Find the differences between the elements.
  Ṡ             Find the sign of each difference. This yields 1 for locations where the
                list is strictly increasing and 0 or -1 elsewhere.
   ’            Decrement. This yields 0 for locations where the list is strictly
                increasing and -1 or -2 elsewhere.
    0;          Prepend a 0.
        D       Get another list of digits.
      œṗ        Split the list of digits at truthy positions, i.e. the -1s and -2s.
         S€     Sum each sublist.
           E    Check if all values are equal.

```

# Answer
> 16 votes
## JavaScript (ES6), ~~72~~ 70 bytes

Takes a string as input. Returns either false or a truthy value (which can be a number).

It's using a regular expression to transform an input string such as `"2846145"` into:

```
"(a=2+8)&&(a==4+6)&&(a==1+4+5)"

```

Then calls `eval()` on this expression.

```
let f =

n=>eval(n.replace(/./g,(v,i)=>(v>n[i-1]?'+':i?')&&(a==':'(a=')+v)+')')

console.log(f("101"));
console.log(f("102"));
console.log(f("777"));
console.log(f("2846145"));
```

# Answer
> 15 votes
# Python, 50 bytes

```
r='0'
for d in input():r=d+'=+'[r<d]*2+r
1/eval(r)

```

Expects `input()` to evaluate to a string, so the input needs surrounding quotes in Python 2. Output is via exit code, where **0** indicates success (truthy) and **1** indicates failure (falsy).

Test it on Ideone.

### How it works

We initialize **r** to the string **0** and iterate over all digits **d** in the input.

* If **d** is larger than the first digit of **r** (initially **0**, then equal to the previous value of **d**), `r<d` evaluates to *True* and `'=+'[r<d]*2` yields `++`.
* If **d** is smaller than the first digit of **r**, `'=+'[r<d]*2` yields `==`.
* If **d** is equal to the first digit of **r**, **r** will be longer than the singleton string **d**, so `'=+'[r<d]*2` yields once again `==`.

In all cases, the digit **d** and the two generated characters get prepended to **r**.

Once all input digits have been processed, `eval(r)` evaluates the generated expression.

* If the input consists of a single strictly increasing sequence of (positive) digits, the expression evaluates to their sum.

For example, the integer **12345** results in the expression `5++4++3++2++1++0`, which yields **15** when evaluated. Note that each second **+** is a *unary* plus, so it doesn't affect the result. Dividing **1** by **15** is valid (the result is not important); the program exits normally.
* If the input consists of two strictly increasing sequences of digits, the expression consists of a simple comparison.

For example, the integer **12012** results in the expression `2++1++0==2++1++0`, which yields *True* when evaluated since both terms have sum **3**. Dividing **1** by *True* (**1**) is valid (the result is not important); the program exits normally.

On the other hand, the integer **12366** results in the expression `6==6++3++2++1++0`, which yields *False* when evaluated since the terms have sums **6** and **12**. Dividing **1** by *False* (**0**) raises a *ZeroDivisionError*; the program exits with an error.
* If the input consists of three or more strictly increasing sequences of digits, the expression consists of a chained comparison, which returns *True* if and only if all involved comparisons return *True*.

For example, the integer **94536** results in the expression `6++3==5++4==9++0`, which yields *True* when evaluated since all terms have sum **9**. As before, the program exits normally.

On the other hand, the integer **17263** results in the expression `3==6++2==7++1++0`, which yields *False* when evaluated since the terms have sums **3**, **8**, and **8**. As before, the program exits with an error.

# Answer
> 8 votes
# Brachylog, 13 bytes

```
~c@e:{<+}a!#=

```

Try it online!

### Explanation

```
~c               Find a list of integers which when concatenated result in the Input
  @e             Split the integers into lists of digits
    :{<+}a       Each list of digit is stricly increasing, and compute its sum
          !      Discard all other choice points (prevents backtracking for smaller sublists)
           #=    All sums must be equal

```

`~c` will unify with the biggest sublists first.

# Answer
> 6 votes
## PowerShell v2+, ~~100~~ ~~64~~ 61 bytes

```
-join([char[]]$args[0]|%{("+$_","-eq$_")[$_-le$i];$i=$_})|iex

```

A literal one-liner, as this is all one pipeline. Takes input as a string `$args[0]`. Loops through it as a `char`-array, each iteration placing either the current element with a `+` or `-eq` in front of it onto the pipeline based on whether the current value is `-l`ess-than-or-`e`qual to the previous value `$i`. Those strings are `-join`ed together and piped to `iex` (short for `Invoke-Expression` and similar to `eval`. For example, for input `2846145` this will be evaluated as `+2+8-eq4+6-eq1+4+5`, which is `True`.

That Boolean is left on the pipeline, and `True`/`False` is implicitly written at program completion.

*NB - for single-digit input, the resulting digit is left on the pipeline, which is a truthy value in PowerShell.*

### Examples

```
PS C:\Tools\Scripts\golfing> 2846145,681,777,12366,2|%{"$_ -> "+(.\dennis-number-20.ps1 "$_")}
2846145 -> True
681 -> False
777 -> True
12366 -> False
2 -> 2

```

# Answer
> 6 votes
## Pyke, 18 bytes

```
mb$1m>0R+fMbms}lt!

```

Try it here!

```
mb                 -         map(int, input)
  $                -        delta(^)
   1m>             -       map(^, 1>i)
      0R+          -      [0]+^
         f         -     input.split_at(^)
          Mb       -    deep_map(int, ^)
            ms     -   map(sum, ^)
              }    -  uniquify(^)
               lt! - len(^) == 1

```

# Answer
> 6 votes
# GNU sed 217 or 115

Both include +1 for -r

**217:**

```
s/./&,/g;s/^/,/g;:;s,0,,;s,2,11,;s,3,21,;s,4,31,;s,5,41,;s,6,51,
s,7,61,;s,8,71,;s,9,81,;t;s/(,1*)(1*)\1,/\1\2X\1,/;t;s/,//g
s,1X1(1*),X\1a,;t;/^1.*X/c0
/Xa*$/s,a*$,,;y,a,1,;/1X1/b;/1X|X1/c0
c1

```

Takes input in normal decimal

Try it online!

---

**115:**

```
s/^|$/,/g;:;s/(,1*)(1*)\1,/\1\2X\1,/;t;s/,//g
s,1X1(1*),X\1a,;t;/^1.*X/c0
/Xa*$/s,a*$,,;y,a,1,;/1X1/b;/1X|X1/c0
c1

```

Takes input as a comma separated list of the numbers digits in unary. e.g. `123` would be `1,11,111`

Try it online!

# Answer
> 5 votes
# JavaScript (ES6), ~~66~~ ~~65~~ 63 bytes

*Saved 2 bytes thanks to @edc65*

```
x=>[...x,p=t=z=0].every(c=>p>=(t+=+p,p=c)?(z?z==t:z=t)+(t=0):1)

```

Takes input as a string. Old version (only works in Firefox 30+):

```
x=>[for(c of(p=t=0,x))if(p>=(t+=+p,p=c))t+(t=0)].every(q=>q==+p+t)

```

# Answer
> 5 votes
## Perl, 38 + 3 (`-p`) = 41 bytes

*-9 bytes thanks to @Ton Hospel !*

```
s%.%2x$&.(~$&le~$')%eg;$_=/^(2+1)\1*$/

```

Since there is a `$'`, the code needs to be in a file to run. So `-p` counts for 3 bytes. Outputs 1 if the number is a Dennis 2.0 number, or an empty string otherwise :

```
$ cat dennis_numbers.pl
s%.%2x$&.(~$&le~$')%eg;$_=/^(2+1)\1*$/
$ perl -p dennis_numbers.pl <<< "1
10
12315
12314"

```

# Answer
> 3 votes
# Mathematica, 38 bytes

```
Equal@@Tr/@IntegerDigits@#~Split~Less&

```

Anonymous function. Takes a number as input, and returns `True` or `False` as output.

# Answer
> 3 votes
# Brachylog 2, 10 bytes, language postdates challenge

```
ẹ~c<₁ᵐ!+ᵐ=

```

Try it online!

This is basically the same algorithm as @Fatalize's answer (which I didn't see until after I'd written this), but rearranged somewhat to make it golfier under Brachylog 2's syntax.

It's a full program, returning `false.` if it isn't a Dennis 2.0 number, or `true` if it is.

## Explanation

```
ẹ~c<₁ᵐ!+ᵐ=
ẹ           Interpret the input number as a list of digits
      !     Find the first (in default order)
 ~c           partition of the digits
   <₁ᵐ        such that each is in strictly increasing order
         =  Assert that the following are all equal:
       +ᵐ     the sums of each partition

```

As usual for a Brachylog full program, if all the assertions can be met simultaneously, we get a truthy return, otherwise falsey. The default order for `~c` is to sort partitions with fewer, longer elements first, and in Prolog (thus Brachylog), the default order's defined by the first predicate in the program (using the second as a tiebreak, and so on; here, `~c` dominates, because  is deterministic and thus has nothing to order).

# Answer
> 2 votes
# MATL, ~~24~~ ~~23~~ ~~20~~ ~~18~~ 16 bytes

```
Tjdl<vYsG!UlXQ&=

```

Returns a truthy of falsey matrix

**Try it Online!**

Also, congrats @Dennis!

**Explanation**

```
T       % Push a literal TRUE to the stack
        %   STACK: {1}
j       % Explicitly grab the input as a string
        %   STACK: {1, '2846145'}
d       % Compute the difference between successive ASCII codes
        %   STACK: {1, [6 -4 2 -5 3 1]}
l<      % Find where that difference is less than 1
        %   STACK: {1, [0 1 0 1 0 0]}
v       % Prepend the TRUE value we pushed previously
        %   STACK: {[1 0 1 0 1 0 0]}
Ys      % Compute the cumulative sum. This assigns a unique integer label to
        % each set of increasing numbers
        %   STACK: {[1 1 2 2 3 3 3]}
G!U     % Grab the input as numeric digits
        %   STACK: {[1 1 2 2 3 3 3], [2 8 4 6 1 4 5]}
lXQ     % Compute the sum of each group of increasing digits
        %   STACK: {[10 10 10]}
&=      % Computes element-wise equality (automatically broadcasts). A
        % truthy value in MATL is a matrix of all ones which is only the case
        % when all elements are equal:
        %   STACK: {[1 1 1
        %            1 1 1
        %            1 1 1]}
        % Implicitly display the result

```

# Answer
> 2 votes
## PHP, ~~108~~ ~~105~~ 92 bytes

```
$p=-1;foreach(str_split("$argv[1].")as$d)$p>=$d?$r&&$s-$r?die(1):($r=$s)&$s=$p=$d:$s+=$p=$d;

```

takes input from argument, exits with `0` for Dennis-2.0 number, with `1` else.

**breakdown**

```
$p=-1;                              // init $p(revious digit) to -1
foreach(str_split("$argv[1].")as$d) // loop $d(igit) through input characters
                                    // (plus a dot, to catch the final sum)
    $p>=$d                              // if not ascending:
        ?$r                             // do we have a sum remembered
        &&$s-$r                         // and does it differ from the current sum?
                ?die(1)                     // then exit with failure
                :($r=$s)&$s=$p=$d           // remember sum, set sum to digit, remember digit
        :$s+=$p=$d                      // ascending: increase sum, remember digit
    ;
//

```

# Answer
> 2 votes
# 05AB1E, 18 bytes

```
SD¥X‹X¸«DgL*ê¥£OÙg

```

**Explanation**

`N = 12012` used as example.

```
                    # implicit input N = 12012
S                   # split input number to list of digits
                    # STACK: [1,2,0,1,2]
 D                  # duplicate
                    # STACK: [1,2,0,1,2], [1,2,0,1,2]
  ¥                 # reduce by subtraction
                    # STACK: [1,2,0,1,2], [1,-2,1,1]
   X‹               # is less than 1
                    # STACK: [1,2,0,1,2], [0,1,0,0]
     X¸«            # append 1
                    # STACK: [1,2,0,1,2], [0,1,0,0,1]
        DgL*        # multiply by index (1-indexed)
                    # STACK: [1,2,0,1,2], [0,2,0,0,5]
            ê       # sorted unique
                    # STACK: [1,2,0,1,2], [0,2,5]
             ¥      # reduce by subtraction
                    # STACK: [1,2,0,1,2], [2,3]
              £     # split into chunks
                    # STACK: [[1,2],[0,1,2]]
               O    # sum each
                    # STACK: [3,3]
                Ù   # unique
                    # STACK: [3]
                 g  # length, 1 is true in 05AB1E
                    # STACK: 1

```

Try it online!

# Answer
> 2 votes
# Ruby 2.3, 56 bytes

```
p !gets.chars.chunk_while(&:<).map{|a|eval a*?+}.uniq[1]

```

Almost certainly not the golfiest way to do this, but it shows off some nice language features.

(Not newline-tolerant, so run like `ruby dennis2.rb <<< '12012'`)

# Answer
> 1 votes
# PHP, 144 bytes

```
<?php preg_match_all("/0?1?2?3?4?5?6?7?8?9?/",$argv[1],$n);foreach($n[0]as$i)if(strlen($i)&&($a=array_sum(str_split($i)))!=$s=$s??$a)die;echo 1;

```

I'm sure there's a much cleverer (and shorter) way to do this but it will do for now.

# Answer
> 1 votes
# JavaScript (ES6), 58

```
s=>![...s,z=x=p=0].some(c=>[c>p?0:z-=(x=x||z),z-=p=c][0])

```

Applying my rarely useful tip https://codegolf.stackexchange.com/a/49967/21348

It scans the string char by char identifying run of ascending chars, at the end of each rum it checks if the sum is always the same

* c : current char
* p : previous char
* z : running sum, at the end of a run will be compared to ...
* x : sum to compare against, at first run is simply made equal to z

**Test**

```
f=
s=>![...s,z=x=p=0].some(c=>[c>p?0:z-=(x=x||z),z-=p=c][0])

function run()
{
  var i=I.value
  O.textContent = i + ' -> ' + f(i)
}

run()

test=`1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 22 23 24 25 26 27 28 29 33 34 35 36 37 38 39 44 45 46 47 48 49 55 56 57 58 59 66 67 68 69 77 78 79 88 89 99 101 111 123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189 202 222 234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267 268 269 278 279 289 303 312 333 345 346 347 348 349 356 357 358 359 367 368 369 378 379 389 404 413 444 456 457 458 459 467 468 469 478 479 489 505 514 523 555 567 568 569 578 579 589 606 615 624 666 678 679 689 707 716 725 734 777 789 808 817 826 835 888 909 918 927 936 945 999`.split` `

numerr=0
for(i=1; i<1000; i++)
{
  v = i + '';
  r = f(v);
  ok = r == (test.indexOf(v) >= 0)
  if (!ok) console.log('Error',++numerr, v)
}
if(!numerr) console.log('All test 1..999 ok')
```

```
<input id=I value=612324 type=number oninput='run()'>
<pre id=O>
```

# Answer
> 1 votes
## Python 2, 69 bytes

Takes input as a string.

```
lambda I:len(set(eval(reduce(lambda x,y:x+',+'[y>x[-1]]+y,I+' '))))<2

```

Explanation:

ex `1201212012`

Converts to list of sums:

`1+2,0+1+2,1+2,0+1+2,`

Evals and converts to set.

`set([3])`

If the length of the set is 1, all sums are the same.

# Answer
> 1 votes
# Pyth, 20 bytes

Two versions

```
!t{sMcJjQThMx1<R0.+J
LS{b!t{sMhyI#I#./jQT

```

Try the first one online!

Try the second one online!

# Answer
> 0 votes
# Ruby, ~~117~~ ~~105~~ 85 bytes

```
# original (117):
j,k=0,?0;"#{i}".chars.group_by{|n|n>k||j=j+1;k=n;j}.values.map{|a|a.map(&:to_i).reduce(&:+)}.reduce{|m,n|n==m ?m:nil}

# inspired by PHP regexp approach (105):
"#{i}".scan(/0?1?2?3?4?5?6?7?8?9?/).map{|a|a.chars.map(&:to_i).reduce(&:+)}.reduce{|m,n|!n||n==m ?m:nil}

# some number comparison simplification (85):
!"#{i}".scan(/0?1?2?3?4?5?6?7?8?9?/).map{|a|a.chars.map(&:to_i).reduce(&:+)}.uniq[1]

```

This would return the integer of this dennis number or `nil` if not a dennis number. All integers will be considered true in ruby as well `nil` is considered false. `i` is the integer that is being check.

Third version actually returns `true` and `false`.

P.S. tested to return 172 integers from 1 to 1000 as in the answer.

# Answer
> 0 votes
# APL, 23 bytes

```
{1=≢∪+/↑N⊂⍨1,2>/N←⍎¨⍕⍵}

```

Explanation:

* `N←⍎¨⍕⍵`: get the individual digits in the input, store in `N`
* `N⊂⍨1,2>/N`: find the sublists of strictly increasing numbers in `N`
* `+/↑`: sum each sublist
* `1=≢∪`: see if the resulting list has only one unique element

# Answer
> 0 votes
# Add++, 109 bytes

```
D,g,@@#,BF1_B
D,k,@@#,bR$d@$!Q@BFB
D,f,@,BDdVÑ_€?1€_0b]$+€?dbLRBcB*BZB]GbL1+b]+qG€gd€bLÑ_0b]$+BcB]£k€¦+Ñ=1$ª=

```

Try it online!

## How it works

We define our 3 functions, \\$f\\$, \\$g\\$ and \\$k\\$. \\$f\\$ is the main function, which transforms the input to the correct output.

### \\$f(x)\\$

First, we convert the input \\$x\\$ into a list of digits, then take the forward increments. Next, we take the sign of each increment. For increasing subsequences, this yields a subsequence of \\$1\\$, for equal subsequences, such as \\$\[4, 4, 4\]\\$, this yields \\$0\\$s and for decreasing sections, \\$-1\\$ is returned. We then take the complement of each of these signs, to turn \\$1\\$ into a falsey value, and everything else into a truthy value. Next, \\$0\\$ is prepended to this array, and we take the sign of each element again. This yields an array, \\$A\\$, of \\$0\\$ and \\$1\\$, with the first element always being \\$0\\$.

We then yield the range \\$\[1, 2, ... length(A)\]\\$ and remove the elements that correspond to \\$0\\$ in \\$A\\$. This leaves us with a second array, \\$A'\\$. We then push the number of digits in the input, add one and append this number to \\$A'\\$. We then deduplicate \\$A'\\$, to yield a new array, \\$A''\\$.

Next, we use the \\$g\\$ helper function. As \\$g\\$ is dyadic (takes 2 arguments), it behaves slightly differently when paired with the *each* operator, . Dyadic functions pop a value from the stack and bind that value as their right argument to create a partial monadic function. This partial function is then mapped over each element in the argument. Here, the bound right argument is the digits of the input and the partial function is mapped over \\$A''\\$.

### \\$g(x, y)\\$

Let's take a look at just one iteration of \\$g(x, y)\\$ where \\$x := \[1, 2, 0, 1, 2\]\\$ and \\$y = 3\\$. Note that \\$3\\$ is the first index in \\$A''\\$ where the signs from \\$A\\$ corresponded with \\$1\\$, rather than \\$0\\$. In fact, for \\$x = 12012\\$, we can see that \\$A'' = \[3, 6\]\\$. \\$3\\$ is the only non-zero index in \\$A\\$, and \\$6\\$ is the length of \\$x\\$ plus one.

So, for \\$g(\[1, 2, 0, 1, 2\], 3)\\$ the following happens: First, we swap the two arguments so that the stack has the digits below the index. We then flatten the array and decrement the index. So far, the stack looks like `[1 2 0 1 2 2]`. We then perform the *head* command. We pop the index from the top f the stack and take that many characters from the stack, starting at the bottom. This yields \\$\[1, 2\]\\$, which is then returned by \\$g\\$.

So, \\$g(x, y)\\$ is mapped over each element \\$y \in A''\\$, which returns a series of prefixes of the input of various increasing lengths. This part could get slightly confusing, so we'll work through it with the example input of \\$x := 12012\\$. After the mapping of \\$g\\$, the stack currently looks like

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

```

We then push an array containing the length of each array in the top element, or in this instance, the array \\$\[2, 5\]\\$. This is the same as \\$A'' - 1\\$, if the \\$-\\$ operator maps, but it takes more bytes to use this relationship. Next, the forward differences of the lengths is taken, and \\$0\\$ is prepended, yielding, in this example, \\$\[0, 3\]\\$. This new array is then zipped with the results from \\$g\\$ to create \\$B\\$ and the *starmap* operator is run over each pair.

### \\$k(x, n)\\$

The *starmap* operator uses the function \\$k\\$ as its argument, and works by taking a dyadic function and a nested array. The array must consist of pairs, such as \\$\[\[1, 2\], \[3, 4\], \[5, 6\]\]\\$, and the dyadic function is mapped over each pair, with each element of the pairs being the left and right arguments respectively.

Here, our example nested array is \\$\[\[\[1, 2\], 0\], \[\[1, 2, 0, 1, 2\], 3\]\]\\$ and our function is \\$k\\$. We'll focus simply on \\$k(\[1, 2, 0, 1, 2\], 3)\\$ for now.

\\$k(x, n)\\$ starts, similar to \\$g\\$, by swapping the two arguments, so that the array is the top of the stack. We then reverse the array and swap the arguments back. Now, \\$n = 0\\$, we want to leave the array unchanged, so we duplicate the integer and rotate the top three arguments, so that the stack has the format of \\$\[n, x, n\]\\$. Next, we return the array if \\$n = 0\\$. Otherwise, the top element is discarded, and we arrange the stack back to how it was i.e. with the reversed array at the bottom and the integer at the top, or in our example: \\$\[\[2, 1, 0, 1, 2\], 3\]\\$. We then flatten the stack, and take the first \\$n\\$ elements of \\$x\\$. These elements are then returned and replace \\$x\\$ in \\$B\\$.

For our input, this returns \\$\[0, 1, 2\]\\$. (Strictly speaking, it returns\\$\[2, 1, 0\]\\$, but order doesn't matter for the rest of the program).

After \\$k(x, n)\\$ is mapped over each pair \\$(x, n) \in B\\$, we take the sum of each pair, then check that each element is equal, by asserting that each neighbouring pair are equal, and then asserting that each of those equality tests result in \\$1\\$ (a truthy value). Finally, this result is returned.

---
Tags: code-golf, math, sequence, arithmetic, decision-problem
---


title: Text to Brain-Flak

text:
# Question
Title: Text to Brain-Flak
Your challenge is to turn input text to brain-flak code that will output the text.

# Tutorial taken from here with permission here

Brain-Flak has two stacks, known as 'left' and 'right'. The active stack starts at left. If an empty stack is popped, it will return 0. That's it. No other variables. When the program starts, each command line argument is pushed on to the active stack.

The only valid characters in a Brain-Flak program are `()[]{}<>`, and they must always be balanced. There are two types of functions: *Nilads* and *Monads*. A *nilad* is a function that takes 0 arguments. Here are all of the nilads:

* `()` Evaluates to one.
* `[]` Evaluates to the height of the current stack.
* `{}` Pop the active stack. Evaluates to the popped value.
* `<>` Toggle the active stack. Evaluates to zero.

These are concatenated together when they are evaluated. So if we had a '3' on top of the active stack, this snippet:

```
()(){}

```

would evaluate to `1 + 1 + active.pop()` which would evaluate to 5.

The monads take one argument, a chunk of Brain-Flak code. Here are all of the monads:

* `(n)` Push 'n' on the active stack.
* `[n]` Evaluates to negative 'n'
* `{foo}` While zero is not on the top of the stack, do foo.
* `<foo>` Execute foo, but evaluate it as 0.

These functions will also return the value inside of them, so

```
(()()())

```

Will push 3 but

```
((()()()))

```

Will push 3 *twice*.

The `{}` will evaluate to the sum of all runs. So if we had '3' and '4' on the top of the stack:

```
{{}}

```

would evaluate as 7.

When the program is done executing, each value left on the active stack is printed, with a newline between. Values on the other stack are ignored.

# Rules

* You may assume that the Brain-Flak is being run with ascii out. (`-A`)
* The brain-flak code must NOT require input
* All standard rules apply
* The code must run within 1 minute for any input up to 1024 bytes on TIO. (If no TIO output is available supply an interpreter and I will run it on my machine (my machine should be able to come close to TIO)).
* You must support arbitrary length input.
* You may take input from a file.
* Optimization for test cases is not allowed
* Deterministic output is required
* Programs don't need to be stack clean

## Test cases (try your code on these, actual scoring texts will be released in 1-2 weeks after challenge is posted)

```
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

The meaning of brain-flak is to flak your brain with pain.

`1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?

To be, or not to be, that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles
And by opposing end them. To die-to sleep,
No more; and by a sleep to say we die

<your brain-flak code here>

The fitness pacer test is a multi stage test. Avacado Avacado Avacadad Avacadad carrot.bat carrot.jar carrot.carrot Quack Quack Quack Quack Quack Quack Quack Quack Quack downgoat doawngoat down down gaot

This challenge came from a online program that turned text into brain-fuck. However brain-fuck has limitations and it is not nearly as cool as brain-flak. I really am looking forward to cool programs :) I am glad you took the time to read this and look forward to seeing your answer.

```

# Winning

To win you must give the total length of the brain-flak code given by each of the test cases which will be released 1-2 weeks after the post date. The shortest total length wins.

# NOTE!!!!!!:

This is not , length of your code will not effect your final score in any way. Making clean readable code is appreciated. Thanks!

# Test cases

here

# Answer
# Brain-Flak, 130 bytes

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

```

Try it online!

# Output for `<your brain-flak code here>`: 5045 bytes

```
(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())

```

Try it online!
> 14 votes

# Answer
# Python 3, 17744 bytes

Edit: I've added a couple of options to help golf in stack safe situations.

```
import sys
sys.setrecursionlimit(1000000)
import time

def copy(n, code):
	if n == 1: return code
	for x in range(2, n):
		if n%x == 0: return '('*(x-1) + copy(n//x, code) + ')'*(x-1) + '{}'*(x-1)
	return '('*(n-1) + code + ')'*(n-1) + '{}'*(n-1)

letterCache = {}
def letterGen(n, stackLen, prev=0, enclosed=0):
	if (n, stackLen, prev, enclosed) in letterCache: return letterCache[(n, stackLen, prev, enclosed)]
	if n == 0: return ''
	if n == 1: return '()'
	if n == stackLen: return '[]'
	f = []
	if n < 0:
		f.append('[%s]'%letterGen(-n, stackLen, prev, enclosed))
	else:
		if prev != 0:
			diff = n-prev
			#Saves ~200 bytes but 20x longer
			#for x in range(min(diff, 0)-stackLen, max(diff, 0)+stackLen+1):
				#f.append(letterGen(x, stackLen - enclosed) + 's' + letterGen(diff - x, stackLen))

			f.append('s' + letterGen(diff, stackLen))
			f.append(letterGen(diff, stackLen - enclosed) + 's')
		x = 2
		while x*x < n:
			f.append(copy(x, letterGen(n//x, stackLen, prev, enclosed)) + letterGen(n%x, stackLen, prev, enclosed))
			x += 1
		f.append(letterGen(n-1, stackLen, prev, enclosed)+'()')
		if abs(n-stackLen) < n and stackLen > 1: f.append(letterGen(n-stackLen, stackLen, prev, enclosed) + '[]')
	letterCache[(n, stackLen, prev, enclosed)] = min(f, key=len)
	return letterCache[(n, stackLen, prev, enclosed)]

def s2BrainFlak(c, checkReverse = True):
	g = []
	c = c[::-1]
	stack = []
	out = []
	enclosed = 0

	if checkReverse:
		g.append(''.join(out) + s2BrainFlak(c, False) + '{({}<>)<>}<>')
		#for x in range(1,11): g.append(s2BrainFlak(list(c)+[chr(0)]*x, False) + '{({}<>)<>}<>')
	#if c and c[0] == chr(0):
	#	out.append('<>')
	#	while c[0] == chr(0):
	#		stack.append(0)
	#		out[0] = '(' + out[0] + ')'
	#		c = c[1:]

	for letter in range(len(c)):
		char = ord(c[letter])
		x = '(%s)'%letterGen(char, len(stack), stack[-1] if stack else 0, enclosed)

		if 's' in x:
			out[-1] = x.replace('s', out[-1])
			enclosed += 1
		else:
			out.append(x)
			enclosed = 1
		if checkReverse and c[letter+1:]:
			g.append(''.join(out) + '<>' + s2BrainFlak(c[letter+1:], False) + '{({}<>)<>}<>')
			m = min(list(map(ord, c[letter+1:])))-1
			#for i in range(1,m): g.append(''.join(out) + '<>' + s2BrainFlak(list(map(lambda x: chr(ord(x)-i), c[letter+1:])), False) + "{({}%s<>)<>}<>"%letterGen(i, 0))
			g.append(''.join(out) + '<>' + s2BrainFlak(list(map(lambda x: chr(ord(x)-m), c[letter+1:])), False) + "{({}%s<>)<>}<>"%letterGen(m, 0))
			#for x in range(1,11): g.append(''.join(out) + s2BrainFlak(list(c)+[chr(0)]*x, False) + '{({}<>)<>}<>')
		stack.append(char)
	g.append(''.join(out))
	return min(g, key=len)

```

Try it online!

A ~~simple~~ recursive solution which I will continue to improve further. This does *very* well with smaller inputs, but loses out to MegaTom's Ruby answer for longer inputs.

Notes:

* This needs a clean stack to operate, otherwise the improvements with `[]` become useless (though they can be disabled by commenting out a couple of lines, and they only improve it by ~~about 100 bytes~~ quite a bit).
* ~~Since this is a recursive algorithm, it will take longer for chars with large values. For example, the character ÿ (value 255) takes 9 seconds to evaluate, where every test case at once takes 1.6 seconds.~~ Cache implemented!
* Idea of checking the reverse shamelessly borrowed from HyperNeutrino's answer, saving 800 bytes from the total.
* I changed the total from all test cases at once to the total of each test case. This saves some bytes by adding more uses for the stack length operator (`[]`)
* ~200 bytes from choosing the minimum of prepending the difference between characters, or appending them (again, this saves bytes through the stack length operator)
* Implemented a cache (which caches values based on stack length), which allowed me to check more possible avenues without going over the time limit. This saved 1500 bytes from the total.
    + Also, I switched the em dash in the Shakespeare test case to a normal `-`. This cut out a few bytes, and a *lot* of time given the value of that em dash was 8212 :o .
* Cut out 1200 bytes from the longer test cases by cutting them into slices and checking whether it was shorter to switch to the other stack, construct it in reverse, and push it back to the first stack again. Next up, even more slicing, and saving time by optimising the minimum slicing range.
* Combined the number generating function with the checking for efficiencies with the previous character part into one recursive function. There's a couple of sections in here that save some bytes, but extend the runtime of the program a bit beyond the the one minute limit.
    + Uncommenting those parts can cut it down to 11394 bytes... but takes about 16 minutes.

Example outputs:

### `<your brain-flak code here>` (312 bytes):

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

```

Try it online!

### `Hello, World!` (142 bytes \[Note: The ~~current~~ previous best was 148 bytes, and is now 136 bytes\]):

```
((()(((((((((()()()()){}){}){}()))){}{}())([][]){})[][])[[]])[((()[]){}){}])([()[]](((()(()[]([][]((()[][]){}[]))){}[])[()()()])))(([][][]){})

```

Try it online!
> 7 votes

# Answer
# Ruby, 17398 bytes for all (new) test cases

```
# cache for holding shortest push results
$p_cache = {}

# Get code to push a number "a" to the stack,
#  given top of stack "b" and stack height "h"
def push a,b=nil,h=0
  return $p_cache[[a,b,h]] if $p_cache[[a,b,h]]
  arr = []
  if b
    arr.push "(({})#{add(a-b,h)})"
  end
  arr.push "(#{add a,h}  )"
  arr.push "([]#{add a-h,h}  )"
  i=2
  while i*i<=a && i<4
    arr.push "#{'('*(i-1)}#{push a/i,b,h}#{')'*(i-2)+'{}'*(i-1)}#{add(a%i,h)})"
    i+=1
  end
  $p_cache[[a,b,h]] = arr.min_by(&:length)
end

$cache = {}

# Get code to add a number "n" to the 3rd stack
#  given stack height "h"

def add n,h=0
  return $cache[[n,h]] if $cache[[n,h]]
  arr = []
  if n > 0
    arr.push("()"*n)
  elsif n == 0
    return ""
  else
    if h > 0
      1.upto(-n/h){|i|
        arr.push "[#{'[]'*i}]#{add(h*i+n,h)}"
      }
    end
    arr.push "[#{add(-n,h)}]"
    return ($cache[[n,h]] = arr.min_by &:length)
  end

  if h > 0
    if n > h
      arr.push "[]#{add n-h,h}"
    else
      arr.push "[]#{add n-h}"
    end
  end

  i=2
  while i*i<=n && i<4
    arr.push "#{'('*(i-1)}#{add n/i,h}#{')'*(i-1)+'{}'*(i-1)}#{add(n%i,h)}"
    x=n-h-i+1
    if x > 0
      arr.push "#{'('*(i-1)}#{add x/i,h}#{')'*(i-1)}[]#{'{}'*(i-1)}#{add(x%i)}"
    end
    i+=1
  end
  $cache[[n,h]] = arr.min_by &:length
end

def push_arr(arr)
  i=0
  code = push(arr[0]) + "\n" +
  arr.each_cons(2).map{|r|
    i+=1;push r[1],r[0],i
  }.join(?\n)

  while code =~ /^\((.*)\)\n(\(*)\{\}/
    code.gsub!(/^\((.*)\)\n(\(*)\{\}/, '\2\1')
  end

  code.split(/\n| /).join
end

# push a string to the stack
def push_string(text)
  push_arr text.chars.map(&:ord)
end

$str_cache = {}
# Push a string in reverse order
def push_string_r(text)
  return $str_cache[text] if $str_cache[text]
  a = [push_string(text)+"{({}<>)<>}<>", push_string(text.reverse)]

  min = text.bytes.min-1
  a.push push_arr(text.bytes.map{|x|x-min}) + "{({}<>#{add min})<>}<>"

  # Try cutting it into bits
  3.upto([text.length/20, 10].min)do|x|
    spl = x*9
    a.push push_string_r(text[spl..-1]) + "<>" +
      push_string(text[0...spl]) + "{({}<>)<>}<>"
    spl = x*10
    a.push push_string_r(text[spl..-1]) + "<>" +
      push_string(text[0...spl]) + "{({}<>)<>}<>"
  end

  a.map!{|code|code.gsub("<><>","")}

  $str_cache[text] = a.min_by &:length
end

```

Try it online!

---

## `<your brain-flak code here>`, ~~362~~ 358 bytes

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

```

Try it online!
> 5 votes

# Answer
# Python 3, 16222 bytes

```
cache = {}

def generate_number(num, height, level = 0, output = False): # Idea to use Stack Height inspired by Jo King
	if output: print(" " * level + str(num) + " " + str(height))
	if (num, height) in cache: return cache[(num, height)]
	if num == 0: return ""
	if num < 0: return "[" + generate_number(-num, height, level + 1, output) + "]"
	if num == height: return "[]"
	value = min((["[]" + generate_number(num - height, height, level + 1, output)] if height > num * 2 and abs(num - height) < num else []) + ["()" + generate_number(num - 1, height, level + 1, output)] + ["(%s)%s{}" % (generate_number(num // i, height, level + 1, output), "({})" * (i - 2)) for i in range(2, num) if num % i == 0], key = len)
	cache[(num, height)] = value
	return value

generate_number(256, 0, 0, False)

def generate_string(array):
	string = ""
	last = 0
	for height, num in enumerate(array):
		string = min("(" + string + generate_number(num - last, height) + ")", "<" + string + ">" + "(" + generate_number(num, height) + ")", key = len)
		last = num
	return string

a = lambda s: generate_string(list(map(ord, s)))

i = sys.stdin.read()
j = i[::-1]

print(min(a(j), a(i) + "{({}<>)<>}<>", key = len))

```

Try it online!

First below 1000 for `<your brain-flak code here>` :D

# Brain-Flak, 448 bytes

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

```

Try it online!

(originally 827 for `<your brain-flak code here>`)
> 4 votes

# Answer
# 05AB1E, too many bytes (My first BF anything)

```
ÇεDÑDg;<èUX÷VX"()"×"(ÿ)"YX-"()"×«"(ÿ)"}»"{({}<>)({<({}[()])><>({})<>}{}<><{}><>)<>}<>"«

```

Try it online!

---

Extremely basic attempt at golfing using a the premade "multiplication" Brain-flak code. All this does is finds the smallest-sum divisor pair for each ASCII code point, then pushes both of those divisors pairs as numbers. The Brainflak code `({}<>)({<({}[()])><>({})<>}{}<><{}>)` is then appended and executed in a loop until all values are on the alternate stack.

---

List of people I'm thanking:

* DJMcMayhem for pointing out `(()())(()()())` = `((()())())` (`-252 bytes`)
* DJMcMayhem for showing me how loops should work (`-927 bytes`).

---

Example golf of `<your brain-flak code here>` at ~~3470~~ ~~3218~~ 2291 bytes:

# Brain-Flak, 2291 bytes

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

```

Try it online!

---

Each row represents one character being golfed, this beats the basic solution I posted by 60%, and going in knowing literally nothing about Brainflak I feel this is a good baseline of what not to do. I'll score the answer in a little while, in the middle of something else and I'm sure I can improve on this. (I'm including the newlines in the byte-count because I don't expect this to win).
> 3 votes

# Answer
# Brain-Flak

```
For each character (main loop)
(([])<{({}[()]<

Get the difference between the top two characters
(({}<>)<>[({})]<><({}<>)>)

Push an open paren on the other stack
<>(((((()()){}()){}){}){})

Retrieve difference
(<>{}<>)

Greater than zero
([(({})[(())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

If
{{}

While non-zero
({

Add value if not 1
<(({})[()])>{()(<{}>)}{}

<

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

Hold the div
({}<

Push the mod part
{({}[()]<
((((((()()){}()){}){}){})())
>)}{}

Put div down
>)

Open paren if div non-zero
(({}))
{(<({}<{}
(((((()()){}()){}){}){})
>)>)}{}

Less than 4
([([({})[()()()()](())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

If
{{}

Make that many 1s
{({}[()]<
((((((()()){}()){}){}){})())
>)}{}

End if
((<()>))}{}

End loop puting number of times run on the stack
>}{})

For each close push and pop
{({}[()]<
((((()()()()()){}){}){}())(((((((()()()()()){}){}){}())){}{})()())
>)}{}

End if
((<()>))}{}

Less than zero
([([({})(())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

If
{{}

([{}]<

Push open bracket
((((((()()){}()){}()){}){}()){}())

>)

While non-zero
({

Add value if not 1
<(({})[()])>{()(<{}>)}{}

<

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

Hold the div
({}<

Push the mod part
{({}[()]<
((((((()()){}()){}){}){})())
>)}{}

Put div down
>)

Open paren if div non-zero
(({}))
{(<({}<{}
(((((()()){}()){}){}){})
>)>)}{}

Less than 4
([([({})[()()()()](())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

If
{{}

Make that many 1s
{({}[()]<
((((((()()){}()){}){}){})())
>)}{}

End if
((<()>))}{}

End loop puting number of times run on the stack
>}{})

For each close push and pop
{({}[()]<
((((()()()()()){}){}){}())(((((((()()()()()){}){}){}())){}{})()())
>)}{}

Push close bracket
((((((()()){}()){}()){}()){}){}())

Endif
((<()>))}{}{}

Remove top character
<>{}

End of main loop
>)}{}{}

Close the open parens
<>>){({}[()]<(((((()()){}()){}){}){}())>)}{}

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

```

Try it online!

## Output for `<your brain-flak code here>`, 582 bytes:

```
([()((()(()(()()()){}){}){}){}]((()(()()){}){}([(()()()){}](()(()){}((()(((()(()()){}){}){}){}){}([(()((((()()){}){}){}){}){}]([(((()()){}){}){}](()(((()()){}){}){}([((()()){}){}]([()(()()){}](()(((((()()){}){}){}){}){}([()(((()(()()()){}){}){}){}]([(()()()){}](()(()(()()){}){}([(()(()()){}){}](()(()((()((()()){}){}){}){}){}([()(()((((()()){}){}){}){}){}]([((()()()){}){}](()(()(()()){}){}([()](()((()(((()()){}){}){}){}){}([(((()((()()){}){}){}){}){}](()(()){}([()((()()()){}){}](()((()()()){}){}(()(()(()((()()){}){}){}){}((()(()(()(()()()){}){}){}){})))))))))))))))))))))))))))

```
> 3 votes

---
Tags: code-challenge, metagolf, test-battery, brain-flak, text-processing
---


title: Modular broadcasting

text:
# Question
Title: Modular broadcasting
*This challenge is related to some of the MATL language's features, as part of the May 2018 Language of the Month event.*

---

## Introduction

In MATL, many two-input functions work **element-wise** with **broadcast**. This means the following:

* **Element-wise** (or **vectorized**): the function takes as inputs two arrays with matching sizes. The operation defined by the function is applied to each pair of corresponding entries. For example, using post-fix notation:

```
[2 4 6] [10 20 30] +

```

gives the ouput

```
[12 24 36]

```

This also works with multi-dimensional arrays. The notation `[1 2 3; 4 5 6]` represents the `2`×`3` array (matrix)

```
1 2 3
4 5 6

```

which has size `2` along the first dimension (vertical) and `3` along the second (horizontal). So for example

```
[2 4 6; 3 5 7] [10 20 30; 40 60 80] *

```

gives

```
[20 80 180; 120 300 560]

```
* **Broadcasting** or (**singleton expansion**): the two input arrays do not have matching sizes, but in each non-matching dimension one of the arrays has size `1`. This array is implicitly replicated along the other dimensions to make sizes match; and then the operation is applied element-wise as above. For example, consider two input arrays with sizes `1`×`2` and `3`×`1`:

```
[10 20] [1; 2; 5] /

```

Thanks to broadcasting, this is equivalent to

```
[10 20; 10 20; 10 20] [1 1; 2 2; 5 5] /

```

and so it gives

```
[10 20; 5 10; 2 4]

```

Similarly, with sizes `3`×`2` and `3`×`1` (broadcasting now acts along the second dimension only),

```
[9 8; 7 6; 5 4] [10; 20; 30] +

```

gives

```
[19 18; 27 26; 35 34]

```

The number of dimensions may even be different. For example, inputs with sizes 3×2 and 3×1×5 are compatible, and give a 3×2×5 result. In fact, size 3×2 is the same as 3×2×1 (there are arbitrarily many implicit trailing singleton dimensions).

On the other hand, a pair of `2`×`2` and `3`×`1` arrays would give an error, because the sizes along the first dimension are `2` and `3`: they are not equal and none of them is `1`.

## Definition of modular broadcasting

Modular broadcasting is a generalization of broadcasting that works even if none of the non-matching sizes are `1`. Consider for example the following `2`×`2` and `3`×`1` arrays as inputs of the function `+`:

```
[2 4; 6 8] [10; 20; 30] +

```

The rule is as follows: for each dimension, **the array that is smaller along that dimension is replicated modularly (cyclically)** to match the size of the other array. This would make the above equivalent to

```
[2 4; 6 8; 2 4] [10 10; 20 20; 30 30] +

```

with the result

```
[12 14; 26 28; 32 34]

```

As a second example,

```
[5 10; 15 20] [0 0 0 0; 1 2 3 4; 0 0 0 0; 5 6 7 8; 0 0 0 0] +

```

would produce

```
[5 10 5 10; 16 22 18 24; 5 10 5 10; 20 26 22 28; 5 10 5 10]

```

In general, inputs with sizes `a`×`b` and `c`×`d` give a result of size `max(a,b)`×`max(c,d)`.

## The challenge

Implement **addition** for **two-dimensional** arrays with **modular broadcasting** as defined above.

The arrays will be **rectangular** (not ragged), will only contain **non-negative integers**, and will have **size at least `1`** in each dimension.

Aditional rules:

## Test cases

The following uses `;` as row separator (as in the examples above). Each test case shows the two inputs and then the output.

```
[2 4; 6 8]
[10; 20; 30]
[12 14; 26 28; 32 34]

[5 10; 15 20]
[0 0 0 0; 1 2 3 4; 0 0 0 0; 5 6 7 8; 0 0 0 0]
[5 10 5 10; 16 22 18 24; 5 10 5 10; 20 26 22 28; 5 10 5 10]

[1]
[2]
[3]

[1; 2]
[10]
[11; 12]

[1 2 3 4 5]
[10 20 30]
[11 22 33 14 25]

[9 12 5; 5 4 2]
[4 2; 7 3; 15 6; 4 0; 3 3]
[13 14 9;12 7 9;24 18 20;9 4 6;12 15 8]

[9 12 5; 5 4 2]
[4 2 6 7; 7 3 7 3; 15 6 0 1; 4 0 1 16; 3 3 3 8]
[13 14 11 16; 12 7 9 8; 24 18 5 10; 9 4 3 21; 12 15 8 17]

[6 7 9]
[4 2 5]
[10 9 14]

```

# Answer
# Jelly, 10 bytes

```
ṁ€ZL$Z€Ɗ⁺S

```

Takes a matrix pair (two arrays of rows) as input and returns a matrix.

Try it online!

### How it works

```
ṁ€ZL$Z€Ɗ⁺S  Main link. Argument: [M, N] (matrix pair)

  Z $       Zip M with N (i.e., transpose the matrix of arrays [M, N], ...
   L            then take the length (number of rows) of the result.
ṁ€          Mold M and N like the indices, cyclically repeating their rows as many
            times as needed to reach the length to the right.
     Z€     Zip each; transpose both M and N.
       Ɗ⁺   Combine the three links to the left into a chain and duplicate it.
            The first run enlarges the columns, the second run the rows.
         S  Take the sum of the modified matrices.

```
> 4 votes

# Answer
# Charcoal, ~~25~~ 23 bytes

```
~~Ａθ~~ＩＥ⌈ＥθＬιＥ⌈ＥθＬ§λ⁰ΣＥθ§§νιλ
```

Try it online! Link is to verbose version of code. Takes input as a 3-dimensional array. Explanation:

~~```
Ａθ

```~~

~~Input everything.~~

```
    θ                   Input
   Ｅ                    Map over arrays
      ι                 Current array
     Ｌ                  Length
  ⌈                     Maximum
 Ｅ                      Map over implicit range
          θ             Input
         Ｅ              Map over arrays
             λ          Current array
            § ⁰         First element
           Ｌ            Length
        ⌈               Maximum
       Ｅ                Map over implicit range
                 θ      Input
                Ｅ       Map over arrays
                    ν   Current array
                   § ι  Cyclically index using outer loop index
                  §   λ Cyclically index using inner loop index
               Σ        Sum
Ｉ                       Cast to string
                        Implicitly print on separate lines and paragraphs

```
> 5 votes

# Answer
# MATL, ~~25~~ 24 bytes

```
,iZy]vX>XKx,@GK:KP:3$)]+

```

Try it online!

Finally! It only took a week for the Language of the Month-inspired challenge to be answered by the Language of the Month!

My guess is that it's not quite as short as possible, but I'm happy enough because my initial version was over 40 bytes. *edit: I was right, Luis found another byte to squeeze out!*

```
,iZy]	# do twice: read input and find the size of each dimension
vX>	# find the maximum along each dimension
XKx	# save this into clipboard K and delete from stack. Stack is now empty.
,	# do twice:
 @G	# push the input at index i where i=0,1.
	# MATL indexes modularly, so 0 corresponds to the second input
 K:	# push the range 1...K[1]
 KP:	# push the range 1...K[2]
 3$)	# use 3-input ) function, which uses modular indexing
	# to expand the rows and columns to the appropriate broadcasted size
]	# end of loop
+	# sum the now appropriately-sized matrices and implicitly display

```
> 5 votes

# Answer
# Python 3, 127 126 125 bytes

*golfed a byte by changing `sum(m)` to `m+n`*

*One more byte thanks to @Jonathan Frech*

```
lambda y:[[m+n for n,m,j in Z(l)]for*l,i in Z(y)]
from itertools import*
Z=lambda y:zip(*map(cycle,y),range(max(map(len,y))))

```

Takes input as a list of two 2-dimensional arrays.

* The `Z` lambda takes two arrays as input and returns an iterator yielding an index and merged values from both arrays, until the index reaches the largest array's length. The index variable isn't useful to me and costs me bytes, but I don't know how to do without it... (related)
* The main lambda just takes the input arrays and calls `Z` on the outer and inner arrays. The innermost values are added together.

Try it online!

Using `itertools.cycle` feels a bit like cheating but I think I've been punished enough by the sheer import statement length :)

I'm sure this could be golfed some more, especially the iteration method that leaves these useless `i` and `j` variables. I would be grateful on any tips on how to golf that, I'm probably missing something obvious.
> 4 votes

# Answer
# 05AB1E, 15 bytes

```
2FεIζg∍ø]øεø¨}O

```

Try it online!

---

### Old version, 25 bytes

```
é`DŠg∍)Σнg}`DŠнgδ∍€˜)ø€øO

```

Try it online!

### Explanation

15-byter:

```
2FεIζg∍ø]øεø¨}O – Full program. Takes input as a 3D [A, B] list from STDIN.
2F              – Apply twice:
  ε             – For each in [A, B]:
   Iζ             – Transpose the input (filling gaps with spaces).
     g            – Length (retrieve the number of rows).
      ∍           – Extend the current item (A or B) to the necessary length.
       ø          – Transpose.
        ]       – Close all loops.
         ø      – Transpose again.
          ε     – For each row in ^ (column of the loops result):
           ø    – Transpose the column.
            ¨}  – Remove the last element and close the map-loop.
              O – Sum.

```

25-byter:

```
é`DŠg∍)Σнg}`DŠнgδ∍€˜)ø€øO – Full program. Takes input as a 3D list from STDIN.
é                         – Sort the list by length.
 `D                       – Dump contents separately onto the stack, duplicate the ToS.
   Š                      – Perform a triple swap. a, b, c -> c, a, b.
    g                     – Get the length of the ToS.
     ∍                    – Extend the shorter list (in height) accordingly.
      )Σ  }               – Wrap the whole stack into a list and sort it by:
        нg                – The length of its first item.
           `DŠ            – Same as above.
              нg          – The length of the first element.
                δ∍€˜      – Extend the shorter list (in width) accordingly.
                    )ø    – Wrap the stack into a list and transpose (zip) it.
                      €ø  - Then zip each list.
                        O – Apply vectorised summation.

```
> 3 votes

# Answer
# JavaScript (ES6), 131 bytes

Not the right tool for the job, and probably not the right approach either. Oh well... ¯\\\_(ツ)\_/¯

```
a=>b=>(g=(a,b,c)=>[...Array((a[b[L='length']]?a:b)[L])].map(c))(a,b,(_,y)=>g(a[0],b[0],(_,x)=>(h=a=>a[y%a[L]][x%a[0][L]])(a)+h(b)))

```

Try it online!

### How?

The helper function **g()** creates an array which is as large as the largest input array (**a** or **b**) and invokes the callback function **c** over it:

```
g = (a, b, c) =>
  [...Array(
    (a[b[L = 'length']] ? a : b)[L]
  )].map(c)

```

The helper function **h()** reads the 2D-array **a** at **(x, y)** with modular broadcasting:

```
h = a => a[y % a[L]][x % a[0][L]]

```

The main code now simply reads as:

```
a => b =>
  g(a, b, (_, y) =>
    g(a[0], b[0], (_, x) =>
      h(a) + h(b)
    )
  )

```

---

# Recursive version, 134 bytes

```
a=>b=>(R=[],g=x=>a[y]||b[y]?a[0][x]+1|b[0][x]+1?g(x+1,(R[y]=R[y]||[])[x]=(h=a=>a[y%a.length][x%a[0].length])(a)+h(b)):g(+!++y):R)(y=0)

```

Try it online!
> 3 votes

# Answer
# , ~~136 104 103 95~~ 93 bytes

Golfed down a whopping ~~33~~ 35 bytes following Giuseppe's advice. Managed to get under 100 bytes by using an operator as a function name. See history for more legible code.

```
function(x,y,d=pmax(dim(x),dim(y)))y/d[2]/d[1]+x/d[2]/d[1]
"/"=function(x,j)apply(x,1,rep,,j)

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Classic), ~~23~~ 21 bytes

```
↑{+⌿⍺[⍵|[0]⍳⍴⍺]}2,¨⍴¨

```

Try it online!

this could be the only time ever I get a chance to use `|[0]`
> 2 votes

# Answer
# K (ngn/k), 23 bytes

```
{+/2{+:'(|/#:'x)#'x}/x}

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 18 bytes

```
éR`UvXNèy‚é`©g∍®+ˆ

```

Try it online!

**Explanation**

```
éR                  # sort by length, descending
  `U                # store the shorter list in X
    v               # for each list y, index N in the longer list
     XNè            # get the nth element of the shorter list
        y‚é         # pair with y and sort by length
           `©g∍     # repeat the shorter list to the same length as the longer
               ®+   # elementwise addition of the lists
                 ˆ  # add to global list
                    # implicitly print global list

```
> 2 votes

# Answer
# Pyth, 24 bytes

```
KeSmlhdQmm+Fm@@bdkQKeSlM

```

Try it here

### Explanation

```
KeSmlhdQmm+Fm@@bdkQKeSlM
                    eSlMQ  Get the maximum length of (implicit) input...
KeSmlhdQ           K       ... and the maximum row length.
        mm                 For each 2d index ...
          +Fm@@bdkQ        ... get the sum of the appropriate elements.

```
> 2 votes

# Answer
# Java 8, 172 bytes

```
A->B->{int m=A.length,o=A[0].length,d=B.length,u=B[0].length,l=m>d?m:d,a=o>u?o:u,r[][]=new int[l][a],$;for(;l-->0;)for($=a;$-->0;)r[l][$]=A[l%m][$%o]+B[l%d][$%u];return r;}

```

Try it online.

**Explanation:**

```
A->B->{                   // Method with integer-matrix as both parameters and return-type
  int m=A.length,         //  Rows of `A`                        (we got an     M)
      o=A[0].length,      //  Columns of `A`                     (we got an     O)
      d=B.length,         //  Rows of `B`                        (we got a      D)
      u=B[0].length,      //  Columns of `B`                     (we got a      U)
      l=m>d?m:d,          //  Maximum of both rows               (we got an     L)
      a=o>u?o:u,          //  Maximum of both columns            (we got an     A)
      r[][]=new int[l][a],//  Result-matrix of size `l` by `a`   (and we got an R)
      $;                  //  Temp integer                       (which $pells? ;P)
  for(;l-->0;)            //  Loop over the rows
    for($=a;$-->0;)       //   Inner loop over the columns
      r[l][$]=            //    Set the current cell in the result-matrix to:
        A[l%m][$%o]       //     The value at {`l` modulo-`m`, `$` modulo-`o`} in `A`
        +B[l%d][$%u];     //     Plus the value at {`l` modulo-`d`, `$` modulo-`u`} in `B`
  return r;}              //  Return the result matrix

```
> 2 votes

# Answer
# Python 2, ~~124~~ 116 bytes

```
l=len
A,B=sorted(input(),key=l)
A*=l(B)
for i in eval(`zip(A,B)`):a,b=sorted(i,key=l);a*=l(b);print map(sum,zip(*i))

```

Try it online!

Explanation:

Takes list of two 2-d lists as input.

```
l=len
A,B=sorted(input(),key=l)         # Sort inputed lists by length
A*=l(B)                           # Extend shorter list
for i in eval(`zip(A,B)`):        # Zip and remove copied references
  a,b=sorted(i,key=l)             # Sort lists in each pair (keep references)
  a*=l(b)                         # Extend shorter list
  print map(sum,zip(*i))          # Zip and sum

```
> 2 votes

# Answer
# Python 2, 101 97 105 bytes

*Edit: Thanks (again !) to Dead Possum for saving 4 bytes*

*Edit 2: lost 8 bytes, some tests cases weren't passing*

A mix between Dead Possum's earlier solution (thanks to him !), and my own Python 3 solution.

```
lambda y:[map(sum,P(i))for i in P(y)]
def P(y):y=sorted(y,key=len);y[0]*=len(y[1]);return eval(`zip(*y)`)

```

Try it online!

Same input as my Python 3 solution (a pair of 2 dimensional lists).

Commented code:

```
# Iterate over the nested lists, resized & joined by P(),
# and sum the inner joined items
lambda y:[map(sum,P(i))for i in P(y)]
def P(y):
 y=sorted(y,key=len)  # Sort the two input lists by length
 y[0]*=len(y[1])      # Multiply the smallest one by the biggest one's length
                      # (The smallest list is now the previously largest one)
 return eval(`zip(*y)`)  # Return paired list elements up to the smallest list's length

```
> 2 votes

# Answer
# Julia 0.6, 85 83 bytes

```
M\N=(((r,c),(s,d))=size.((M,N));repmat(M,s,d)+repmat(N,r,c))[1:max(r,s),1:max(c,d)]

```

Try it online!

*(Replace  with `\` thanks to Jo King)*

Works by repeating each matrix horizontally and vertically so they both have the same size (product of row sizes x product of column sizes), adding those up and extracting out the correct region from that. (Row vector inputs or column vector inputs need a `reshape` call to be cast as 2-dimensional arrays, which I'm assuming is fine since the question specifies "Implement addition for two-dimensional arrays" and "Input and output can be taken by any reasonable means. Their format is flexible as usual.")
> 1 votes

---
Tags: code-golf, number, array, integer
---