title: Dijkstra's Challenge

text:
# Question
Title: Dijkstra's Challenge
## Presented in honor of APL as an interactive tool turning 50 this year

### Background

> Ken \[Iverson\] presented his paper *Formalism in Programming Languages* in August 1963 at a Working Conference on Mechanical Language Structures, Princeton, N.J. The list of conferees is full of famous and soon-to-be famous names, and a few future Turing Award winners (Backus, Curry, Dijkstra, Floyd, Iverson, Newell, Perlis, Wilkes). The paper also records the discussion that occurred after the presentation, ending with an exchange between Ken and \[Edsger\] Dijkstra, in which Ken’s reply to Dijkstra’s question was a one-liner.

### Challenge

> How would you represent a more complex operation, for example, the sum of all elements of a matrix ***M*** which are equal to the sum of the corresponding row and column indices?

Write a snippet or expression (no need for a full program or function) to calculate the sum of each element in a given integer matrix which is equal to the sum of its indices. Or, as FryAmTheEggman puts it: given a matrix ***M*** with elements ***a***ij return the sum of each ***a***ij where ***a***ij = i + j.

You may assume the matrix already being in a variable or memory location, or you may take it as an argument or input. You may use either 0 or 1 based indices.

### Test cases

```

```

`0` for empty matrix

```
2

```

`0` for 0 based indices or `2` for 1-based

```
1 5 2
9 4 2
5 9 6

```

`2` for 0 based or `10` for 1 based

```
 0 3  0  4
 0 4  1  4
 4 3  1  2
-2 4 -2 -1

```

`11`

```
3 -1 3 3
3 -1 3 1

```

`6` for 0 based or `3` for 1 based

### Anecdote

Iverson's answer was ++/(***M*** = ¹ ⨢ ¹)//***M***, which is neither valid in the *Iverson Notation* as defined in *A Programming Language*, nor in what eventually became APL. In Iverson notation, it would have been +/(***M*** = ¹(*μ*(***M***)) ⨢ ¹(*ν*(***M***)))/***M***. In the very first versions of APL it was `+/(,M=(⍳1↑⍴M)∘.+⍳1↓⍴M)/,M`.

# Answer
> 10 votes
# MATL, ~~15~~ ~~14~~ 10 bytes

```
3#fbb+y=*s

```

The input has rows separated by `;`. For example: `[1 5 2; 9 4 2; 5 9 6]`. 1-based indexing is used.

Try it online! Or verify all test cases.

### Explanation

I'll use the example with input `[3 -1 3 3; 3 -1 3 1]` in the explanation.

```
3#f    % Three-output find: for all nonzero values of implicit input matrix, pushes
       % three column vectors with row indices, column indices, and values
       %   Stack contains: [1;2;1;2;1;2;1;2], [1;1;2;2;3;3;4;4], [3;3;-1;-1;3;3;3;1]
bb     % Bubble up twice: move vectors of row and column indices to top
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [1;2;1;2;1;2;1;2], [1;1;2;2;3;3;4;4]
+      % Element-wise sum of top two arrays
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [2;3;3;4;4;5;5;6]
y      % Duplicate the vector of nonzero values onto the top of the stack
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [2;3;3;4;4;5;5;6], [3;3;-1;-1;3;3;3;1]
=      % Element-wise equality test of top two arrays
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [0;1;0;0;0;0;0;0]
*      % Element-wise multiply of top two arrays
       %   Stack contains: [0;3;0;0;0;0;0;0]
s      % Sum of array
       %   Stack contains: 3

```

# Answer
> 9 votes
# APL, ~~13~~ 12 bytes

**1 byte thanks to @jimmy23013.**

1-indexed.

The array is stored in the variable `m`.

```
~~+/,m×m=+/¨⍳⍴m~~
+/∊m∩¨+/¨⍳⍴m

```

Try it online!

Based on the answer in J, which is a language based on APL.

In TryAPL, to key in: `+/m`em`c`1+/`1`i`rm`

With the array: `+/m`em`c`1+/`1`i`rm `[ 2 4 `r 3 `21 3 3 3 `21 3 1`

### Explanation

```
+/∊m∩¨+/¨⍳⍴m
           m    temp ← variable
          ⍴     temp ← shape of temp
         ⍳      temp ← a 2D array where each element is
                       the corresponding index. for the
                       example, this gives:
                       ┌───┬───┬───┬───┐
                       │1 1│1 2│1 3│1 4│
                       ├───┼───┼───┼───┤
                       │2 1│2 2│2 3│2 4│
                       └───┴───┴───┴───┘
      +/¨       each element in temp ← its sum
   m∩¨          temp ← intersect each element in temp with the variable
+/              temp ← sum of temp

```

# Answer
> 6 votes
## JavaScript, ~~49~~ 46 bytes

```
a.map((b,i)=>b.map((c,j)=>r+=c==i+j&&c),r=0)|r

```

Edit: Saved 3 bytes thanks to @MartinEnder pointing out that snippets are allowed.

# Answer
> 5 votes
## Retina, 46 bytes

Byte count assumes ISO 8859-1 encoding.

```
\d+
$*
M!`(?<=(\S* |.*¶)*)(?<-1>1)+\b(?(1)1)
1

```

Input uses space and linefeed separators to represent the matrix. Indices are 0-based.

Try it online!

### Explanation

Not quite the kind of challenge Retina was made for, but it's doing surprisingly well... :)

**Stage 1: Substitution**

```
\d+
$*

```

This simply expands all the integers in the string as unary numbers using `1` as the unary digit. Negative numbers like `-3` will simply become things like `-111`.

**Stage 2: Match**

```
M!`(?<=(\S* |.*¶)*)(?<-1>1)+\b(?(1)1)

```

Due to the `!` option, this prints all the matches of the given regex. Said regex uses balancing groups to check whether the current number is the same as the sum of its indices.

To do that, we first determine the sum of indices with the lookbehind `(?<=(\S* |.*¶)*)`. This adds one capture for each number in front of the current one on the same line (via `\S*` ) as well as one capture for each line in front of the current one (via `.*¶`) to group `1`. Hence, we get the zero-based sum of indices as a result.

Then we try to match the entire next number while removing captures from this stack with `(?<-1>1)+\b`. And then we make the match fail if any captures are left on group `1` with `(?(1)1)` to ensure equality.

Note that negative numbers are never matched, because the lookbehind cannot get past the `-` in front of list of `1`s and the `(?<-1>1)+` can't match it either.

This gives us a list of all the unary numbers which equal the sum of their indices.

**Stage 3: Match**

```
1

```

We end with another match stage, but without the `!` option, this just counts the number of matches, which both sums all the unary numbers from the previous result and also converts that sum back to decimal.

# Answer
> 4 votes
# J, 15 bytes

```
+/,M*M=+/&i./$M

```

Uses zero-based indexing and assumes the matrix is already stored in variable *M*.

## Explanation

```
+/,M*M=+/&i./$M
             $a  Get the shape of M
            /    Insert between the shape
         &i.     Create a range from 0 to each end exclusive
       +/        Forms a table which is the sum of each row and column index
     M=          1 if the element is equal to its index sum else 0
   M*            Multiply by their values
  ,              Flatten
+/               Reduce using addition to get the sum

```

# Answer
> 4 votes
# Jelly, ~~15~~ ~~14~~ 10 bytes

**4 bytes thanks to Adnan.**

1-indexed.

```
~~L€R€+"LR$=³×³FS~~
~~L€R€+"LR$=×³FS~~
J€+"J=×⁸FS

```

Try it online!

Verify all testcases at once. (Slightly modified.)

# Answer
> 4 votes
# R, 24 bytes

```
sum(M[M==row(M)+col(M)])

```

1-based.
Test cases:

```
> M<-matrix(nrow=0,ncol=0)
> M
<0 x 0 matrix>
> sum(M[M==row(M)+col(M)])
[1] 0
> M<-matrix(2,nrow=1,ncol=1)
> M
     [,1]
[1,]    2
> sum(M[M==row(M)+col(M)])
[1] 2
> M<-matrix(c(1,9,5,5,4,9,2,2,6),nrow=3)
> M
     [,1] [,2] [,3]
[1,]    1    5    2
[2,]    9    4    2
[3,]    5    9    6
> sum(M[M==row(M)+col(M)])
[1] 10
> M<-matrix(c(0,0,4,-2,3,4,3,4,0,1,1,-2,4,4,2,-1),nrow=4)
> M
     [,1] [,2] [,3] [,4]
[1,]    0    3    0    4
[2,]    0    4    1    4
[3,]    4    3    1    2
[4,]   -2    4   -2   -1
> sum(M[M==row(M)+col(M)])
[1] 11
> M<-matrix(c(3,3,-1,-1,3,3,3,1),nrow=2)
> M
     [,1] [,2] [,3] [,4]
[1,]    3   -1    3    3
[2,]    3   -1    3    1
> sum(M[M==row(M)+col(M)])
[1] 3

```

# Answer
> 3 votes
## CJam, ~~23~~ ~~21~~ 20 bytes

*Thanks to Peter Taylor for saving 3 bytes.*

```
ee{~_@f-_,,.=.*~}%1b

```

Expects the matrix to be on the stack and leaves the sum instead. Indices are zero-based in either case.

Test it here.

# Answer
> 3 votes
# Python 2 - ~~60~~ 57 bytes

It's a code snippet, so it would be a few more bytes if I actually returned the value, I guess. `e=enumerate;sum(i*(x+y==i)for x,r in e(a)for y,i in e(r))`

Thanks for the help Leaky Num :-)

Quick explanation. `a` is an array holding numbers. Simply iterate through indexes and sum up all values where the value equals the sum of the index.

# Answer
> 3 votes
# k4, 24 bytes

Assumes the matrix is stored in `m`.

```
+//7h$m*m=(!#m)+/:\:!#*m

```

This is one of those puzzles where the simplifications involved in designing k from APL (and J) really hurt—k’s `!` is the equivalent of APL’s  but only works on vectors, so I have to assemble the matrix of indices myself; inner product is one character in APL but five in k; and I lose three characters to handling the empty matrix properly because k doesn’t have strongly-typed matrices.

# Answer
> 2 votes
# Pyth, 14 bytes

0-indexed.

```
ss.e.e*ZqZ+kYb

```

Test suite.

# Answer
> 2 votes
## PowerShell v2+, 43 bytes

```
%{$j=0;$_|%{$o+=$_*($_-eq$i+$j++)};$i++};$o

```

As a snippet. Usage is to explicitly pipe the matrix to this (see examples below). Assumes that `$i`, and `$o` are either null or zero at the start (I've explicitly set them as such in the examples below), and utilizes 0-index.

Does a foreach loop on each row of the matrix. We set `$j` to `0`, and then go through each element of the row in another loop `$_|%{...}`. Each inner loop, we increment `$o` by the current element multiplied by a Boolean `($_-eq$i+$j++)`, meaning if that Boolean is `$TRUE`, it'll be `1`, otherwise `0`. Then we exit the inner loop, increment `$i`, and start the next row. Finally, we leave `$o` on the pipeline at the end.

### Examples

```
PS C:\Tools\Scripts\golfing> $o=0;$i=0;$j=0;@(@(3,-1,3,3),@(3,-1,3,1))|%{$j=0;$_|%{$o+=$_*($_-eq$i+$j++)};$i++};$o
6

PS C:\Tools\Scripts\golfing> $o=0;$i=0;$j=0;@(@(0,3,0,4),@(0,4,1,4),@(4,3,1,2),@(-2,4,-2,-1))|%{$j=0;$_|%{$o+=$_*($_-eq$i+$j++)};$i++};$o
11

```

# Answer
> 2 votes
# Ruby, 63 bytes

With z as a two-dimensional array of numbers:

```
s=0;z.each_index{|i|z[i].each_index{|j|s+=i+j if z[i][j]==i+j}}

```

Not terribly exciting at all.

If z is a flattened array with x and y having the sizes of the arrays, such as:

```
x=z.size
y=z[0].size
z=z.flatten

```

Then we have this monstrousity - perhaps more ruby-ish with it's fancy products and zips, but actually larger:

```
(1..x).to_a.product((1..y).to_a).zip(z).inject(0){|s,n|s+(n[0][0]+n[0][1]==n[1]+2?n[1]:0)}

```

# Answer
> 2 votes
## Actually, 21 bytes

```
ñ`i╗ñ"i╜+@;(=*"£Mi`MΣ

```

Try it online!

Thanks to Leaky Nun for making me stop being lazy and finally write this.

This uses 0-indexed matrices, and takes input as a nested list.

Explanation:

```
ñ`i╗ñ"i╜+@;(=*"£Mi`MΣ
ñ                      enumerate input
 `i╗ñ"i╜+@;(=*"£Mi`M   for each (i, row) pair:
  i╗                     flatten, store i in register 0
    ñ                    enumerate the row
     "i╜+@;(=*"£M        for each (j, val) pair:
      i╜+                  flatten, add i to j
         @;(               make an extra copy of val, bring i+j back to top
            =              compare equality of i+j and val
             *             multiply (0 if not equal, val if they are)
                 i       flatten the resulting list
                    Σ  sum the values

```

# Answer
> 2 votes
# Matlab/Octave, 48 bytes

1-indexed.

Will not handle the first test case because `[1:0]` has size 1x0 for some reason

```
sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0)))

```

Tested in Octave 3.

Full program:

```
M = [2]
sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0)))
M = [1 5 2; 9 4 2; 5 9 6]
sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0)))
M = [ 0 3  0  4; 0 4  1  4; 4 3  1  2;-2 4 -2 -1]
sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0)))
M = [ 3 -1 3 3; 3 -1 3 1]
sum(sum(M.*(M-[1:size(M,1)]'-[1:size(M,2)]==0)))

```

# Answer
> 1 votes
# Lua, 70 bytes

1-indexed.

```
s=0 for i=1,#a do for j=1,#a[i]do s=i+j==a[i][j]and s+i+j or s end end

```

Bonus: it works for ragged arrays!

Input stored in `a`, output stored in `s`.

# Full program:

```
function Dijkstras_Challenge(a)
    s=0 for i=1,#a do for j=1,#a[i]do s=i+j==a[i][j]and s+i+j or s end end
    print(s)
end

Dijkstras_Challenge({})
Dijkstras_Challenge({{2}})
Dijkstras_Challenge({{1,5,2},{9,4,2},{5,9,6}})
Dijkstras_Challenge({{0,3,0,4},{0,4,1,4},{4,3,1,2},{-2,4,-2,-1}})
Dijkstras_Challenge({{3,-1,3,3},{3,-1,3,1}})

```

# Answer
> 1 votes
# PHP, 59 bytes

```
foreach($a as$y=>$r)foreach($r as$x=>$v)$s+=($v==$x+$y)*$v;

```

expects array $a defined; must be empty or 2-dimensional, 0-indexed.
calculates sum to $s (previously 0 or undefined - 0 equals NULL)
insert `+2` before final `)` for 1-indexed behaviour

Happy Birthday APL!

**functions and test suite**

```
function f0($a) { foreach($a as$y=>$r)foreach($r as$x=>$v)$s+=($v==$x+$y)*$v;return $s|0; }
function f1($a) { foreach($a as$y=>$r)foreach($r as$x=>$v)$s+=($v==$x+$y+2)*$v;return $s|0;}
$samples = [
    [], 0, 0,
    [[2]], 0, 2,
    [[1,5,2],[9,4,2],[5,9,6]], 2, 10,
    [[0,3,0,4],[0,4,1,4],[4,3,1,2],[-2,4,-2,-1]],11,11,
    [[3,-1,3,3],[3,-1,3,1]],6,3
];
function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',cmp($e,$y)?'N':'Y',"</td></tr>";$h='';}
while($samples)
{
    $a=array_shift($samples);
    test($a,'B0:'.array_shift($samples),'B0:'.f0($a));
    test($a,'B1:'.array_shift($samples),'B1:'.f1($a));
}

```

# Answer
> 1 votes
# Brachylog, 15 bytes

```
{iiʰI-ʰ=∧Ihh}ᶠ+

```

Try it online!

```
              +    The output is the sum of
{           }ᶠ     all possible results of
 i                 taking a row from the input with its index,
  i                taking an element with its index
   ʰ               from that row,
    I    Ihh       and outputting the element
       =∧          so long as the index of the row is equal to
     -ʰ            the value of the element minus its index within the row.

```

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

```
ArrayRules/*Cases[p_~_~v_/;Tr@p==v:>v]/*Tr

```

Try it online!

1-indexed.

```
ArrayRules                                  (*Convert into a list of (position->value) Rules*)
          /*Cases[p_~_~v_/;Tr@p==v          (*select those where sum(position)==value*)
                                  :>v]/*Tr  (*and find the sum of those values*)

```

---
Tags: code-golf, math, arithmetic, matrix
---


title: Is it rectilinear?

text:
# Question
Title: Is it rectilinear?
Today's challenge:

> Given an ordered list of at least 3 *unique* integer 2D points forming a polygon, determine if the resulting polygon is Rectilinear.

A polygon is rectilinear if every interior angle is a right angle. The edges do not necessarily have to be purely vertical or horizontal (parallel to the x or y axis), as long as the angles are all right (This is slightly different than Wikipedia's definition, but it's the definition we'll be sticking with). For example, the following shape is a perfect square rotated 45°

```
(0, -1)
(1, 0)
(0, 1)
(-1, 0)

```

None of the lines are parallel to the x or y axis, but all of the angles are right so it is considered truthy for today's challenge. Note that the order of the points is important. The following reordering of these points gives a self-intersecting polygon, which is basically an hourglass shape rotated 45°. This is falsy:

```
(0, -1)
(0, 1)
(1, 0)
(-1, 0)

```
* You must take the input as an ordered set of points. Angles between the points or a "shape object" if your language has one, are not valid inputs.
* You must output one consistent value for truthy and a different consistent value for falsy.
* Note that truthy inputs will always have an even number of points.
* It is acceptable if your submission fails for very large inputs because of floating-point inaccuracies.

*Note*: If you want to visualize a polygon, I've found this tool and Desmos Graphing Calculator both very useful.

## Truthy examples

```
(0, 0)
(0, 20)
(20, 20)
(20, 0)

(1, 1)
(0, 3)
(6, 6)
(7, 4)

# This example is self-intersecting
(2, 3)
(3, 1)
(-3, -2)
(-2, -4)
(2, -2)
(0, 2)

(4, 0)
(4, 2)
(0, 2)
(0, 4)
(2, 4)
(2, 5)
(4, 5)
(4, 3)
(6, 3)
(6, 0)

```

## Falsy examples

```
(0, 0)
(0, 20)
(20, 20)
(20, 10)

(100, 100)
(100, 50)
(50, 100)

(2, 2)
(3, 3)
(6, 2)
(7, 3)

(100, 100)
(100, -100)
(-100, -100)
(-100, 99)

```

# Answer
> 7 votes
# Octave, ~~60 42 41~~ 40 bytes

I was just looking for an excuse to use `nlfilter`, too bad the solution was too long:) Now we compute the vectors of the sides of the polygon using `d=x-x(:,[2:end,1]))`. Then `d * d'` computes *all* pairwise dot products. We are only interested if consecutive dot products are all zero, therefore we check whether the first superdiagonal `diag(...,1)` is all zeros using `any(...)`.

```
@(x)any(diag((d=x-x(:,[2:end,1]))*d',1))

```

Try it online!

# Answer
> 6 votes
# APL (Dyalog Unicode), 16 bytes

```
×/0=4○∘×2÷/2-/,⍨

```

Try it online!

Accepts the input as a list of complex numbers, e.g. `1j2` means \\$ 1 + 2i \\$ which represents the point \\$ (1,2) \\$.

The result is 1 if the given polygon is rectilinear, 0 otherwise.

### How it works

```
×/0=4○∘×2÷/2-/,⍨
              ,⍨  Concatenate self, so that all angles can be tested
           2-/    Difference of two adjacent values, i.e. vectors
        2÷/       Ratio of two adjacent values, i.e. angle difference
       ×          Normalize to unit vectors
    4○∘           Compute sqrt(1+x^2)
                  Zero if and only if the angle is a right angle
                  i.e. the normalized angle difference vector is i or -i
×/0=              Test if all results are zero, i.e. all angles are right angles

```

# Answer
> 5 votes
# Jelly, 7 bytes

```
;`_ƝḋƝẸ

```

Try it online!

Outputs \\$0\\$ if rectilinear, \\$1\\$ otherwise

-2 bytes thanks to Jonathan Allan!

# Answer
> 3 votes
# Zsh, 94 bytes

```
for v w;:
for x y;a+=($[v-x]\ $[w-y])&&v=$x&&w=$y
for v w x y ($=a[-1] ${=a:^a})((r|=v*x+w*y))

```

Try it online!

Input as flattened list of coordinates, outputs via exit code (`1` if rectilinear, `0` if not rectilinear). There are three loops here:

```
for v w;:   # this does nothing other than set $v and $w to the last coordinate pair

```

```
for x y                     # ($v,$w) is previous vertex, ($x,$y) is current vertex
    a+=($[v-x]\ $[w-y]) &&  # vector ($v,$w)->($x,$y) as space-delimited string
    v=$x && w=$y            # save previous point

```

```
for v w x y ($=a[-1] ${=a:^a}) # This iterates through all subsequent vectors (see below)
    ((r|=v*x+w*y))             # calculate the dot product, bitwise-or with previous dot-products
                               # if non-zero, r will be non-zero and the exit code will be zero

```

The last loop uses `${= }`, which splits parameters on spaces, and `${ :^ }`, which zips two arrays together (in this case, an array with itself). So, we have the last element in the array, followed by every element twice. That isn't an even number of coordinate pairs, so on the last iteration, `x` and `y` are empty. This is fine for the dot product, though, it will compute the dot product with the zero vector, which will always be rectilinear.

Using debug traps, you can walk through the function here.

# Answer
> 2 votes
# Python3, 98 bytes

```
lambda p:not sum((a-c)*(e-c)+(b-d)*(f-d)for(a,b),(c,d),(e,f)in zip(*[p[i:]+p[:i]for i in[0,1,2]]))

```

Try it online!

Takes in a list of tuple points and outputs True if the points are rectilinear, False otherwise.

## How it works

```
p # contains a list of points
[p[i:]+p[:i]for i in[0,1,2]]  # makes 3 lists of p rotated 0, 1, and, 2 places respectively
zip(*[p[i:]+p[:i]for i in[0,1,2]])  # zips the shifted lists together
(a,b),(c,d),(e,f) in zip(*[p[i:]+p[:i]for i in[0,1,2]])  # extracts (x0,y0), (x1,y1), and (x2,y2) from the zipped lists
(a-c)*(e-c)+(b-d)*(f-d)  # translates the 0th and 2nd point by the 1st and computes the dot product, which should be 0 if the points are orthogonal
sum((a-c)*(e-c)+(b-d)*(f-d)for(a,b),(c,d),(e,f)in zip(*[p[i:]+p[:i]for i in[0,1,2]]))  # sums all of the consecutive dot products together
not sum((a-c)*(e-c)+(b-d)*(f-d)for(a,b),(c,d),(e,f)in zip(*[p[i:]+p[:i]for i in[0,1,2]]))  # finally negate the result since if the sum is 0 than all of the points are orthogonal and hence the points form a rectilinear shape!

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~49~~ 48 bytes

```
0==##&@@Dot@@@({#,r@#})&[(r=RotateLeft)@#-#]&

```

Try it online!

-1 thanks to attinat!

# Answer
> 1 votes
# Charcoal, 20 bytes

```
⬤θ¬ΣＥιΠＥ²⁻λ§§θ⁺κ⊖⊗νμ

```

Try it online! Link is to verbose version of code. Outputs using Charcoal's default boolean format, which is `-` for true and nothing for false. Works by separately subtracting each point's x- and y-coordinates from its two adjacent points, then taking the products of the subtractions, then summing, which results in zero when the point is at a right angle. Explanation:

```
 θ                      Input array
⬤                       Each point satisfies
     ι                  Current point
    Ｅ                   Map over coordinates
       Ｅ²               Map over implicit range `0`..`1`
          λ             Current coordinate
         ⁻              Subtract
                  ν     Inner value `0` or `1`
                 ⊗      Doubled to `0` or `2`
                ⊖       Decremented to `-1` or `1`
               κ        Outer index
              ⁺         Added
             θ          Input array
            §           Get the adjacent point
           §       μ    Take the relevant coordinate
      Π                 Take the product
   Σ                    Take the sum
  ¬                     Is zero
                        Implicitly print

```

# Answer
> 1 votes
# Python 2, 68 bytes

```
lambda l:any(((a-b)/(b-c)).real for a,b,c in zip(l,l[1:]+l,l[2:]+l))

```

Try it online!

Input is a list of complex numbers. Output is True or False, swapped.

# Answer
> 1 votes
# Haskell, 54 bytes

```
all((==0).sum).r(*).r(-)
r=(=<<tail<>id).z.z
z=zipWith

```

Try it online!

Uses `(<>)`, which is available in base in the latest release.

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~41~~ ~~35~~ 34 bytes

```
Norm@Cos@PolygonAngle@Polygon@#>0&

```

Returns `False` for rectilinear polygons and `True` otherwise.

Only works in 12.0+, so no TIO link

-6 bytes thanks to @Roman

-1 bytes thanks to deleted comment

# Answer
> 1 votes
Excuse my rusty Ruby. Maybe someone can hint how to shorten. :)

# Ruby, 158 bytes

```
s=0;a=ARGV;a[0].split(",").zip(a[2].split(",")).map{|a,b|b.to_i-a.to_i}.zip(
a[1].split(",").zip(a[3].split(",")).map{|a,b|b.to_i-a.to_i}){|a,b|s+=a*b};p s==0

```

Try it online!

# Answer
> 0 votes
# Python and numpy, ~~94~~ 92 bytes

Uses roll a silly number of times and has two input lists of x and y coordinates. It is easier to rotate an array with python lists (`x[1:]+x[:1]`) but naturally numpy arrays aren't concatenated with `+`.

```
from numpy import roll as r
def f(x,y):a,b=r(x,1)-x,r(y,1)-y;return 1-any(a*r(a,1)+b*r(b,1))

```

# Answer
> 0 votes
# R, ~~60~~ 53 bytes

Takes in a vector of complex coordinates and returns swapped truthy and falsey. Uses xnor's dot product trick.

```
function(x,a=c(x[-1],x[1])-x)any(Re(a/c(a[-1],a[1])))

```

-7 bytes by using inline rotation instead of creating a function.

# R, ~~82~~ ~~79~~ 75 bytes

Improved version taking advantage of doing computation in default parameters to save on curly braces.

```
r=pryr::f(c(z[-1],z[1]))
function(x,y,a=r(x)-x,b=r(y)-y)any(a*r(a)+b*r(b))

```

-3 bytes by using `pryr::f` anonymous function and returning 0 for truthy, 1 for falsey.

-4 bytes with better roll function

# R, 87 bytes, original answer

My first R answer! Uses same array rotation logic as my numpy answer.

```
r=function(x)c(tail(x,-1),x[1])
x=scan()
y=scan()
a=r(x)-x
b=r(y)-y
!any(a*r(a)+b*r(b))

```

---
Tags: code-golf, math, decision-problem, geometry
---


title: In Flanders Fields

text:
# Question
Title: In Flanders Fields
Today is November 11th, which for many regions is Remembrance Day.

If you don't know anything about the history or context of Remembrance Day, you can read about it in the wiki page, but it's not relevant for this challenge.

*In Flanders Fields* is a poem that is pretty well-known relating to this day. It opens like so:

```
In Flanders fields the poppies blow
Between the crosses, row on row

```

# Challenge

You will be given a grid with crosses (represented below as `+`) on it. Your task is to grow poppies between all crosses. That is, fill the space between any two crosses that are on the same row or column with poppies (represented below as `*`).

# Example

```
....+....
...+.+...
.........
....+....
..+...+..
.........
..+...+..

```

This becomes:

```
....+....
...+*+...
....*....
....+....
..+***+..
..*...*..
..+***+..

```

Rigorously defined, on a non-cylindrical grid, each grid space is `+` if it was `+`, and becomes `*` if it has a `+` in the same column above and below it, or in the same row to its left and right.

# Test Cases

```
.....+...    .....+...
+......+.    +******+.
....+.+.. -> *...+*+..
+.+...+..    +*+***+..
...++.+..    ...++*+..

.+.....    .+.....
....+..    .*..+..
...+..+    .*.+**+
.+++...    .+++*.*
....... -> .****.*
.+++.+.    .+++*+*
.++.++.    .++*++*
.......    .*....*
.+....+    .+****+

.......    .......
...+...    ...+...
.....++    .....++
++.....    ++...**
+....+. -> +****+*
.....+.    .....+*
.......    ......*
.......    ......*
..+...+    ..+***+

.+.+..    .+*+..
.....+    .*.*.+
+.....    +*.*.*
.+....    .+.*.*
...+.+ -> ...+*+
......    ......
......    ......
....+.    ....+.

```

# Rules and Specifications

Input requires a grid of two distinct values. You can take this in any convenient format, and you can choose to use any reasonable convenient values, like `0` and `1`, for example.

Output requires a grid of three distinct values. Again, you can deliver this in any reasonable, convenient format.

Standard loopholes apply.

This is a challenge, so the shortest solution in each language wins. No answer will be accepted.

(Sorry for posting another challenge, especially another one, so soon, but I really wanted to do something for 11/11 and I thought of it after my pattern expansion one)

# Answer
# Python 2, ~~131~~ 125 bytes

```
f=lambda A,p=1:map(''.join,zip(*[re.sub('\+.+\+',lambda x:re.sub('\.','*',x.group()),s)for s in p and f(A,0)or A]))
import re

```

Try it online!

Input is a list of strings; as is output.
> 7 votes

# Answer
# Jelly, 12 bytes

```
ẒT.ịr/Ṭ»)Z$⁺

```

A monadic Link accepting a list of lists where:

* crosses, `+`, are `2`
* spaces, `.`, are `0`

which yields a list of lists as above with poppies, `*`, as `1`.

**Try it online!** Or see one which translates IO.

### How?

```
ẒT.ịr/Ṭ»)Z$⁺ - Link: list of lists
          $  - last two links as a monad  - i.e. f(Rows):
        )    -   for each Row in Rows:
Ẓ            -     is prime? (vectorises) (isCross() that work's once poppies are planted)
 T           -     truthy indices e.g. [0,0,1,0,0,1,1,0] -> [3,6,7]
  .          -     literal one half
   ị         -     index into (the truthy indices)  -- non-integer indices reference the
             -         items on either side of that location & indexing is 1-based and
             -         modular, so [last,first]  e.g. [3,6,7]->[7,3] or [8] -> [8,8]
     /       -     reduce by:
    r        -       inclusive range  e.g. [7,3]->[7,6,5,4,3] or [8,8]->[8]
      Ṭ      -     un-truth  e.g. [7,6,5,4,3]->[0,0,1,1,1,1,1] or [8]->[0,0,0,0,0,0,0,1]
       »     -     maximum (with Row) (vectorises) (keep crosses, plant poppies)
         Z   -   transpose
           ⁺ - repeat the last link (plant the remaining column poppies and transpose back)

```
> 6 votes

# Answer
# PowerShell, 96 bytes

```
param($a)$a=&($g={($a=$a-replace'(?<=\+.*)\.(?=.*\+)','*')[0]|% t*y|%{-join$a.chars($i++)}});&$g

```

Try it online!
> 5 votes

# Answer
# Japt `-h`, 16 bytes

```
2Æ=Õ®Ëd0E©nFÊÉ}S

```

No regex!

Try it

```
2Æ=Õ®Ëd0E©nFÊÉ}S     U = input
2Æ                   2 times do:
  =                    Set U to
   Õ                     U transposed
    ®                    Map each row:
     Ë        }S           Split each row on spaces (crosses),
                           and pass each chunk through the following function,
                           then rejoin on spaces
                           For each chunk:
      d0                     Replace all 0's (empty spaces)
        E©nFÊÉ               And replace with 1 if this chunk wasn't the first or last chunk
-h                   Take final result of second iteration

```
> 4 votes

# Answer
# , 44 bytes

```
'.*+'{~[:(+:+-.*](+.|:)&(>./\.*>./\)|:)=&'+'

```

Try it online!

No regex used:

* Takes the product of the max scan of the prefixes and the max scan of the suffixes to turn the in-between cells to 1.
* Does this for both the input and its transpose (to get both directions)
* "Or"s these two matrices.
* Multiplies by one minus the input, to get rid of endpoints (ie, original crosses)
* Add double the original matrix to that.
* After all this, in-between points in both directions are 1, original points are 2, rest are 0.
* We use that to index into `'.*+`.
> 4 votes

# Answer
# Jelly, ~~18~~ 14 bytes

```
UÄUaÄa2
ZÇZoÇ_

```

Try it online!

-4 bytes because I figured out what I did wrong with my cumulative sums

Input and output is as two-dimensional lists with `.` mapped to 0, `+` mapped to 1, and `*` mapped to 2. (The footer on TIO converts automatically for convenience.)

```
           Helper link:
     a2    Fill in 2s wherever
    Ä      there's at least one truthy value to the left
UÄUa       and at least one truthy value to the right.
           This fills in poppies between (and on) all crosses horizontally.

   oÇ      Overlay the horizontal poppies
ZÇZ        on the vertical poppies,
     _     and subtract the crosses out to recover them.

```
> 4 votes

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

```
a=>(g=m=>m[0].map((_,i)=>m.map(l=>l.join``.replace(/(?<=x.*)-(?=.*x)/g,8)[i])))(g(a))

```

Try it online!

Input / Output as character matrix. Use `x` for `+`, `-` for `.`, `8` for `*`.

First, convert dots `.` between two crosses `+` in a row into star `*`.

```
l.join``.replace(/(?<=\+.*)\.(?=.*\+)/g,'*')

```

Then. rotate the matrix

```
a=>m=>m[0].map((_,i)=>m.map(l=>l[i]))

```

Repeat twice, and get the result.
> 3 votes

# Answer
# Ruby, 101 bytes

```
->s{g=->x{x.map(&:chars).transpose.map(&:join).map{|l|l[w=/\+.+\+/]&&l[w]=l[w].tr(?.,?*);l}};g[g[s]]}

```

Try it online!

Not really satisfied with it, but it's a starting point.
> 3 votes

# Answer
# Japt v2.0a0 `-h`, ~~22~~ ~~21~~ ~~19~~ 13 bytes

Uses `<space>` for `+`, `*` for `.` & `1` for `*`.

```
2Æ=Õr/ .+ /È×

```

Try it (Header & footer convert I/O to characters used in spec)

```
2Æ=Õr/ .+ /È×     :Implicit input of string U
2Æ                :Map the range [0,2)
  =               :Reassign to U
   Õ              :Transpose U
    r/ .+ /       :Global RegEx replacement
           È      :Pass each match through a function
            ×     :  Replace all * with 1
                  :Implicit output of last element in array

```
> 3 votes

# Answer
# Retina 0.8.2, 80 bytes

```
+`#( *)#
#$.1$**#
+ms`^(((.))*#.*^(?<-2>.)*(?(2)$)) (.*^(?<-3>.)*(?(3)$)#)
$1*$4

```

Try it online! Includes header/footer that translates input/output between `.` and `+` to something more regex-friendly for the actual code. Explanation:

```
+`#( *)#
#$.1$**#

```

Repeatedly horizontally fill all s between `#`s. (Since this requires an unbroken run of s, this has to repeat until completion before the second stage runs.)

```
+ms`

```

Repeat as many times as necessary, allow `^` to match after a newline, and allow `.` to match newlines.

```
^(((.))*#.*

```

Look for a `#` and capture its indent twice.

```
^(?<-2>.)*(?(2)$)) (.*

```

Look for a  at the same indent.

```
^(?<-3>.)*(?(3)$)#)

```

Look for another `#` at the same indent.

```
$1*$4

```

Replace the  with a `*`.
> 3 votes

# Answer
# Red, ~~160~~ 154 bytes

```
func[b][loop 2[t: collect[until[parse keep rejoin
collect[forall b[keep take b/1]][any[thru"+"change
copy p to"+"(replace/all p".""*")]]empty? b/1]]b: t]]

```

Try it online!
> 2 votes

# Answer
# Perl 5 (`-p`), 80 bytes

```
/
/;$l="."x"@-";1while s/(\+\S*)\.(\S*\+)|(\+$l(.$l)*)\.($l(.$l)*\+)/$1$3*$2$5/s

```

Try it online!
> 0 votes

# Answer
# Python 3.8, 354 bytes

```
e,r=enumerate,range
def f(s):
	s=s.split('\n')
	t=[(x,y) for y,i in e(s) for x,c in e(i) if c=='+']
	#t is the '+'es coordinates
	m=sum((l for x,y in t for u,v in t
		if (x==u)!=(y==v)and x<=u and y<=v and
		(l:=[[(y,j)for j in r(x+1,u)],[(i,x)for i in r(y+1,v)]][x==u]) and
		#l is coordinates of cells between two '+'es
		all(s[i][j]=='.' for i,j in l)),[])
	return '\n'.join(''.join([c,'*'][(y,x) in m]for x,c in e(i))for y,i in e(s))

```

Try it online! (without comments or unnecessary white-space)
> 0 votes

# Answer
# Japt `-R`, 19 bytes

```
yV=_gZa0 oZb0)_p
yV

```

Try it

```
U = U.y // for each columns
(V = function(Z) { return
  Z.g // modify
(Z.a(0).o(Z.b(0)), // indexes from first cross to Last cross
function(Z) { return Z.p() // power of 2: -1 => 1
 })  });
V = U.y(V); // repeat transposing

Outputs a matrix of values:
-1 -> ground,  1 -> poppies,  0 -> cross
Footer maps to [' ','○','+']

```

With the help of @Shaggy and @Embodiment of Ignorance
> 0 votes

---
Tags: code-golf, ascii-art, matrix
---


title: Counting symmetric grid chains

text:
# Question
Title: Counting symmetric grid chains
# Notation and definitions

Let \\$\[n\] = \\{1, 2, ..., n\\}\\$ denote the set of the first \\$n\\$ positive integers.

A polygonal chain is a collection of connected line segments.

The *corner set* of a polygonal chain is a collection of points which are the endpoints of one or more of the line segments of the chain.

# Challenge

The goal of this challenge is to write a program that takes two integers, \\$n\\$ and \\$m\\$ and computes the number of non-self-intersecting polygonal chains with corner set in \\$\[n\] \times \[m\]\\$ that hit every point in \\$\[n\] \times \[m\]\\$ and are stable under \\$180^\circ\\$ rotation. You should count these shapes up to the symmetries of the rectangle or square.

Note: In particular, a polygon is considered to be self-intersecting.

# Example

For example, for \\$n=m=3\\$, there are six polygonal chains that hit all nine points in \\$\[3\] \times \[3\]\\$ and are the same after a half-turn:

### Table of small values

```
 n | m | f(n,m)
---+---+-------
 1 | 2 | 1
 1 | 3 | 1
 2 | 1 | 1
 2 | 2 | 1
 2 | 3 | 5
 2 | 4 | 11
 2 | 5 | 23
 3 | 1 | 1
 3 | 2 | 5
 3 | 3 | 6
 3 | 4 | 82

```

# Scoring

This is a challenge, so shortest code wins.

# Answer
> 7 votes
# Python 3 \+ SymPy, ~~480~~ ~~455~~ 452 bytes

```
lambda w,h:len({min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w+~p[0],p[1]),I),(lambda p:(p[0],h+~p[1]),I),(lambda p:p[::-1],I)))for o in permutations(Q(range(w),range(h)))for s in[[*zip(o,o[1:])]]if any(x-~X-w|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))+any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s))<1})
from math import*
from sympy import*
from itertools import*
Q=product
S=Segment
I=tuple

```

Try it online!

Inlined version of the previous answer below. -3 bytes thanks to Kevin Cruijssen's tip.

---

# Python 3 \+ SymPy, 480 bytes

```
from math import*
from sympy import*
from itertools import*
Q=product
S=Segment
I=tuple
def f(w,h):
 a={1}
 for o in permutations(Q(range(w),range(h))):
  s=[*zip(o,o[1:])]
  if any(x+X-w+1|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))+any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s))<1:a.add(min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w-1-p[0],p[1]),I),(lambda p:(p[0],h-1-p[1]),I),(lambda p:p[::-1],I))))
 return~-len(a)

```

Try it online!

The golfed version takes too long to check the nontrivial answers. The version below has a shortcut in the conditional, so you can check that the results up to `(2,4)` are correct.

# Python 3 \+ SymPy, 483 bytes

```
from math import*
from sympy import*
from itertools import*
Q=product
S=Segment
I=tuple
def f(w,h):
 a={1}
 for o in permutations(Q(range(w),range(h))):
  s=[*zip(o,o[1:])]
  if(any(x+X-w+1|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))or any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s)))<1:a.add(min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w-1-p[0],p[1]),I),(lambda p:(p[0],h-1-p[1]),I),(lambda p:p[::-1],I))))
 return~-len(a)

```

Try it online!

## Ungolfed, with comments

```
from math import*
from sympy import*
from itertools import*
def pass_point(p1,p2): # test if the segment passes through another point
 return gcd(p1[0]-p2[0],p1[1]-p2[1]) > 1
def f(w,h):
 pts = [(i,j) for i in range(w) for j in range(h)]
 ans = set()
 for orders in permutations(pts):
  # test if the ordering has 180 degrees rotational symmetry
  if any(x1+x2!=w-1or y1+y2!=h-1for (x1,y1),(x2,y2) in zip(orders, orders[::-1])):continue
  segments = [*zip(orders, orders[1:])]
  # test if a segment passes through another point or two segments intersect
  if any(pass_point(*p)for p in segments)+any(len({*s1,*s2})==4and intersection(Segment(*s1),Segment(*s2))for s1 in segments for s2 in segments):continue
  # take minimum of 8 possible rotations/reflections
  flipH = lambda p:(w-1-p[0],p[1]); flipV = lambda p:(p[0],h-1-p[1]); flipD = lambda p:p[::-1]; nop = lambda p:p
  flipmin = min(tuple(map(lambda o:d(h(v(o))),orders))for h in (flipH,nop)for v in (flipV,nop) for d in (flipD, nop))
  ans.add(flipmin)
 print(len(ans))

```

Try it online!

SymPy has Geometry module that includes an intersection checker `intersection` that works for line segment `Segment` objects. This is much shorter than rolling a hand-written intersection checker based on coordinates. The `intersection` of two `Segment`s is either an empty array (if they don't intersect) or an array that contains a single object (either `Point` or `Segment`, depending on the input).

---
Tags: code-golf, geometry, combinatorics, grid
---


title: A guess the word game

text:
# Question
Title: A guess the word game
# A guess the word game

The agreed dictionary. All words are 6 letters long with all letters distinct

Rules: This is a game of two players and the task will be to implement Player 2.

Player 1 chooses a word from the agreed dictionary

Player 2 repeatedly guesses a word from the agreed dictionary.

At each turn, Player 1 tells Player 2 how many letters the guess has in common with the secret word. For example, `youths` and `devout` have three letters in common.

# Goal

Player 2's goal is to guess the word in as few turns as possible.

# Task

The task is to implement player 2 to minimize the maximum number of guesses they ever have to make. Your score is the maximum number of guesses made when considered over all the words in the agreed dictionary. A lower score is better.

You should test your code by choosing each word from the agreed dictionary in turn and see how many guesses your implementation of Player 2 needs. You should then output the maximum.

# Objective winning criteria

Answers will first be compared by the score they get using the rules above. Two answers with the same score will then be compared using rules. That is by the number of bytes in the code.

# Answer
# Ruby, 418 bytes, score 12 (on 'palest')

```
$dict = File.readlines('agreeddict.txt').map(&:chomp)

def search(wrd)
  words = 0
  fdic = $dict.clone
  guess = ''
  starters = ['earths','blowup','coding']

  chs = wrd.chars

  while guess!=wrd do
    guess = starters.pop || fdic.pop
    words += 1
    ghs = guess.chars
    chars = (chs|ghs).size
    fdic.select!{|w|(w.chars|ghs).size == chars}
  end

  words
end

upp = 0;

p $dict.map{|w|
  [search(w),w]
}.max

```

Try it online!

Runs in 15 seconds on my machine.

TIO link for reference only - does not work if the file is not in the current directory.

### The trick

Instead of brute-force elimination, try a list of initializers first. A lot of words differ by only 1 character and it's easy to get stuck in a single-letter elimination loop.

The most difficult words to guess are those with 4-5 very common characters (a e r s t), 1-2 'outsiders' (c p x z...) and some anagrams in the dictionary.

For example, when we reach a word containing the letters "a e r s t" and the answer is 5: if we just filter all the entries containing these 5 characters, we are left with a dictionary of 40 similar words, and then we have to try almost all of them, removing only a few words at each step.

We need to remove these words first, and we filter on the least common character, so if we get to "earths", and Player 1 answers 5, we don't have a lot of words to check. The first 2 words we always check are "coding" and "blowup" (no pun intended).

Now we can try with a word containing the 5 most common letters ("earths"). If the answer is 4 or 5 (which is likely), we don't have a lot of words to choose from, because we already filtered all the words containing only 1 or 2 uncommon letters (and we only used 3 guesses to get here).

Finding the right initializers was a little tricky, I started with a list of 5 "quasi orthogonal" words (with as few letters as possible in common, a good start was "sporty fuzing hawked climax jumble", missing only the letter z) and got to 13, then started a test on automatically generated smaller lists.

'palest' seems to be a worst case, having 6 anagrams and 4 very common letters, but it's not the only word requiring 12 guesses, so I don't think I could get a better score with this approach.

I don't want to golf this.
> 5 votes

# Answer
# Python 3.8, 730 bytes, score 13

```
p='https://gist.github.com/lesshaste/775f70d4da6778807ff9a8a42c293169/raw/c36b8d3b3d501106de781cb2c3b4c8f6e9d47b33/agreeddict.txt'
from urllib.request import urlopen as o
w=str(o(p).read(),encoding='utf-8').split('\n')
from collections import*
g=lambda x:lambda s:len(set(x)&set(s))
s=dict()
for x in w:
	f=g(x) #the answer function from Player 1. Nothing else knows x
	y=w[:] #init the word set
	c=0 #tries counter
	wd='muting'
	while len(set(frozenset(i) for i in y))>1: #till we have only one set of letters
		c+=1
		m=f(wd)
		y=[i for i in y if len(set(i)&set(wd))==m] #filter words
		#print('%2d'%c,wd,'answer:%d'%m,'variants left:%4d'%len(y))
		d=dict()
		for i in y:
			r=Counter(len(set(i)&set(j)) for j in y)
			d[i]=max(r.items(),key=lambda x:x[1])
			#-math.log(d[i]/len(y),2) is the info in worst case
		wd=min(d.items(),key=lambda x:x[1][1])[0]
	s[x]=(c,len(y))
	assert set(y[0])==set(x)
	print(x,c,len(y),flush=True)
print(max(sum(i) if i[1]!=1 else i[0] for i in s.values()))

```

Try it online! (doesn't seem to work, you can download it from there and run with `python3` (likely 3-4 hours)) -- the result is here.
The working version with `5` first words+`['palest','extras','orates']` for shorter amount of time (with words-list lzma-compressed).

At every step we choose such word from the list of words left, as even the worst answer form Player 1 gives us the most of information over all worst cases. We need `~11.77` bits of information.
Output is word, number of tries to get set of letters, number of words with such set.
The maximum:

```
 1 muting answer:1 variants left:1149
 2 charts answer:4 variants left: 133
 3 alerts answer:5 variants left:  32
 4 averts answer:5 variants left:  19
 5 prates answer:5 variants left:  16
 6 rawest answer:5 variants left:  13
 7 skater answer:5 variants left:  10
 8 stared answer:5 variants left:   7
 9 barest answer:5 variants left:   5
10 faster answer:5 variants left:   3
11 ersatz answer:5 variants left:   2
12 extras answer:5 variants left:   1
orates 12 1

```

(compared with "palest")

```
 1 muting answer:1 variants left:1149
 2 charts answer:3 variants left: 344
 3 dactyl answer:3 variants left: 102
 4 adepts answer:5 variants left:  18
 5 basted answer:4 variants left:  11
 6 palest answer:6 variants left:   6

```
> 4 votes

# Answer
# Haskell, haven't bothered to golf, 14

If I can get down to 13, I'll try to golf this, but I don't have time right now:

```
{-# LANGUAGE TemplateHaskell #-}
module Main where

import Control.Monad.State.Lazy
import Control.Lens
import Data.List (intersect)
import System.Environment
import Text.Printf

data World = World { _wDictionary :: [String]
                   , _wAnswer     :: String
                   , _wScore      :: Int
                   }
makeLenses ''World

main :: IO ()
main = do [answer]   <- getArgs
          dictionary <- fmap lines getContents
          let score   = evalState solve $ World dictionary answer 0
          putStrLn $ printf "Correctly guessed answer %s in %d attempts" answer score

solve :: State World Int
solve = do word   <- uses wDictionary head
           result <- guess word
           if result == 6
           then use wScore
           else do wDictionary %= filter ((== result) . length . intersect word)
                   solve

guess :: String -> State World Int
guess word = do wScore += 1
                uses wAnswer $ length . intersect word

```

Words scoring 14 are "streak", "skater", and "takers." I can't add TIO because it doesn't have the lens package.
> 4 votes

---
Tags: code-challenge
---


title: Tips for golfing in Clojure

text:
# Question
Title: Tips for golfing in Clojure
What are your tips for code golfing using Clojure?

The aim of this question is to collect a list of techniques that are specific to Clojure and can be used in general code-golfing problems.

# Answer
> 6 votes
Use reader syntax for lambdas.
So use

```
#(+ % %2 %3)

```

instead of

```
(fn [x y z] (+ x y z))

```

You can also eliminate whitespace some of the time:

```
#(if (< % 0) (- %) %)
#(if(< % 0)(- %)%)

```

# Answer
> 5 votes
# Where you can remove whitespace:

* Between a string and anything else:

```
(println(+"Hello, World!"1))

```
* Between brackets and anything else:

```
(for[x(range 5)](* x x))

```
* Between a number and everything other than builtins or variable names:

```
Allowed:
(+ 1"Example")
(map{1"-1"2"-2"}[1 2 3])

Not allowed:
(+1 2)

```
* Between `@` (dereference for atoms) and brackets.

# Answer
> 3 votes
**Strings can be treated as a sequence of chars**

e.g. to sort the characters in a string alphabetically:

```
(sort "hello")
=> (\e \h \l \l \o)

```

# Answer
> 2 votes
# Use `nth ... 0` instead of `first`

To get the first element of a collection, using `(nth ... 0)` over `first` saves a byte:

```
(first[2 3 4]): 14 bytes
(nth[2 3 4]0): 13 bytes (saves a byte!)

```

# Answer
> 2 votes
# Use maps instead of `if`s when testing for equality

```
;; if n=3 then A else B
(if (= 3 n) A B) ; (if(=3n)AB)
({3 A} n B)      ; ({3A}nB) -> -3 chars

;; if n=2 or n=3 then A else B
(if (#{2 3} n) A B) ; (if(#{23}n)AB)
({2 A 3 A} n B)     ; ({2A3A}nB) -> -4 chars

```

# Answer
> 1 votes
# Use apply instead of reduce

For example `#(apply + %)` is one byte shorter than `#(reduce + %)`.

# Answer
> 1 votes
## Bind long function names at let to a single-byte symbol

For example if you need to use `partition` or `frequencies` multiple times, it could be beneficial to bind them to a single-byte symbol in a `let` macro. Then again it might not be worth it if you don't need the `let` otherwise, and the function name is relatively short.

# Answer
> 1 votes
## Avoid let if you already have a for

For example: `#(for[a[(sort %)]...)` instead of `#(let[a(sort %)](for ...))`.

For does also have a `:let` construct but it is too verbose for code golf.

# Answer
> 1 votes
# Use `+` and `-` instead of `inc` and `dec`

This saves 1 byte if you're using `inc`/`dec` on an expression with parens:

```
(inc(first[1 3 5]))
(+(first[1 3 5])1)

```

# Answer
> 0 votes
# Use for instead of map

For instance `#(for[i %](Math/abs i))` is a lot shorter than the `map` equvalent.

---
Tags: code-golf, tips, lisp
---


title: What is my volume?

text:
# Question
Title: What is my volume?
Given an input integer, output the volume corresponding to the value. The value will always be in the range \\$\[0,100\]\\$.

## Examples

If the input \\$=0\\$:

```
 _/|
|  |\/
|_ |/\
  \|

```

If the input \\$\>0\\$ and \\$\<33\\$:

```
 _/|
|  |\
|_ |/
  \|

```

If the input \\$\ge33\\$ and \\$\<66\\$:

```
 _/| \
|  |\ \
|_ |/ /
  \| /

```

If the input \\$\ge66\\$, \\$\le100\\$:

```
 _/| \ \
|  |\ \ \
|_ |/ / /
  \| / /

```

## Rules

* Input/output can be given by any convenient method.
* You can print it to STDOUT or return it as a function result.
* Either a full program or a function are acceptable.
* Any amount of extraneous whitespace is permitted, provided the characters line up appropriately.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 15 votes
# JavaScript (ES6), 98 bytes

```
n=>` _/|2
|  |\\0
|_ |/1
  \\|3`.replace(/\d/g,k=>n?(k&1?' /':' \\').repeat(n/33^n>98):['/\\'[k]])

```

Try it online!

### How?

We use the following template:

```
 _/|2
|  |\0
|_ |/1
  \|3

```

If \\$n=0\\$ (volume muted):

* \\$0\\$ is replaced with `/` and \\$1\\$ is replaced with `\`
* the other digits are removed

If \\$n\neq 0\\$:

* odd digits are replaced with the string `" /"` repeated \\$k\\$ times
* even digits are replaced with the string `" \"` repeated \\$k\\$ times

where \\$k\\$ is defined as:

$$k=\cases{\left\lfloor n/33\right\rfloor&\text{$n\<99$}\\ 2&\text{$n\ge 99$} }$$

# Answer
> 7 votes
# 05AB1E, ~~65~~ 64 bytes

```
„ /SõD‚„\ Â‚D4δ∍D)T•4aÖ™é•“| 0\
1/“ÅвJrI33÷IĀ+©è‡∊'_1•uтÄ•22в®è‚ǝ

```

When I started I thought I would be able to make this pretty short with the approach I had in mind, but it had some annoying edge cases to fix.. Can definitely be golfed, though. Will take another look later on.

Try it online or verify some more test cases.

**Explanation:**

```
„ /              # Push string " /"
   S             # Convert it to a list of characters: [" ","/"]
õD‚              # Push an empty string "", duplicate it, and pair them together: ["",""]
„\               # Push string "\ "
   Â             # Bifurcate it (shorter for duplicate and reverse copy)
    ‚            # Pair them together: ["\ ","\ "]
D                # Duplicate it
 4δ∍             # Extend both inner strings to size 4: ["\ \ ","\ \ "]
D                # Duplicate it
)                # Wrap all lists on the stack into a list:
                 #  [[" ","/"],["",""],["\ ","\ "],["\ \ ","\ \ "],["\ \ ","\ \ "]]
T                # Push 10
•4aÖ™é•          # Push compressed integer 17523821317
“| 0\
1/“              # Push string "| 0\\n1/"
   Åв            # Convert the integer to custom base-"| 0\\n1/"
     J           # And join these characters together to a single string:
                 #  "  /| 1\n
                 #   |  |\0"
r                # Reverse the items on the stack (list, 10, string to string, 10, list)
 I33÷            # Push the input, and integer-divide it by 33
     IĀ          # Push the input again, and truthy it (0 if 0; else 1)
       +         # And add them together (0→0; 1..32→1; 33..65→2; 66..98→3; 98..100→4)
        ©        # Store it in variable `®` (without popping)
         è       # And index it into the list we created at the start
          ‡      # Then transliterate the ["1","0"] of 10 to the strings in this pair
∊                # Now vertically mirror the entire string
                 #  (i.e. "  /|  \n
                 #         |  |\/" becomes:
                 #   "  /|  \n
                 #    |  |\/\n
                 #    |  |/\\n
                 #      \|  "
    •/Tδ•        # Push compressed integer 7095187
         ₂в      # Converted to base-26 as list: [15,13,17,21,21]
           ®     # Push variable `®` again
            è    # Index it into this list
   1         ‚   # Pair it with a leading 1
 '_           ǝ '# And insert a "_" at those 0-based positions inside the string
                 # (after which the result is output implicitly)

```

See this 05AB1E tips of mine (section *How to compress large integers?* and *How to compress integer lists?*) to understand why `•4aÖ™é•` is `17523821317`; `•/Tδ•` is `7095187`, and `•/Tδ•₂в` is `[15,13,17,21,21]`.

# Answer
> 6 votes
# Python 2, ~~111~~ ~~101~~ 90 bytes

```
n=input()
for s in'\ _/|','\|  |\/','/|_ |/\\','/  \|':print s[1:6+0**n],s[:n>32],s[:n/66]

```

Try it online!

<sub>-11 bytes, thanks to xnor</sub>

# Answer
> 6 votes
# Lua, ~~308 259 246 242 219~~ 180 bytes

```
i=io.read("*n")
print(i<1 and[[ _/|
|  |\/
|_ |/\
  \|]]or i<33 and[[ _/|
|  |\
|_ |/
  \|]]or i<66 and[[ _/| \
|  |\ \
|_ |/ /
  \| /]]or[[ _/| \ \
|  |\ \ \
|_ |/ / /
  \| / /]])

```

Try it online!

New to code golf and coding in general.
Thanks to all comments for their help!

# Answer
> 3 votes
# PowerShell, 113 bytes

```
param($n)' _/|'+($y=' \'*($x=($n-ge33)+($n-ge66)))
'|  |\'+($y,'/')[!$n]
'|_ |/'+(($z=' /'*$x),'\')[!$n]
"  \|$z"

```

Try it online!

# Answer
> 2 votes
# Perl 5 (`-p`), 86 bytes

inspired from @Arnauld's solution

```
$_=' _/|3
|  |\\1
|_ |/0
  \|2'=~s,\d,$_?" $&"x($_/33-$_/99):$&<2&&$&^1,ger;y;0213;//\

```

Try it online!

# Answer
> 2 votes
# Charcoal, 40 bytes

```
ＮθＦ AＦ›θ℅ι \Ｃ¹¦¹⸿\Ｆ¬θ/‖Ｍ↓⸿←Ｐ↑⁴←↖¹←_↑² _/

```

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

```
Ｎθ

```

Input the volume.

```
Ｆ AＦ›θ℅ι \

```

Output a space and a `\` for each character ordinal in space and `A` that the volume is greater than. In other words, output once for inputs of 33 or more and twice for inputs of 66 or more.

```
Ｃ¹¦¹

```

Copy the `\`s one square diagonally.

```
⸿\

```

Output an extra `\` at the start of the second line.

```
Ｆ¬θ/

```

If the volume was zero then add a `/`.

```
‖Ｍ↓

```

Reflect to complete the volume.

```
⸿←Ｐ↑⁴←↖¹←_↑² _/

```

Draw the speaker symbol.

# Answer
> 2 votes
# PowerShell, ~~94~~ 92 bytes

```
param($n)33,66-le$n|%{$y+=' \';$z+=' /'}
" _/|$y
|  |\$y"+'/'*!$n
"|_ |/$z"+'\'*!$n
"  \|$z"

```

Try it online!

# Answer
> 2 votes
# Canvas, ~~32~~ ~~27~~ 26 bytes

```
┤＃Mi‾‟⁸？⁸‾｛÷ｕ２ｍ２＼×＋］ ¶/＋｝═

```

Try it here!

# Answer
> 2 votes
# Keg, `-hd` 167 bytes

```
¿:0=[` _/|\n|  |\\/\n|_ |/\\\n  \\|`|:1\!"∂[` _/|\n|  |\\\n|_ |/\n  \\|`|:\!B"∂[` _/| \\\n|  |\\ \\\n|_ |/ /\n  \\| /`|` _/| \\ \\\n|  |\\ \\ \\\n|_ |/ / /\n  \\| / /`

```

Try it online!

Definitely golfable by using variables and string formatting. That's what Imma go do now. Anyhow, it acts as a sort of switch statement to determine which range the volume is in and prints the corresponding string.

Nevermind. Variables only make the program longer.

# Answer
> 1 votes
# Python 3, 109 bytes

```
lambda n:'\n'.join(i[:5+0**n]+(n//33*(' '+j))[:4]for i,j in zip([' _/|','|  |\\/','|_ |/\\','  \|'],'\\\//'))

```

Try it online!

# Answer
> 0 votes
# Lua, 196 bytes

```
i=tonumber(io.read())
t=[[ _/|%s
|  |\%s
|_ |/%s
  \|%s]]
t=(i==0 and t:format("","/","\\","")) or t
while i>=33 do t=t:format(" \\%s"," \\%s"," /%s"," /%s");i=i-34 end
t=t:gsub("%%s","")
print(t)

```

Try it online!

A bit shorter (below 200) than the other Lua answer.

---
Tags: code-golf, string, ascii-art
---


title: Unique magic triplets

text:
# Question
Title: Unique magic triplets
## Description

Your input is a list of integers \\$\[a\_1, \dots, a\_n\]\\$.

A **magic triplet** is a triplet \\$(a\_i, a\_j, a\_k)\\$ of values from this list, such that

* the indices \\$\\{i, j, k\\}\\$ are all distinct,
* the values are in ascending order (\\$a\_i \leq a\_j \leq a\_k\\$), and
* the sum of two of the values equals the third.

Your task is to output all *unique* magic triplets, in any order.

## Rules

1. Each number in the input list is guaranteed to be in the range \\$-2^{32} \leq a \< 2^{32}\\$.
2. The input list's length is guaranteed to be at most 1000.
3. The input list's length may be less than 3 (even 0). In this case, there are no magic triplets, and your program should produce an empty result.
4. The shortest answer in bytes wins.

## Test cases

```
[1,2,3,2,4] -> [[1,2,3], [1,3,4], [2,2,4]]
[0,0,0,0] -> [[0,0,0]]
[1,0,-1] -> [[-1,0,1]]
[1,2] -> []
[1,2,4,8,99] -> []
[33,90,7,24,60,32,80,43,15,40,36,90,65,12,91,33,88,1,96,33,40] -> [[7,33,40], [32,33,65], [1,32,33], [1,90,91], [7,36,43], [24,36,60], [12,24,36], [36,60,96], [15,65,80], [40,40,80]]

```

### Notes

* In the second test case, `[[0,0,0], [0,0,0]]` is not a valid answer. No triplet may be listed twice in the output.
* Remember that your program may order the triplets differently. For example, `[[2,2,4], [1,2,3], [1,3,4]]` is also a valid output for the first test case.
* Nonetheless, `[[4,2,2], …]` is invalid: each triplet *itself* must be in ascending order.

# Answer
# Ruby, ~~46 51~~ 58 bytes

```
->l{l.permutation(3).select{|a,b,c|a+b==c}.map(&:sort)|[]}

```

Try it online!

Ok, not so straightforward, but now seems to work.
> 9 votes

# Answer
# 05AB1E, ~~11~~ ~~10~~ ~~9~~ 10 bytes

```
{æ3ùêʒxsOå

```

+1 byte as bugfix for test cases like `[1,0,-1] → [[-1,0,1]] (-1+1=0)` and `[-1,-2,-3] → [[-3,-2,-1]] (-1+-2=-3)`.

Try it online or verify all test cases.

**Explanation:**

```
{           # Sort the (implicit) input-list from lowest to highest value
 æ          # Take the powerset of this sorted list
  3ù        # Only keep inner lists of length 3
    ê       # (Sort and) uniquify this entire list of triplets
     ʒ      # Filter this list of (individually sorted) triplets by:
      x     #  Double each value in the triplet (without popping the triplet itself)
       s    #  Swap to get the original triplet
        O   #  Take the sum of this triplet
         å  #  And check whether this value is in the doubled list
            # (after which the filtered list is output implicitly as result)

```

The last four bytes could alternatively be `œÆ0å` (given by *@Grimy*): Try it online or verify all test cases.

```
      œ     #  Get all possible permutations of the triplet
       Æ    #  Reduce each by subtracting: [a,b,c] → a-b-c
        0å  #  And check if there are any 0s among the reduced permutations

```
> 8 votes

# Answer
# Jelly, 10 bytes

```
Ṣœc3ḤiSƊƇQ

```

Try it online!

```
Ṣ             Sort the input,
 œc3          find all length-3 subsequences,
        Ƈ     filter to only the sets for which
      S       the sum of all three elements
     i        is an element of
    Ḥ  Ɗ      the set with all elements doubled,
         Q    and uniquify.

```
> 6 votes

# Answer
# Brachylog, 11 bytes

```
{o⊇Ṫ.+/₂∈}ᵘ

```

Try it online!

Takes input through the input variable and outputs through the output variable.

```
{        }ᵘ    Output every unique output from:
    .          the output is
  ⊇            a subsequence
   Ṫ           of length 3
{              of the input
 o             sorted
     +         the sum of which
      /₂       divided by 2
        ∈      is an element of
         }     the output.

```
> 5 votes

# Answer
# Japt, ~~13~~ 11 bytes

```
á3 k_r-ÃmÍâ

```

Try it

```
á3 k_r-ÃmÍâ // input as arrays
á3            // all unique permutations
  k_          // save list that..
    r-Ã       // reduced by - from first element
         mÍ   // ==mn   => sort all
              â // remove duplicates

```

Thanks to @Shaggy and @Embodiment of Ignorance for saving 2
> 5 votes

# Answer
# Perl 6, ~~65~~ 64 bytes

```
*.combinations(3)>>.sort.grep({@$_.sum==2*.any}).unique(:as(~*))

```

Try it online!

```
*.combinations(3)               # All the combinations of length 3
                 >>.sort        # Sorted
                        .grep({               }) # Filtered by
                              {@$_.sum==         # The sum is equal to
                                        2*.any   # Double any element
                                                .unique(:as(~*))  # And take the unique lists

```
> 4 votes

# Answer
# JavaScript (Node.js),  ~~118 116~~  115 bytes

Returns a set.

```
a=>new Set(a.flatMap((x,i)=>a.flatMap((y,j)=>j-i&&~(k=a.indexOf(x+y))&&k-i&&k-j?[x,y,x+y].sort((a,b)=>a-b)+'':[])))

```

Try it online!

### Commented

```
a =>                             // a[] = input array
  new Set(                       // create a set:
    a.flatMap((x, i) =>          //   for each value x at position i in a[]:
      a.flatMap((y, j) =>        //     for each value y at position j in a[]:
        j - i &&                 //       if j is not equal to i
        ~(                       //       and the position k
          k = a.indexOf(x + y)   //       of x + y in a[]
        ) &&                     //       is not equal to -1
        k - i &&                 //       and k is not equal to i
        k - j ?                  //       and k is not equal to j:
          [x, y, x + y]          //         build the triplet (x, y, x + y)
          .sort((a, b) => a - b) //         sort it in ascending order
          + ''                   //         and coerce it to a string
        :                        //       else:
          []                     //         yield an empty array
      )                          //     end of inner flatMap()
    )                            //   end of outer flatMap()
  )                              // end of Set()

```
> 4 votes

# Answer
# Python 3, ~~94, 89, 88~~, 85 bytes

One byte saved thanks to frank.

```
lambda l:{p for p in combinations(sorted(l),3)if sum(p)/2in p}
from itertools import*

```

Try it online!
> 4 votes

# Answer
# Haskell, 78 bytes

```
import Data.List
f x=nub[y|y@[a,b,c]<-subsequences$sort x,or[2*z==sum y|z<-y]]

```

Try it online!
> 3 votes

# Answer
# K (oK), 38 bytes

```
{?{x@<x}'({z=x+y}.)#x@/:{x~?x}#+!3##x}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 66 bytes

```
ＦＬθＦＬθＦＬθＦ¬⌈⟦⁼ικ⁼ιλ⁼κλ›§θι§θκ›§θκ§θλ⟧«≔Ｅ⟦ικλ⟧§θνη¿∧№η⊘Ση¬№υη⊞υη»Ｉυ

```

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

```
ＦＬθＦＬθＦＬθＦ¬⌈⟦

```

Loop through all triples of indices...

```
⁼ικ⁼ιλ⁼κλ

```

... checking whether the indices are distinct...

```
›§θι§θκ›§θκ§θλ

```

... and that the triplet is in ascending order...

```
⟧«≔Ｅ⟦ικλ⟧§θνη

```

... if so then save the triplet in a variable...

```
¿∧№η⊘Ση¬№υη⊞υη

```

... and if it contains its halved sum and is unique then remember it in a list.

```
»Ｉυ

```

After checking all triplets output the unique magic triplets double-spaced with each triplet member on its own line.
> 2 votes

# Answer
# Java 10, 225 bytes

```
import java.util.*;L->{var r=new TreeSet();for(int j,k,a,b,t[],i=L.size();i-->0;)for(j=i;j-->0;)if((k=L.indexOf((a=L.get(i))+(b=L.get(j))))>=0&k!=i&k!=j){Arrays.sort(t=new int[]{a,b,a+b});r.add(Arrays.toString(t));}return r;}

```

Port of *@Arnauld*'s JavaScript answer, just twice as long.. \>.\>

Try it online.

**Explanation:**

```
import java.util.*;       // Required import for the TreeSet and both Arrays
L->{                      // Method with integer-List as parameter & sorted Set as return
  var r=new TreeSet();    //  Result-set, starting uninitialized
                          //  A Set will automatically remove duplicates
                          //  (and a TreeSet will automatically sort, which is irrelevant,
                          //   but it's the same size as a regular HashSet anyway)
  for(int j,k,a,b,t[],    //  Temp integers
      i=L.sisze();i-->0;) //  Loop `i` in the range (input-length, 0]:
    for(j=i;j-->0;)       //   Inner loop `j` in the range (`i`, 0]:
      if((k=L.indexOf((a=L.get(i))
                          //    Set `a` to the `i`'th value in the list
          +(b=L.get(j))   //    Set `b` to the `j`'th value in the list
                          //    And add `a` and `b` together
         ))               //    Set `k` to the index of this sum
           >=0            //    If the index `k` is NOT -1
         &k!=i&k!=j){     //    And `k` is also NOT `i` nor `j`:
        Arrays.sort(t=new int[]{a,b,a+b});
                          //     Create an array `t` with items [a,b,a+b],
                          //     and sort the values of this triplet
        r.add(Arrays.toString(t));}
                          //     Then convert this array to a String,
                          //     and add it to the result-TreeSet
  return r;}              //  After the nested loop: return the result-TreeSet

```
> 1 votes

# Answer
# Pyth, 13 bytes

```
{f}csT2T.cSQ3

```

Try it online!

Port of the solution thats been floating around.

## How it works

```
{f}csT2T.cSQ3
        .c  3  - All combinations length 3 of...
          SQ   - The sorted input
 f             - Filtered such that...
   csT2        - Half the sum of each combination...
  }    T       - Is an element of the original combination
{              - Remove duplicates

```

# Pyth, 15 bytes

```
{mSdfqsPTeT.PQ3

```

Try it online!

Less sophisticated solution. Posting it because I think it can be golfed more

## How it works

```
{mSdfqsPTeT.PQ3
           .PQ3 - All 3 element permutations of the input
    f           - Filtered such that
      sPT       - The sum of the first 2 inputs...
     q   eT     - Is equal to the last input
 mSd            - Sort all elements
{               - Remove duplicates

```
> 1 votes

# Answer
### JULIA

A solution w/o external package:

```
F(l)=(n=length(sort!(l));a=Set();
for i=1:n,j=1:n,k=1:n i<j<k&&(v=l[[i,j,k]];sum(v) in 2v)&&push!(a,v)end;
[a...])

```

Not a nice one 115 bytes of code (with 2 extra newlines for readability).

A solution using the non-core package `Combinatorics`:

```
using Combinatorics
H(l)=[Set(v for v in combinations(sort(l),3) if sum(v) in 2v)...]

```

Length 85 bytes (or 84 if you omit the space before the '''if''')
You can REPLIT online.
> 1 votes

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


title: Number that can eat itself

text:
# Question
Title: Number that can eat itself
Given a positive integer, output a truthy/falsy value as to whether the number can eat itself.

### Rules

Leftmost is the head, rightmost is the tail

If the head is greater than or equal to the tail, the head eats the tail and the new head becomes their sum.

If \\$sum \ge 10 \\$ then the head is replaced by \\$sum \mod 10\\$.

\\$sum=0\\$ cannot be ignored, however the input number will never have any leading zeroes.

**Example:**

```
number=2632
head-2, tail-2

2632 -> 463
head-4, tail-3

463 -> 76
head-7, tail-6

76 -> 3
If only one digit remains in the end, the number can eat itself.

```

If at any point the head cannot eat the tail, the answer will be False.

```
number=6724
072
False (0<2)

```

### Test Cases:

```
True:
[2632, 92258, 60282, 38410,3210, 2302, 2742, 8628, 6793, 1, 2, 10, 100, 55, 121]

False:
[6724, 47, 472, 60247, 33265, 79350, 83147, 93101, 57088, 69513, 62738, 54754, 23931, 7164, 5289, 3435, 3949, 8630, 5018, 6715, 340, 2194]

```

This is **code-golf** so shortest code wins.

# Answer
# JavaScript (ES6),  ~~52 51~~  50 bytes

*Saved 1 byte thanks to @tsh*

Takes input as a string. Returns a Boolean value.

```
f=n=>n>[n%10]?f(-(-n[0]-n)%10+n.slice(1,-1)):!n[1]

```

Try it online!

### Commented

```
f = n =>                 // f = recursive function taking n (a string)
  n > [n % 10]           // The last digit is isolated with n % 10 and turned into a
                         // singleton array, which is eventually coerced to a string
                         // when the comparison occurs.
                         // So we do a lexicographical comparison between n and its
                         // last digit (e.g. '231'>'1' and '202'>'2', but '213'<'3').
  ?                      // If the above result is true:
    f(                   //   do a recursive call:
      -(-n[0] - n) % 10  //     We compute (int(first_digit) + int(n)) mod 10. There's no
                         //     need to isolate the last digit since we do a mod 10 anyway.
      + n.slice(1, -1)   //     We add the middle part, as a string. It may be empty.
    )                    //   end of recursive call
  :                      // else:
    !n[1]                //   return true if n has only 1 digit, or false otherwise

```
> 7 votes

# Answer
# Perl 6, ~~63~~ 62 bytes

```
{!grep {.[*-1]>.[0]},(.comb,{.[0,*-1].sum%10,|.[1..*-2]}...1)}

```

Try it online!

### Explanation:

```
{                                                            } # Anonymous code block
                     (                                  ... )       # Create a sequence
                      .comb,  # Starting with the input converted to a list of digits
                            {                          }   # With each element being
                             .[0,*-1]   # The first and last element of the previous list
                                     .sum%10  # Summed and modulo 10
                                            ,|.[1..*-2]   # Followed by the intermediate elements
                                                        ...1 # Until the list is length 1
 !grep   # Do none of the elements of the sequence
       {.[*-1]>.[0]},   # Have the last element larger than the first?

```
> 6 votes

# Answer
# Jelly, 11 bytes

```
Ṛṙ-µṖÄ%⁵:ḊẠ

```

Try it online!

### How it works

```
Ṛṙ-µṖÄ%⁵:ḊẠ  Main link. Argument: n

Ṛ            Reverse n, after casting it to a digit list.
 ṙ-          Rotate the result -1 units to the left, i.e., 1 unit to the right.
             Let's call the resulting digit list D.
   µ         Begin a new chain with argument D.
    Ṗ        Pop; remove the last digit.
     Ä       Accumulate; take the cumulative sum of the remaining digits.
      %⁵     Take the sums modulo 10.
         Ḋ   Dequeue; yield D without its first digit.
        :    Perform integer division between the results to both sides.
             Integer division is truthy iff greater-or-equal is truthy.
          Ạ  All; return 1 if all quotients are truthy, 0 if not.

```
> 6 votes

# Answer
# Java (JDK), 83 bytes

```
n->{int r=0,h=n;while(h>9)h/=10;for(;n>9;h=(h+n)%10,n/=10)r=h<n%10?1:r;return r<1;}

```

Try it online!

## Credits
> 5 votes

# Answer
## Mathematica, 62 bytes

```
0(IntegerDigits@#//.{a_,r___,b_}/;a>=b:>{Mod[a+b,10],r})=={0}&

```

First calls `IntegerDigits` on the input to get a list of its digits, then repeatedly applies the following rule:

```
{a_,r___,b_}       (* match the first digit, 0 or more medial digits, and the last digit... *)
/;a>=b             (* under the condition that the number is edible... *)
:>{Mod[a+b,10],r}  (* and replace it with the next iteration *)

```

The rule is applied until the pattern no longer matches, in which case either there is only one digit left (truthy) or the head is less than the tail (falsy).

Instead of calling `Length[__]==1`, we can save a few bytes with `0(__)=={0}`, multiplying all elements in the list by `0` and then comparing with the list `{0}`.
> 4 votes

# Answer
# Python 2, ~~105~~ ~~82~~ 81 bytes

```
i,x=map(int,input()),1
for y in i[:0:-1]:
 if i[0]%10<y:x=0
 else:i[0]+=y
print x

```

Try it online!

Many thanks for a massive -23 from @ØrjanJohansen

Thanks to @VedantKandoi (and @ØrjanJohansen) for another -1
> 4 votes

# Answer
# Python 3, 50 bytes

First line stolen from Black Owl Kai's answer.

```
p,*s=map(int,input())
while s:*s,k=s;p%10<k>q;p+=k

```

Try it online!

Output is via exit code. Fails (1) for falsy inputs and finishes (0) for truthy inputs.
> 4 votes

# Answer
# Brachylog, 23 bytes

```
ẹ{bkK&⟨h{≥₁+tg}t⟩,K↰|Ȯ}

```

Try it online!

This is a 1 byte save over Fatalize's solution. This uses a recursive approach instead of a iterative

### Explanation

```
ẹ                          Input into a list of digits
 {                    }    Assert that either
  bk                       | the list has at least 2 elements (see later)
      ⟨h{     }t⟩           | and that [head, tail]
         ≥₁                |  | is increasing (head >= tail)
           +               |  | and their sum
            t              |  | mod 10 (take last digit)
             g             |  | as single element of a list
                ,          | concatenated with
  bkK            K         | the number without head and tail (this constrains the number to have at least 2 digits)
                  ↰        | and that this constraint also works on the newly formed number
                   |Ȯ      | OR is a 1 digit number

```
> 4 votes

# Answer
# APL (Dyalog Unicode), 33 bytesSBCS

Anonymous tacit prefix function taking a string as argument.

```
{⊃⍵<t←⊃⌽⍵:0⋄3::1⋄∇10|t+@1⊢¯1↓⍵}⍎¨

```

Try it online!

`⍎¨` evaluate each character (this gives us a list of digits)

`{``}` apply the following "dfn" to that;  is the argument (list of digits):

`⌽⍵` reverse the argument

pick the first element (this is the tail)

`t←` assign to `t` (for **t**ail)

`⍵<` for each of the original digits, see if it is less than that

pick the first true/false

`:` if so:

`0` return false

then:

`3::` if from now on, an index error (out of bounds) happens:

`1` return true

`¯1↓⍵` drop the last digit

yield that (separates `1` and `¯1` so they won't form a single array)

`t+@1` add the tail to the first digit (the head)

`10|` mod-10

recurse

Once we hit a single digit, `¯1↓` will make that an empty list, and `@1` will cause an index error as there is no first digit, causing the function to return true.
> 3 votes

# Answer
# Python 3, 77 bytes

```
p,*s=map(int,input())
print(all(n<=sum(s[i+1:],p)%10for i,n in enumerate(s)))

```

Try it online!

---

And my old solution with a recursive approach

# Python 3, 90 bytes

```
f=lambda x,a=0:2>len(x)if 2>len(x)or(int(x[0])+a)%10<int(x[-1])else f(x[:-1],a+int(x[-1]))

```

Try it online!

Takes input as a string.
> 3 votes

# Answer
# Brachylog, 24 bytes

```
ẹ;I⟨⟨h{≥₁+tg}t⟩c{bk}⟩ⁱ⁾Ȯ

```

Try it online!

I should change 's default behaviour so that it iterates an unknown number of times (currently, it iterates 1 time by default which is completely useless). I then wouldn't need the `[…];I[…]⁾`, saving 3 bytes

### Explanation

This program contains an ugly fork inside a fork. There is also some plumbing needed to work on lists of digits instead of numbers (because if we remove the head and tail of `76` we are left with `0`, which doesn't work contrary to `[7,6]` where we end up with `[]`).

```
ẹ                          Input into a list of digits
                       Ȯ   While we don't have a single digit number…
 ;I                  ⁱ⁾    …Iterate I times (I being unknown)…
   ⟨                ⟩      …The following fork:
               c           | Concatenate…
    ⟨         ⟩            | The output of the following fork:
     h       t             | | Take the head H and tail T of the number
      {     }              | | Then apply on [H,T]:
       ≥₁                  | | | H ≥ T
         +                 | | | Sum them
          tg               | | | Take the last digit (i.e. mod 10) and wrap it in a list
                {  }       | With the output of the following predicate:
                 bk        | | Remove the head and the tail of the number

```
> 3 votes

# Answer
## Haskell, ~~70~~ ~~64~~ 60 bytes

```
f(a:b)=b==""||a>=last b&&f(last(show$read[a]+read b):init b)

```

Input is taken as a string.

Try it online!

Edit: -6 bytes by using @Laikoni's trick of using `||` instead of separate guards. Another -4 bytes thanks to @Laikoni.
> 3 votes

# Answer
# Python 2, ~~75~~ 67 bytes

```
l=lambda n:n==n[0]or n[-1]<=n[0]*l(`int(n[0]+n[-1],11)%10`+n[1:-1])

```

**Try it online!**

Recursive lambda approach. Takes input as a string. Many thanks to Dennis for saving 8 bytes!
> 2 votes

# Answer
# Perl 5, 64 bytes

```
{local$_=pop;1while s/(.)(.*)(.)/$1<$3?'':(($1+$3)%10).$2/e;/./}

```

Try it online!
> 2 votes

# Answer
# Haskell, ~~69~~ 64 bytes

```
f n=read[show n!!0]#n
h#n=n<10||h>=mod n 10&&mod(h+n)10#div n 10

```

Try it online! Example usage: `f 2632` yields `True`.

*Edit:* -5 bytes because `mod (h + mod n 10) 10 = mod (h + n) 10`
> 2 votes

# Answer
# Ruby, 139 bytes

```
->(a){a.length==1?(p true;exit):1;(a[0].to_i>=a[-1].to_i)?(a[0]=(a[-1].to_i+a[0].to_i).divmod(10)[1].to_s;a=a[0..-2];p b[a]):p(false);exit}

```

Try it online! (has some extra code to process input, since it's a function)

Ungolfed code:

```
->(a) do
    if a.length == 1
        p true
        exit
    if a[0].to_i >= a[-1].to_i
        a[0] = (a[-1].to_i + a[0].to_i).divmod(10)[1].to_s
        a = a[0..-2]
        p b[a]
    else
        p false
        exit
    end
end

```
> 2 votes

# Answer
# 05AB1E, ~~26~~ ~~25~~ 24 bytes

```
[DgD#\ÁD2£D`›i0qëSOθs¦¦«

```

Can probably be golfed a bit more.. It feels overly long, but maybe the challenge is in terms of code more complex than I thought beforehand.

Try it online or verify all test cases.

**Explanation:**

```
[                 # Start an infinite loop
 D                #  Duplicate the top of the stack
                  #  (which is the input implicitly in the first iteration)
  gD              #  Take its length and duplicate it
    #             #  If its a single digit:
                  #   Stop the infinite loop
                  #   (and output the duplicated length of 1 (truthy) implicitly)
                  #  Else:
  \               #   Discard the duplicate length
   Á              #   Rotate the digits once towards the left
    D2£           #   Duplicate, and take the first two digits of the rotated number
       D`         #   Duplicate, and push the digits loose to the stack
         ›i       #   If the first digit is larger than the second digit:
           0      #    Push a 0 (falsey)
            q     #    Stop the program (and output 0 implicitly)
          ë       #   Else (first digit is smaller than or equal to the second digit):
           SO     #    Sum the two digits
             θ    #    Leave only the last digit of that sum
           s      #    Swap to take the rotated number
            ¦¦    #    Remove the first two digits
              «   #    Merge it together with the calculated new digit

```
> 1 votes

# Answer
# Retina 0.8.2, 42 bytes

```
\d
$*#;
^((#*).*;)\2;$
$2$1
}`#{10}

^#*;$

```

Try it online! Link include test cases. Explanation:

```
\d
$*#;

```

Convert the digits to unary and insert separators.

```
^((#*).*;)\2;$
$2$1

```

If the last digit is not greater than the first then add them together.

```
#{10}

```

Reduce modulo 10 if appropriate.

```
}`

```

Repeat until the last digit is greater than the first or there is only one digit left.

```
^#*;$

```

Test whether there is only one digit left.
> 1 votes

# Answer
# C++ (gcc), 144 bytes

```
bool f(std::string b){int c=b.length();while(c>1){if(b[0]<b[c-1])return 0;else{b[0]=(b[0]-48+b[c-1]-48)%10+48;b=b.substr(0,c-1);--c;}}return 1;}

```

Try it online!

First time I'm trying something like this so if I formatted something wrong please let me know. I'm not 100% sure on the rules for stuff like using namespace to eliminate the 5 bytes "std::" so I left it in.

Ungolfed:

```
bool hunger(std::string input)
{
    int count=input.length();
    while (count>1)
    {
        if (input[0]<input[count-1])                         //if at any point the head cannot eat the tail we can quit the loop
                                                             //comparisons can be done without switching from ascii
        {
            return false;
        }
        else
        {
             input[0]=(input[0]-48+input[count-1]-48)%10+48; //eating operation has to occur on integers so subtract 48 to convert from ASCII to a number
             input=input.substr(0,count-1);                  //get rid of the last number since it was eaten
             --count;
        }

    }
    return true;                                             //if the end of the loop is reached the number has eaten itself
}

```
> 1 votes

# Answer
# C#, 114 bytes

```
static bool L(string n){return n.Skip(1).Reverse().Select(x=>x%16).Aggregate(n[0]%16,(h,x)=>h>=x?(h+x)%10:-1)>=0;}

```

Try it online
> 1 votes

# Answer
# C (gcc) *(with string.h)*, ~~110~~ 108 bytes

```
c;f(char*b){c=strlen(b);if(!c)return 1;char*d=b+c-1;if(*b<*d)return 0;*b=(*b+*d-96)%10+48;*d=0;return f(b);}

```

Try it online!

Still relatively new to PPCG, so the correct syntax for linking libraries as a new language is foreign to me. Also note that the function returns 0 or 1 for false/true, and printing that result to stdout does require stdio. If we're being pedantic and the exercise requires output, the language requires *stdio* that as well.

Conceptually similar to @BenH's answer, but in C, so kudos where they are due (Welcome to PPCG, btw), but using recursion. It also uses array pointer arithmetic, because dirty code is shorter than clean code.

The function is tail recursive, with exit conditions if the first number can't eat the last or the length is 1, returning false or true, respectively. These values are found by dereferencing a pointer to the C-String (which gives a char) at the beginning and end of the string, and doing the comparisons on them. pointer arithmetic is done to find the end of the string. finally, the last char is "erased" by replacing it with a null terminator (0).

It's possible that the modulus arithmetic could be shortened by a byte or two, but I already need a shower after that pointer manipulation.

Ungolfed Version Here

Update: Saved two bytes by replacing c==1 with !c. This is essentially c == 0. It will run an additional time, and will needlessly double itself before deleting itself, but saves two bytes. A side effect is null or zero length strings won't cause infinite recursion (though we shouldn't get null strings as the exercise says positive integers).
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 69 bytes

```
x=>{for(int h=x[0],i=x.Length;i>1;)h=h<x[--i]?h/0:48+(h+x[i]-96)%10;}

```

Try it online!

Success or failure is determined by presence or absence of an exception. Input is in the form of a string.

Less golfed...

```
// x is the input as a string
x=>{
  // h is the head
  for(int h=x[0],
    // i is an index to the tail
    i=x.Length;
    // continue until the tail is at 0
    i>1;)
      // is head smaller larger than tail?
      h=h<x[--i]
        // throw an exception
        ?h/0
        // calculate the next head
        :48+(h+x[i]-96)%10;
}

```

There are a couple extra bytes to deal with converting between characters and digits, but overall that didn't affect the size too much.
> 1 votes

# Answer
# Powershell, 89 bytes

```
"$args"-notmatch'(.)(.*)(.)'-or(($m=$Matches).1-ge$m.3-and(.\g(''+(+$m.1+$m.3)%10+$m.2)))

```

Important! The script calls itself recursively. So save the script as `g.ps1` file in the current directory. Also you can call a script block variable instead script file (see the test script below). That calls has same length.

Note 1: The script uses a lazy evaluation of logic operators `-or` and `-and`. If `"$args"-notmatch'(.)(.*)(.)'` is `True` then the right subexpression of `-or` is not evaluated. Also if `($m=$Matches).1-ge$m.3` is `False` then the right subexpression of `-and` is not evaluated too. So we avoid infinite recursion.

Note 2: The regular expression `'(.)(.*)(.)'` does not contain start and end anchors because the expression `(.*)` is greedy by default.

## Test script

```
$g={
"$args"-notmatch'(.)(.*)(.)'-or(($m=$Matches).1-ge$m.3-and(&$g(''+(+$m.1+$m.3)%10+$m.2)))
}

@(
    ,(2632, $true)
    ,(92258, $true)
    ,(60282, $true)
    ,(38410, $true)
    ,(3210, $true)
    ,(2302, $true)
    ,(2742, $true)
    ,(8628, $true)
    ,(6793, $true)
    ,(1, $true)
    ,(2, $true)
    ,(10, $true)
    ,(100, $true)
    ,(55, $true)
    ,(121, $true)
    ,(6724, $false)
    ,(47, $false)
    ,(472, $false)
    ,(60247, $false)
    ,(33265, $false)
    ,(79350, $false)
    ,(83147, $false)
    ,(93101, $false)
    ,(57088, $false)
    ,(69513, $false)
    ,(62738, $false)
    ,(54754, $false)
    ,(23931, $false)
    ,(7164, $false)
    ,(5289, $false)
    ,(3435, $false)
    ,(3949, $false)
    ,(8630, $false)
    ,(5018, $false)
    ,(6715, $false)
    ,(340, $false)
    ,(2194, $false)
) | %{
    $n,$expected = $_
   #$result = .\g $n   # uncomment this line to call a script file g.ps1
    $result = &$g $n   # uncomment this line to call a script block variable $g
                       # the script block call and the script file call has same length
    "$($result-eq-$expected): $result <- $n"
}

```

Output:

```
True: True <- 2632
True: True <- 92258
True: True <- 60282
True: True <- 38410
True: True <- 3210
True: True <- 2302
True: True <- 2742
True: True <- 8628
True: True <- 6793
True: True <- 1
True: True <- 2
True: True <- 10
True: True <- 100
True: True <- 55
True: True <- 121
True: False <- 6724
True: False <- 47
True: False <- 472
True: False <- 60247
True: False <- 33265
True: False <- 79350
True: False <- 83147
True: False <- 93101
True: False <- 57088
True: False <- 69513
True: False <- 62738
True: False <- 54754
True: False <- 23931
True: False <- 7164
True: False <- 5289
True: False <- 3435
True: False <- 3949
True: False <- 8630
True: False <- 5018
True: False <- 6715
True: False <- 340
True: False <- 2194

```

---

# Powershell, 90 bytes

No recursion. No file name dependency and no script block name dependency.

```
for($s="$args";$s[1]-and$s-ge$s%10){$s=''+(2+$s[0]+$s)%10+($s|% S*g 1($s.Length-2))}!$s[1]

```

A Powershell implicitly converts a right operand to a type of a left operand. Therefore, `$s-ge$s%10` calculates right operand `$s%10` as `integer` and compare it as a `string` because type of the left operand is `string`. And `2+$s[0]+$s` converts a char `$s[0]` and string `$s` to `integer` because left operand `2` is integer.

`$s|% S*g 1($s.Length-2)` is a shortcut to `$s.Substring(1,($s.Length-2))`
> 1 votes

# Answer
# Perl 5 `-pF`, 53 bytes

```
$F[0]=($F[0]+pop@F)%10while$#F&&$F[0]>=$F[-1];$_=!$#F

```

Try it online!
> 1 votes

# Answer
# Brachylog, 18 bytes

```
ẹ⟨k{z₁{≥₁+t}ᵐ}t⟩ⁱȮ

```

Try it online!

Takes three bytes off Fatalize's solution just by virtue of non-deterministic superscriptless  existing now, but loses another three by doing vaguely Jelly-inspired things with `z₁` to avoid using `c`, `g`, or even `h`. (Also inspired by trying, and failing, to use a different new feature: the `ʰ` metapredicate.)

```
                 Ȯ    A list of length 1
                ⁱ     can be obtained from repeatedly applying the following
ẹ                     to the list of the input's digits:
 ⟨k{         }t⟩      take the list without its last element paired with its last element,
    z₁                non-cycling zip that pair (pairing the first element of the list with
                      the last element and the remaining elements with nothing),
      {    }ᵐ         and for each resulting zipped pair or singleton list:
       ≥₁             it is non-increasing (trivially true of a singleton list);
          t           take the last digit of
         +            its sum.

```
> 1 votes

# Answer
# PowerShell, ~~94~~ 91 bytes

```
for(;$n-and$n[0]-ge$n[-1]){$n=$n-replace"^.",((+$n[0]+$n[-1]-96)%10)-replace".$"}return !$n

```

Try it online!

---

## Test Script

```
function f($n){

for(;$n-and$n[0]-ge$n[-1]){$n=$n-replace"^.",((+$n[0]+$n[-1]-96)%10)-replace".$"}return !$n

Remove-Variable n
}
Write-Host True values:
@(2632, 92258, 60282, 38410,3210, 2302, 2742, 8628, 6793, 1, 2, 10, 100, 55, 121) |
    % { Write-Host "  $_ $(' '*(6-$_.ToString().Length)) $(f $_.ToString())" }

Write-Host False values:
@(6724, 47, 472, 60247, 33265, 79350, 83147, 93101, 57088, 69513, 62738, 54754, 23931, 7164, 5289, 3435, 3949, 8630, 5018, 6715, 340, 2194) |
    % { Write-Host "  $_ $(' '*(6-$_.ToString().Length)) $(f $_.ToString())" }

```

## Ungolfed code:

```
function f ($inVar){
    # While the Input exists, and the first character is greater than last
    while($inVar -and ($inVar[0] -ge $inVar[-1])){

        # Calculate the first integer -> ((+$n[0]+$n[-1]-96)%10)
        $summationChars = [int]$inVar[0]+ [int]$inVar[-1]
        # $summationChars adds the ascii values, not the integer literals.
        $summationResult = $summationChars - 48*2
        $summationModulo = $summationResult % 10

        # Replace first character with the modulo
        $inVar = $inVar -replace "^.", $summationModulo

        # Remove last character
        $inVar = $inVar -replace ".$"
    }
    # Either it doesn't exist (Returns $True), or
    # it exists since $inVar[0] < $inVar[-1] returning $False
    return !$inVar
}

```
> 0 votes

---
Tags: code-golf, decision-problem
---


title: Exploding Primes

text:
# Question
Title: Exploding Primes
At the time of writing this puzzle, there are soon to be 269 puzzles related to primes. To celebrate/mourn this event (269 is prime), this challenge will be about exploding primes. In preparation for this task, I've obtained a permit (legal, I assure you) for dynamite charges of military grade, along with enormous dynamite itself. Unfortunately, I also have a lot of junk in my warehouse, and I've packaged everything (and I mean *everything*) into ASCII text.

From sizes 1 to 6 (actual input sizes can be arbitrarily large), here are examples of my enormous dynamite:

```
                             +
                          ___L__
                     +   |      |
                   __L__ |      |
               +  |     ||      |
             __L_ |     ||      |
         +  |    ||     ||      |
        _L_ |    ||     ||      |
     + |   ||    ||     ||      |
    _L |   ||    ||     ||      |
 + |  ||   ||    ||     ||      |
 L |  ||   ||    ||     ||      |
| ||  ||   ||    ||     ||      |
|_||__||___||____||_____||______|
                                                                  __________________
                                               _______________   |                  |
                               ____________   |               |  |                  |
                  _________   |            |  |               |  |                  L-*
        ______   |         |  |            L-*|               L-*|                  |
 ___   |      L-*|         L-*|            |  |               |  |                  |
|___L-*|______|  |_________|  |____________|  |_______________|  |__________________|

```

The pattern for size `n` vertical dynamite is two `2n`-high columns of `|` separated by `n` spaces in the middle/`_`s on the bottom and top. The bottom `_`s will be surrounded by `|`s, but the top `_`s will be surrounded by spaces. There will be an `L` under a `+` replacing the mid-point (biased right) of the top `_`s.
The pattern for size `n` horizontal dynamite is two `n`-wide rows of `_` separated by `n-1` space-filled rows in the middle. There will be `n+1`-high columns on the left and right, out of which the top character will be a space, and others will be `|`. There will be an `L` with a `*` on the right replacing the mid-point (biased upwards) of the right `|`s.

As my best and brightest assistant, you will need to help me determine how many primes each ASCII package (input grid) can destroy. Your task is to count all the valid dynamite within a package, taking into account the size. You will output a string like so: `BOOM! # prime(s) primed for destruction`, where `#` is the total computed dynamite size in the package.

# Examples

```
Input:
 ______
|      L-*
|______|
Output:
BOOM! 2 prime(s) primed for destruction
Reasoning:
Single piece of dynamite of size 2

Input:
Output:
BOOM! 0 prime(s) primed for destruction
Reasoning:
Empty string contains no dynamite

Input:
   __+_
   \_|_\
   /_|_/
  ___L___
~~\_____/~~
Output:
BOOM! 0 prime(s) primed for destruction
Reasoning:
Despite being cute and non-empty, this ASCII ship from my warehouse has no dynamite in it

Input:
 ____________
|            |
|    ___     L-*
|   |___L-*  |
|____________|
Output:
BOOM! 1 prime(s) primed for destruction
Reasoning:
Dynamite is non-recursive - the outer dynamite doesn't count at all,
but the inner dynamite is valid and will blow up 1 prime.

Input:
 +
 L
| |
|_|
Output:
BOOM! 0 prime(s) primed for destruction
Reasoning:
A space character is missing to the right of the L - the box must be
fully complete, although the + for vertical and -* for horizontal dynamite
are not necessarily space-padded; all that is required for those elements
is that they be aligned with the L.

Input:
                     +
                   __L__
                + |     |
             __L_ |     |
         +  |    ||     | _____________________
        _L_ |    ||     ||                     |
     + |   ||    ||     ||                     |
    _L |   ||    ||     ||                     |
 + |  ||   ||    ||     ||                     L-*
 L |  ||   ||    ||     ||                     |
| ||  ||   ||    ||     ||                     |
|_||__||___||____||_____||_____________________|
Output:
BOOM! 18 prime(s) primed for destruction
Reasoning:
The size-4 dynamite is malformed, but all the other pieces of dynamite
are valid. Summing the dynamite sizes within this package yields
1 + 2 + 3 + 5 + 7 = 18 units of dynamite.

Input:
   A
  C+C
 M L M
E | | E
 M|_|M
  C C
   A
Output:
BOOM! 1 prime(s) primed for destruction
Reasoning:
The dynamite's box is properly surrounded by spaces, and the tip is not
required to be surrounded by spaces. Therefore, this is a valid piece of
dynamite that can explode 1 prime.

Input:
 +
 L ______
| |      L-*
|_|______|
Output:
BOOM! 3 prime(s) primed for destruction
Reasoning:
Although the 2 pieces of dynamite intersect, each on their own satisfies
the parameters for enormous dynamite. Therefore, the pieces can explode
1 + 2 = 3 primes together.

```

# Rules

Input will be an ASCII grid/string of characters in any reasonable format. Output must be a correctly computed string consisting of `BOOM! # prime(s) primed for destruction`, where `#` is the total computed dynamite size in the input.

Your answer may be a function or full program (both will be scored according to the same metrics).

Exploiting standard loopholes is forbidden.

# Scoring

This is - shortest code wins. Go out there and explode some primes :)

# Answer
# JavaScript (ES8),  ~~298 ... 272~~  267 bytes

Takes input as an array of strings.

```
a=>`BOOM! ${a.map((s,y)=>s.replace(/ _*(L?)_*(?= )/g,(s,L,x)=>t+=(w=s.length,L?y&&s[d=w+1>>1]+a[y-1][k=w*2-1,x+d]=='L+'&&~-w:k=w/3|0)*(v=L?0:++k+1>>1,g=c=>!--k||(a[y+k]+g).indexOf('|'.padEnd(w,c)+(--v?'|':'L-*'),x)==x&g())`_`),t=0)|t} prime(s) primed for destruction`

```

Try it online!

## How?

For each line, we look for the following pattern:

```
/ _*(L?)_*(?= )/g

```

The above regular expression matches a space followed by a sequence of `_` with or without a single `L` within it, followed by a space. We use a lookahead for this last space, so that it can be combined with the first space of another pattern immediately following.

If a `L` is captured, the pattern is interpreted as the top of a vertical dynamite stick. In this case, we make sure that the `L` is located at the expected position and that there is a `+` above it.

If no `L` is captured, the pattern is interpreted as the top of a horizontal dynamite stick.

In both cases, we use the recursive helper function \\$g\\$ to test the body of the stick. There's a special case in this function to make sure that we have `L-*` at the end of the middle row of a horizontal stick. All other rows are expected to be a sequence of `_` or spaces surrounded by two `|`.

## Commented

### Wrapper

```
a => `BOOM! ${...} prime(s) primed for destruction`

```

### Main code

```
a.map((s, y) =>                  // for each string s at position y in the input a[]:
  s.replace(                     //   for each string s
    / _*(L?)_*(?= )/g,           //   matching / _*(L?)_*(?= )/
    (s, L, x) =>                 //   with L = captured 'L' and x = position:
      t += (                     //     update t:
        w = s.length,            //       w = length of matched string
        L ?                      //       if a 'L' was captured:
          y &&                   //         if y is not equal to 0
          s[d = w + 1 >> 1] +    //         and the character at floor((w+1)/2)
          a[y - 1]               //         followed by the character above it ...
          [k = w * 2 - 1, x + d] //         (set k to 2w-1)
          == 'L+' && ~-w         //         ... form the string 'L+', yield w-1
        :                        //       else:
          k = w / 3 | 0          //         yield k = floor(w/3)
      ) * (                      //       multiply this by the result of g():
        v = L ? 0                //         if a 'L' was captured, set v to 0
              : ++k + 1 >> 1,    //         else, increment k and set v to floor((k+1)/2)
        g = c =>                 //         g is a recursive function taking a character c:
          !--k ||                //           decrement k and stop if it's equal to 0
          (a[y + k]              //           otherwise, take the entry at y+k,
                    + g)         //           coerce it to a string in case it's undefined,
          .indexOf(              //           look for the position of this substring:
            '|'.padEnd(w, c) +   //             a '|' followed by c repeated w-1 times
            (--v ? '|' : 'L-*'), //             followed by either a '|' or 'L-*' if v = 0
            x                    //             starting from x
          ) == x                 //           and make sure it's equal to x
          & g()                  //           recursive call with c undefined
      )`_`                       //       initial call to g with c = '_'
  ),                             //   end of replace()
  t = 0                          //   start with t = 0
) | t                            // end of map(); return t

```
> 5 votes

# Answer
# Perl 5 (`-Minteger` `-00p`), 323 bytes

Gives the correct output for tests, to be golfed more

```
for$s(2..y/
//){$t=$s-1>>1;$u=$s/2-1;$v=2*$s-1;s/^ (___){$s} .*
(\|(   ){$s}\|.*
){$t}\|(?3){$s}L-\*.*
(?2){$u}\|(?1){$s}\||^...{$u}\+.*
 __{$u}L_{$t} .*
(\| {$s}\|.*
){$v}\|_{$s}\|/$\+=$s;$&/gme}s/^ ___ .*
\|___L-\*|^.\+.*
 L .*
\| \|.*
\|_\|/$\++;$&/gme;s/^.//gm&&redo}{$\|=0;$\="BOOM! $\ prime(s) primed for destruction"

```

Try it online!
> 5 votes

---
Tags: code-golf, string, ascii-art
---