title: Square Triangles

text:
# Question
Title: Square Triangles
A positive integer **x** is a square triangle number iff there are two different positive integers, **y** and **z**, which are smaller than **x** such that all of the sums

**x + y**

**x + z**

**y + z**

are perfect squares.

For example 30 is a square triangle number because

**30 + 6 = 62**

**30 + 19 = 72**

**6 + 19 = 52**

---

Your task is to write some code that takes a positive integer as input and determines whether or not it is a square triangle number. You should output one of two distinct values, one if the input is a square triangle number and the other otherwise.

This is so answers will be scored in bytes with fewer bytes being better.

## Testcases

Here are all of the square triangle numbers under 1000

```
30,44,47,48,60,66,69,70,78,86,90,92,94,95,96,98,108,113,116,118,120,122,124,125,126,132,138,142,147,150,152,154,156,157,158,159,160,165,170,176,180,182,185,186,188,190,192,194,195,196,197,198,200,207,212,214,216,218,221,222,224,227,230,232,234,236,237,238,239,240,246,248,253,258,260,264,266,267,268,270,273,274,275,276,278,280,281,282,283,284,285,286,290,296,298,302,303,306,308,310,312,314,317,318,320,322,323,324,326,328,329,330,331,332,333,334,335,336,338,340,344,347,350,351,352,356,357,360,362,364,368,370,371,372,374,376,377,378,380,382,384,385,386,387,388,389,390,392,394,396,402,405,408,410,413,414,415,418,420,422,423,424,426,429,430,432,434,435,436,438,440,442,443,444,445,446,447,448,449,452,456,458,462,464,466,467,468,470,472,476,477,479,480,482,484,485,488,490,491,492,494,496,497,498,500,501,502,503,504,505,506,507,508,509,510,512,515,516,518,522,523,524,527,528,530,533,536,538,540,542,543,546,548,549,550,551,552,554,557,558,560,562,563,564,566,568,569,570,571,572,573,574,575,576,578,579,582,585,588,590,592,593,594,598,600,602,603,604,605,606,608,610,612,613,614,615,616,618,620,621,623,624,626,627,628,630,632,633,634,636,638,639,640,641,642,643,644,645,646,650,652,656,657,658,659,660,662,666,667,668,670,672,674,677,678,680,682,683,686,687,689,690,692,694,695,696,698,700,701,702,704,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,722,723,726,728,730,734,737,739,740,742,744,745,746,750,752,755,756,758,760,762,764,765,767,768,770,772,773,774,776,778,779,780,782,783,784,785,786,788,789,790,791,792,793,794,795,796,797,798,800,802,803,804,805,810,812,814,816,817,818,819,820,822,825,826,827,828,829,830,832,833,834,836,837,838,840,842,846,847,848,849,850,851,852,854,855,856,858,860,861,862,863,864,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,882,884,888,890,891,893,896,897,898,902,903,904,905,908,912,913,914,915,916,918,920,923,924,926,927,928,929,931,932,933,935,936,938,940,941,942,944,946,947,948,950,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,970,972,974,976,978,980,981,984,986,987,988,992,993,995,996,998

```

OEIS A242445

# Answer
> 8 votes
# Haskell, 62 bytes

```
f x|l<-(^2)<$>[1..x]=or[b>x|c<-l,b<-l,a<-l,a-x+b-x==c,c<b,b<a]

```

Try it online!

# Answer
> 7 votes
# Jelly, 12 bytes

```
R²_fṖŒcS€Æ²Ẹ

```

Try it online!

### How it works

```
R²_fṖŒcS€Æ²Ẹ  Main link. Argument: x

R             Range; yield [1, 2, ..., x].
 ²            Square; yield [1², 2², ..., x²].
  _           Subtract; yield [1²-x, 2²-x, ..., x²-x].
    Ṗ         Pop; yield [1, 2, ..., x-1].
   f          Filter; keep those values of n²-x that lie between 1 and x-1.
              This list contains all integers n such that n+x is a perfect square.
              We'll try to find suitable values for y and z from this list.
     Œc       Yield all 2-combinations [y, z] of these integers.
       S€     Take the sum of each pair.
         Æ²   Test each resulting integer for squareness.
           Ẹ  Any; check is the resulting array contains a 1.

```

# Answer
> 7 votes
# Python 2, ~~93~~ ~~87~~ 86 bytes

-1 byte thanks to Dennis

```
lambda n:{0}in[{m**.5%1for m in[x+y,n+x,n+y]}for x in range(1,n)for y in range(1+x,n)]

```

Try it online!

# Answer
> 7 votes
# Brachylog, 19 bytes

```
~hṪ>₁ℕ₁ᵐ≜¬{⊇Ċ+¬~^₂}

```

Try it online!

Also 19 bytes: `~hṪ>₁ℕ₁ᵐ≜{⊇Ċ+}ᶠ~^₂ᵐ`

### Explanation

```
~hṪ                    Ṫ = [Input, A, B]
  Ṫ>₁                  Ṫ is strictly decreasing (i.e. Input > A > B)
  Ṫ  ℕ₁ᵐ               All members of Ṫ are in [1, +∞)
  Ṫ     ≜              Assign values to A and B that fit those constraints
  Ṫ      ¬{       }    It is impossible for Ṫ…
           ⊇Ċ            …that one of its 2-elements subset…
            Ċ+           …does not sum…
              ¬~^₂       …to a square

```

# Answer
> 4 votes
# PowerShell, 150 bytes

```
param($x)filter f($a,$b){($c=[math]::Sqrt($a+$b))-eq[math]::Floor($c)}1..($i=$x-1)|%{$y=$_;1..$i|%{$o+=+($y-ne$_)*(f $x $y)*(f $x $_)*(f $y $_)}};!!$o

```

Try it online! or Verify some test cases

Takes input `$x`. Establishes a `filter` (here equivalent to a function) on two inputs `$a,$b`, which returns a Boolean true iff the `[math]::sqrt` of `$a+$b` is `-eq`ual to the `Floor` of that square root (i.e., it's an integer square root).

The rest of it is the meat of the program. We double-for loop up from `1` to `$x-1`. Each iteration, we check whether `$y` is `-n`ot`e`qual to `$_` (i.e., $z), and whether the function is true for all combinations of `$x`, `$y` and `$_`. If it is, `$o` is incremented by one (which makes it non-zero).

Finally, at the end, we double-Boolean-negate `$o`, which turns `0` into `False` and non-zero into `True`. That's left on the pipeline and output is implicit.

# Answer
> 4 votes
## JavaScript (ES7), ~~75~~ 71 bytes

```
f=
n=>(g=i=>i?--j?[n+i,i+j,j+n].some(e=>e**.5%1)?g(i):1:g(j=i-1):0)(j=n-1)
```

```
<input type=number min=1 oninput=o.textContent=f(+this.value)><pre id=o>
```

# Answer
> 4 votes
# Haskell, ~~75~~ 69 bytes

```
f x=or[all(`elem`map(^2)[1..x])[x+y,x+z,y+z]|y<-[1..x-1],z<-[1..y-1]]

```

Try it online!

Could probably be improved if someone knows a shorter way to test if a number is square. I'm pretty sure using `sqrt` ends up being longer because `floor` turns the result into an integral type so you need to put `fromIntegral` in somewhere before you can compare to the original.

EDIT: Thanks @Wheat Wizard for taking off 6 bytes!

# Answer
> 4 votes
# 05AB1E, 18 bytes

```
Lns-IL¨Ãæ2ù€OÅ²O0›

```

Try it online!

Thanks to Emigna for  ~~-3~~  -1 byte ~~and a fix~~!

# Answer
> 3 votes
# , 79 bytes

```
function(x){s=(1:x)^2
S=outer(y<-(z=s-x)[z>0&z<x],y,"+")
diag(S)=0
any(S%in%s)}

```

Try it online!

computes all the values of `y,z` with `y<-(z=s-x)[z>0&z<x]`, then computes all their sums with `outer(y,y,"+")`. This yields a square matrix where off-diagonal entries are potentially squares, as `y==z` only if they are on the diagonal. Hence, `diag(S)=0` sets the diagonals to zero, which are not perfect squares, and we test to see if `any` element of `S` is `%in%s`.

# Answer
> 3 votes
# SWI-Prolog, 88 bytes

```
s(A,B,C):-between(A,B,C),C<B,between(1,B,X),B+C=:=X*X.
g(X):-s(1,X,Y),s(Y,X,Z),s(Y,Z,Y).

```

Try it online!

```
s(A, B, C) :-
    between(A, B, C), % Find an integer C between A and B (inclusive),
    C < B,            % which is less than B.
    between(1, B, X), % Find an integer X between 1 and B (inclusive),
    B+C =:= X*X.      % of which (B+C) is the square.
g(X) :-
    s(1, X, Y), % Find Y: 1 <= Y < X, and X+Y is a perfect square
    s(Y, X, Z), % Find Z: Y <= Z < X, and X+Z is a perfect square
    s(Y, Z, Y). % Make sure that Z > Y and Y+Z is a perfect square

```

`g(X)` is the rule that takes an integer as parameter and outputs whether it is a square triangle number (true/false).

# Answer
> 2 votes
# Jelly, 15 bytes

```
ṖŒc;€ŒcS€Æ²ẠƊ€Ẹ

```

Try it online!

### How?

```
ṖŒc;€ŒcS€Æ²ẠƊ€Ẹ || Full program.
                ||
Ṗ               || Popped range. Yields [1, N) ∩ ℤ.
 Œc             || Pairs (two-element combinations).
   ;€           || Append N to each.
            Ɗ€  || For each of the lists, check whether:
           Ạ    || ... All ...
       S€       || ... The sums of each of their...
     Œc         || ... Disjoint Pairs
         Æ²     || ... Are perfect squares.
              Ẹ || Test whether there is any value that satisfies the above.

```

# Answer
> 2 votes
# JavaScript (ES7), 72 bytes

Returns `0` or `1`.

```
x=>(g=y=>z?y>z?![x+y,x+z,y+z].some(n=>n**.5%1)|g(y-1):g(x-1,z--):0)(z=x)

```

### Demo

```
let f=

x=>(g=y=>z?y>z?![x+y,x+z,y+z].some(n=>n**.5%1)|g(y-1):g(x-1,z--):0)(z=x)

for(n = 1; n < 150; n++) {
  f(n) && console.log(n)
}
```

# Answer
> 2 votes
# C, 113 bytes

```
p(n){return(int)sqrt(n)==sqrt(n);}f(x,y,z,r){for(r=y=0;++y<x;)for(z=y;++z<x;p(x+y)&p(x+z)&p(z+y)&&++r);return!r;}

```

Returns `0` if the number is square triangle, `1` otherwise.

Try it online!

# Answer
> 2 votes
# APL (Dyalog), 49 bytes

```
{∨/{0=+/(⍺=⍵),1|.5*⍨(⍺+⍵)(⍺+k)(⍵+k)}/¨,⍳2⍴1-⍨k←⍵}

```

Try it online!

# Answer
> 1 votes
# Julia 0.6, 61 bytes

Start reading from the function `all`. The first argument is an anonymous function checking that the square root of a number is an integer, this is applied to each value in the second argument. The single argument to `any` is a `Generator` with two for loops, which for each iteration contains the output of the `all` function.

Thanks to Mr Xcoder for -2 bytes.

```
x->any(all(x->√x%1==0,[x+y,x+z,y+z])for y=1:x-1for z=1:y-1)

```

Try it online!

# Answer
> 1 votes
# Clean, ~~95~~ ~~88~~ 86 bytes

```
import StdEnv
@x#l=[1..x-1]
=or[all(\n=or[i^2==n\\i<-l])[x+y,y+z,z+x]\\y<-l,z<-l|y<>z]

```

Try it online!

# Answer
> 1 votes
# Ruby, 73 bytes

```
->n{(1...n).any?{|b|(1...b).any?{|c|[n+b,b+c,n+c].all?{|r|r**0.5%1==0}}}}

```

Try it online!

# Answer
> 1 votes
# MATL, ~~20~~ ~~19~~ 18 bytes

```
q:2XN!tG+wsvX^1\aA

```

Try it online! Returns 1 for falsey, 0 for truthy.

Testcases up to 500: Try it online! (using `H` instead of `G`). Runtime is quadratic in the input size, so enumerating the testcases from `1` to `n` runs in `O(n^3)`, which is why enumerating all testcases up to 1000 times out on TIO.

* -1 byte and a conjecture less thanks to @LuisMendo
* -1 byte by a more clever check of integer-ness.

Removing `q` generates a sequence with the desired sequence as a subset, but without the constraint that `y` and `z` be strictly smaller than `x`. An example is `x=18`, `y=7`, `z=18`.

```
q:    % Push 1...n-1
2XN   % Generate all permuations of choosing 2 numbers from the above.
!     % Transpose to take advantage of column-wise operators later on.
 G+   % Add n to these combinations, to have all combos of x+y and x+z
t  ws % Duplicate the combinations, swap to the top of the stack and sum to get y+z.
v     % Concatenate vertically. The array now contains columns of [x+y;x+z;y+z].
X^    % Element-wise square root of each element
1\    % Get remainder after division by 1.
a     % Check if any have remainders, columnwise. If so, it is not a square triangle.
A     % Check whether all combinations are not square triangle.

```

# Answer
> 1 votes
# Pyt, 63 bytes

```
0←Đ⁻Đ`⁻Đ3ȘĐ3Ș+√ĐƖ=4ȘĐ3ȘĐ3Ș+√ĐƖ=4ȘĐ3ȘĐ3Ș+√ĐƖ=4Ș6Ș**4Ș↔+↔łŕ⁻Đłŕŕŕ

```

Tests all possible combinations of y,z such that 1≤z\<y\<x

Returns 1 if x is a square triangle number, 0 otherwise

Try it online!

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


title: 3D ASCII Block Building

text:
# Question
Title: 3D ASCII Block Building
## Challenge

Write a program that takes an 11x11 array of integers, and constructs a 3D ASCII block building, where each value in the array represents the height of a column of blocks at the coordinates matching the array position. A negative height is a "floating" column - only the top block is visible.

## Example

```
                                                        __________________
                                        ___            /\__\__\__\__\__\__\
 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,      /\__\          /\/\__\__\__\__\__\__\
 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,     /\/__/         /\/\/__/__/__/__/__/__/
 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,    /\/\__\        /\/\/\__\      /\/\/__/
 1, 0, 0, 7,-7,-7,-7,-7, 7, 0, 0,    \/\/\__\      /\/\/\/__/     /\/\/__/
 0, 0, 0, 7,-7,-7,-7,-7, 7, 0, 0,     \/\/__/     /\/\/\/\__\    /\/\/__/
 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0,      \/\__\    /\/\/\/\/__/   /\/\/__/
 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0,       \/__/    \/\/\/\/\__\_  \/\/__/
 1, 0, 0, 4, 3, 2, 1, 0, 0, 0, 1,                 \/\/\/\/__/_\_ \/__/
 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,            ___   \/\/\/__/__/_\_         ___
 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,           /\__\   \/\/__/__/__/_\       /\__\
 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1,           \/\__\   \/__/__/__/__/       \/\__\
                                             \/\__\_________         ______\/\__\
                                              \/\__\__\__\__\       /\__\__\__\__\
                                               \/__/__/__/__/       \/__/__/__/__/

```

## Input

The input will be a list of 121 integers, either read from stdin (choice of separator is up to you), or passed in as an array (can be 1D or 2D).

Heights will be in the range -11 to 11.

## Output

The generated building can be written to stdout, displayed directly on the screen, or returned as a newline-separated string.

Leading and trailing whitespace is allowed.

## Building Rules

The shape of an individual 3D block looks like this:

```
 ___
/\__\
\/__/

```

And a 2x2x2 cube of blocks looks like this:

```
  ______
 /\__\__\
/\/\__\__\
\/\/__/__/
 \/__/__/

```

When blocks overlap, a higher block takes precedence over a lower one, blocks in front take precedence over those further back, and blocks to the left takes precedence over those to the right. The only special case is that the top line of a block should never overwrite any non-space character behind it.

The interpretation of column heights can best be explained by looking at a 2D representation from the side.

```
HEIGHT:  1    2    3   -3   -2   -1
                  __   __
             __  |__| |__|  __
        __  |__| |__|      |__|  __
       |__| |__| |__|           |__|

```

## Test Cases

If you want to try out your solution on a few more inputs, I've put together a couple of test cases here.

## Winning

This is , so the shortest submission (in bytes) wins.

# Answer
> 25 votes
# Charcoal, ~~70~~ ~~69~~ 68 bytes

```
≔Ｅ¹¹⮌Ｉ⪪Ｓ,θＦ²Ｆ¹¹Ｆ¹¹Ｆ¹¹«Ｊ⁻⁻⁺λκ×μ³ι⁻λκ≔§§θλμη¿∨⁼±η⊕κ‹κη¿ι“↗⊟&⁹κＵhnI”___

```

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

```
≔Ｅ¹¹⮌Ｉ⪪Ｓ,θ

```

Read the array, split each line on commas and cast to integer, but also reverse each line, since we want to draw right-to-left so that left columns overwrite right columns. (Other dimensions already have desired overwriting behaviour.)

```
Ｆ²Ｆ¹¹Ｆ¹¹Ｆ¹¹«

```

Loop through i) top lines and bodies k) height l) rows m) columns. (Looping through first top lines and then bodies avoids overwriting bodies with top lines.)

```
Ｊ⁻⁻⁺λκ×μ³ι⁻λκ

```

Jump to the position of the cube.

```
≔§§θλμη

```

Fetch the height at the current row and column.

```
¿∨⁼±η⊕κ‹κη

```

Test whether a cube should be drawn at this height for this row and column.

```
¿ι“↗⊟&⁹κＵhnI”___

```

Draw the body or top of the cube.

# Answer
> 34 votes
# C,  ~~376~~   ~~350~~   ~~313~~   ~~309~~  285 bytes

*Thanks to @Jonathan Frech for saving four bytes!*

```
#define F for(
char*t,G[26][67],*s;i,j,e,k,v,x,y;b(){F s="\\/__//\\__\\ ___ ";*s;--y,s+=5)F e=5;e--;*t=*s<33&*t>32?*t:s[e])t=G[y]+x+e;}f(int*M){F;e<1716;++e)G[e/66][e%66]=32;F k=0;++k<12;)F i=0;i<11;++i)F j=11;j--;v+k||b())x=i+j*3+k,y=14+i-k,(v=M[i*11+j])>=k&&b();F;++e<26;)puts(G+e);}

```

Try it online!

**Unrolled:**

```
#define F for(

char *t, G[26][67], *s;
i, j, e, k, v, x, y;

b()
{
    F s="\\/__//\\__\\ ___ "; *s; --y, s+=5)
        F e=5; e--; *t=*s<33&*t>32?*t:s[e])
            t = G[y]+x+e;
}

f(int*M)
{
    F; e<1716; ++e)
        G[e/66][e%66] = 32;

    F k=0; ++k<12;)
        F i=0; i<11; ++i)
            F j=11; j--; v+k||b())
                x = i+j*3+k,
                y = 14+i-k,
                (v=M[i*11+j])>=k && b();

    F; ++e<26;)
        puts(G+e);
}

```

# Answer
> 9 votes
# JavaScript (ES6), ~~277~~ 251 bytes

```
a=>(n=55,$=f=>[...Array(n)].map((_,i)=>f(i)),S=$(_=>$(_=>' ')),n=11,$(l=>$(z=>$(y=>$(x=>(x=10-x,X=x*3+y+z,Y=y-z+n,Z=a[y][x])<=z&&Z+z+1?0:l?['/\\__\\','\\/__/'].map(s=>S[++Y].splice(X,5,...s)):S[Y].splice(X+1,3,...'___'))))),S.map(r=>r.join``).join`
`)

```

```
f=

a=>(n=55,$=f=>[...Array(n)].map((_,i)=>f(i)),S=$(_=>$(_=>' ')),n=11,$(l=>$(z=>$(y=>$(x=>(x=10-x,X=x*3+y+z,Y=y-z+n,Z=a[y][x])<=z&&Z+z+1?0:l?['/\\__\\','\\/__/'].map(s=>S[++Y].splice(X,5,...s)):S[Y].splice(X+1,3,...'___'))))),S.map(r=>r.join``).join`
`)

console.log(f([
 [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, -11],
 [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [1, 0, 0, 7,-7,-7,-7,-7, 7, 0, 0],
 [0, 0, 0, 7,-7,-7,-7,-7, 7, 0, 0],
 [0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0],
 [1, 0, 0, 4, 3, 2, 1, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 11]
]))
```

Saved 26 bytes from @Neil's suggestion.

### Ungolfed

```
a=>(
    n=55,
    $=f=>[...Array(n)].map((_,i)=>f(i)),
    S=$(_=>$(_=>' ')),
    n=11,
    $(l=>
        $(z=>$(y=>$(x=>(
            x=10-x,
            X=x*3+y+z,
            Y=y-z+n,
            Z=a[y][x],
            Z<=z && Z+z+1 || (
                l
                ? ['/\\__\\','\\/__/'].map(s=>S[++Y].splice(X,5,...s))
                : S[Y].splice(X+1,3,...'___')
            )
        ))))
    ),
    S.map(r=>r.join``).join`\n`
)

```

# Answer
> 6 votes
# Python 2, 243 bytes

```
a=input()
s=eval(`[[' ']*55]*23`)
for h in range(7986):
 k=h%3;x=h/3%11;y=h/33%11;z=h/363%11;i=h/3993;u=y+z-x*3+30;v=y-z+10
 if~-(z>=a[y][10-x]!=~z):
	if i*k:s[v+k][u:u+5]='\//\____/\\'[k%2::2]
	if~-i:s[v][u+1+k]='_'
for l in s:print''.join(l)

```

Try it online!

A Python translation of Neil’s Charcoal approach.

# Answer
> 5 votes
# Tcl, 380 ~~409~~ bytes

User **sergiol** has been busy crunching this down very nicely:

```
set X [read stdin]
proc L {a b c d e s} {time {incr z
set y -1
time {incr y
set x -1
time {if {abs([set Z [lindex $::X [expr ($y+1)*11-[incr x]-1]]])==$z|$z<$Z} {set s [string repl [string repl $s [set i [expr -3*$x+57*$y-55*abs($z)+701]] $i+$b $a] [incr i $c] $i+$e $d]}} 11} 11} 12
set s}
puts [L /\\__\\ 4 56 \\/__/ 4 [L "" -1 -55 ___ 2 [string repe [string repe \  55]\n 23]]]

```

Try it online!

### Original Content

```
set xs [read stdin]
proc L {a b c d e s} {set z 0
while {[incr z]<12} {set y -1
while {[incr y]<11} {set x -1
while {[incr x]<11} {set Z [lindex $::xs [expr ($y+1)*11-$x-1]]
if {abs($Z)==$z||$z<$Z} {set i [expr -3*$x+57*$y-55*abs($z)+701]
set s [string repl [string repl $s $i $i+$b $a] [incr i $c] $i+$e $d]}}}}
set s}
puts [L /\\__\\ 4 56 \\/__/ 4 [L "" -1 -55 ___ 2 [string repe [string repe \  55]\n 23]]]

```

Try it online!

Alas, it is what it is. It’s only a tad easier on the eyes when “ungolfed”

```
set s [string repeat [string repeat " " 55]\n 23]

proc loops {s0 i0 io s1 i1} {
  set z  0; while {[incr z] < 12} {
  set y -1; while {[incr y] < 11} {
  set x -1; while {[incr x] < 11} {
    set Z [lindex $::xs [expr {($y+1) * 11 - $x - 1}]]
    if {abs($Z) == $z || $z < $Z} {
        set i [expr {-3*$x + 57*$y - 55*abs($z) + 701}]
        set ::s [string replace $::s $i $i+$i0 $s0]
        incr i $io
        set ::s [string replace $::s $i $i+$i1 $s1]
    }
  } } }
}

loops ""      -1 -55 \
       ___     2
loops /\\__\\  4  56 \
      \\/__/   4

puts $s

```

Builds a string, as per requirements. Takes the array from stdin. Goes from bottom to top, front to back, right to left over the string data. Does it in two passes, once for the top edge and again for the rest of the body of each cube.

I tried to make it smaller using some sweet functional lambda mojo, but alas, that made it larger.

# Answer
> 5 votes
# APL (Dyalog Unicode), ~~117~~ ~~116~~ 112 bytesSBCS

```
a←23 55⍴0⋄{i←11 0+⍵+.×3 2⍴3-7897⊤⍨6⍴5⋄(,2 5↑i↓a)←745366⊤⍨10⍴4⋄(3⍴i↓1⌽¯1⊖a)⌈←1}¨j[⍋-/↑j←⍸↑⎕↑¨⊂⌽1,11/⍳2]⋄' _/\'[a]

```

Try it online!

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


title: Does a letter fit inside the other?

text:
# Question
Title: Does a letter fit inside the other?
Do you remember my mat properly grouped by colors?

Yesterday I was looking at it and realized that some letters fit inside others. Example: a letter `P` fits in the place where the letter `R` goes. So here's a simple challenge: given two letters, return a truthy value if any one of the letters fits inside the other (directly or rotated, but not flipped), or a falsey value if they don't. That is, if the input is `[P,R]` or `[R,P]`, you must return truthy because in both cases one letter fits inside the other. If you get `[L,U]` you must return falsey as neither fit inside the other.

**Rules**

* The input must be two alphanumeric characters in the range \[0-9A-Z\], as there are also numbers in the mat, in any form you need (two separate chars as two inputs, a list with two chars, a string with the 2 chars, whatever).
* The output must be consistent (the truthy and falsey values must be always the same).
* Following is the table of fittings (note that a letter always fits in its proper place, just in case you get something like `[Y,Y]` as input):

```
char fits inside chars
--------------------------------------------------------
   C             G,O
   F             B,E,P,R
   G             O
   I             0,1,7,B,D,E,F,H,K,L,M,N,O,P,R,T,V,W,X,Z
   L             E
   M             W
   P             R
   S             O
   V             A
   W             M
   0             O
   1             B,E,L
   3             O
   6             9,O
   8             O
   9             6,O

```

I solemnly swear that I have tested every fitting in my kid's mat. *(Dries his sweat from his forehead.)*

This is , so may the shortest code for each language win!

**Some test cases**

```
input  output
-------------
[C,G]  truthy (C fits inside G)
[G,C]  truthy (C fits inside G)
[F,R]  truthy (F fits inside R)
[M,W]  truthy (both fit inside the other)
[O,S]  truthy (S fits inside O)
[T,T]  truthy (T fits in its place)
[E,V]  falsey (no fit found)
[P,L]  falsey

```

---

Sandbox post. Please, forgive me if you spot more fittings that I missed. Many thanks to Οurous for helping me with the fittings list.

# Answer
# Python 2, ~~135~~ ~~130~~ 129 bytes

-1 byte thanks to Lynn

```
lambda s:cmp(*s)%2*s[::cmp(*s)|1]in'OIH TIE XI7 RF O8 OGC LI0 O3 O96 VA O6 KI PI WI L1 WMI O0 RIB NI1 FE SOC VID ZIFB1 PF LE1 RP'

```

Try it online!

# Python 3, 143 bytes

```
lambda*i:any({*i}&{a,c}=={*i}for a,b in zip('CFGILMPSVW013689','GO BEPR O 017BDEFHKLMNOPRTVWXZ E W R O A M O BEL O 9O O 6O'.split())for c in b)

```

Try it online!
> 6 votes

# Answer
# Retina, ~~93~~ 92 bytes

```
O`.
(.)\1|1[BEL]|69|AV|CG|BF|EF|EL|FP|FR|[017BDEFH]I|I[KLMNOPRTVWXZ]|MW|PR|OS|[03689CG]O

^$

```

Try it online! Edit: Saved 1 byte thanks to @ovs.
> 5 votes

# Answer
# Javascript ~~155 153 151~~ 149 bytes

I think this works on all cases, 1/0 for true/false.

```
(c,f,q=1)=>"CGO,FBEPR,GO,I017BDEFHKLMNOPRTVWXZ,LE,MW,PR,SO,VA,WM,0O,1BEL,3O,69O,8O,96O".split`,`.some((v=>v[0]==c&v.includes(f)))|c==f|(q?F(f,c,0):0)

```

Explanation:

```
F=(
c, // input 1
f, // input 2
q=1 // variable used to execute F twice
)=>(
"CGO,FBEPR,GO,I017BDEFHKLMNOPRTVWXZ,LE,MW,PR,SO,VA,WM,0O,1BEL,3O,69O,8O,96O".split`,`
                              // array of strings where [0] is input 1 and [>0] are the fittings
.some(                        // any element of the array meets:
(v=>v[0]==c&v.includes(f)))|  // input 1 equals [0] and input 2  exists in the lookup string OR
c==f|                         // input 1 equals input 2 OR
(q?F(f,c,0):0)                // input 2 fits inside input 1

```

```
let F=(c,f,q=1)=>"CGO,FBEPR,GO,I017BDEFHKLMNOPRTVWXZ,LE,MW,PR,SO,VA,WM,0O,1BEL,3O,69O,8O,96O".split`,`.some((v=>v[0]==c&v.includes(f)))|c==f|(q?F(f,c,0):0);
let tests = [
  ["C","G"],  //truthy (C fits inside G)
  ["G","C"],  //truthy (C fits inside G)
  ["F","R"],  //truthy (F fits inside R)
  ["M","W"],  //truthy (both fit inside the other)
  ["O","S"],  //truthy (S fits inside O)
  ["T","T"],  //truthy (T fits in its place)
  ["E","V"],  //falsey (no fit found)
  ["P","L"]   //falsey
];
tests.forEach((v)=>{console.log("F('"+v[0]+"','"+v[1]+"') = " + F(v[0],v[1]))});
```

## Changelog:

* saved 2 bytes thanks to kamoroso94
* saved 2 bytes thanks to Chris M
* saved 2 bytes by changing lookup method to .some()
> 2 votes

# Answer
# Clean, ~~276~~ 226 bytes

Vaguely golfed-ish. Will polish tomorrow.

```
import StdEnv
i a b=isMember b a
t=True
f'C'b=i['GO']b
f'F'b=i['BEPR']b
f'O'b=i['GS03689']b
f'I'b=i['017BDEFHKLMNOPRTVWXZ']b
f'L''E'=t
f'P''R'=t
f'V''A'=t
f'M''W'=t
f'1'b=i['BEL']b
f'6''9'=t
f _ _=False
?a b=a==b||f a b||f b a

```

Try it online!
> 2 votes

# Answer
# Haskell, ~~149~~ 145 bytes

```
[]!_=0>1
(a:b:c)!t=(a,b)==t||(b,a)==t||c!t
f x y=x==y||"0I0O1B1E1I1L3O696O7I8O9OAVBFBICGCODIEFEIELFIFPFRGOHIIKILIMINIOIPIRITIVIWIXIZMWOSPR"!(x,y)

```

Try it online!
> 2 votes

# Answer
# Julia 0.6, 139 bytes

```
(a,b)->(a==b)|any(map(x->all(in.((a,b),x))|all(in.((b,a),x)),zip("OCFILMPV16",split("CGS0368 G BEPR 017BDEFHKLMNOPRTVWXZ E W R A BEL 9"))))

```

Try it online!

Saved some bytes by grouping the chars that fit into 'O'. But testing the reversed input uses too much code...

Explanation:

* `zip(☐)` zips corresponding single letters from `"OCFILMPV16"` & a string of matching letters.
* `.in(☐)` is applied elementwise, e.g. `(in(a,'O'),in(b,"OCFILMPV16"))`
* `all(.in(☐))` Both must be found...
* `|` for either `a,b` or `b,a`...
* `any(map(☐))` for at least one element of the zipped list.
> 1 votes

# Answer
# Kotlin, ~~147~~ 139 bytes

```
fun p(s:String)=setOf(s,s.reversed()).any{it.matches(Regex("(.)\\1|F[BEPR]|I[017BDEFHKLMNOPRTVWXZ]|1[BEL]|69|CG|LE|MW|PR|VA|O[CG69038S]"))}

```

Try it online!

The example on *Try It Online* includes test cases for every positive combination and a few negative ones.

I haven't optimized the reg.ex. too much, so it might be longer than necessary

**EDIT:** saved a few bytes on reg.ex.
> 1 votes

# Answer
# C (gcc), 211 bytes

A first attempt. Very straight-forward.

```
i;char*c="CFGILMPSVW013689",*x[]={"GO","BEPR","O","017BDEFHKLMNOPRTVWXZ","E","W","R","O","A","M","O","BEL","O","9O","O","6O"};h(a,b){return(i=strchr(c,a)-c)>=0&&strchr(x[i],b);}f(a,b){return a==b|h(a,b)|h(b,a);}

```

Try it online!
> 1 votes

# Answer
# PHP, 204 bytes

*-147 bytes because I cam back to remove 2 bytes only to find that my code had a few bugs and unused variables! My code is now much shorter.*

```
<?php $a=fgets(STDIN);for($w=0;$w<2;$w++){if(strpos(explode(',','GO,BEPR,O,017BDEFHKLMNOPRTVWXZ,E,W,R,O,A,M,O,BEL,O,9O,O,6O')[strpos(CFGILMPSVW013689,$a[0])],$a[1])!==false){echo"t";break;}$a=strrev($a);}

```

Try it online!
> 0 votes

# Answer
# Ruby, 140 bytes

```
->c,t{x='CFGILMPSVW013689'.chars.zip('GO BEPR O 017BDEFHKLMNOPRTVWXZ E W R O A M O BEL O 9O O 6O'.split).to_h;p x.key?(c)&&x[c].include?(t)}

```

Pretty much the same as the python 3 answer, but with a different execution.
> 0 votes

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


title: Help pannenkoek count A presses

text:
# Question
Title: Help pannenkoek count A presses
pannenkoek2012 aims to complete Super Mario 64 with as few presses as possible of the A button, which makes Mario jump. Each "A press" consists of three parts:

* Pressing the button
* Holding it for any length of time
* Releasing it

See this video (1:15 - 3:23) for a great explanation that includes the above image. (However, this challenge will not use the half-A-press terminology and will posit obstacles that require releasing A.)

**Task:**

Given a sequence of obstacles requiring pressing (P), holding (H), or releasing (R) the A button, output the smallest number of presses required to overcome them in the order given. The A button is initially not held.

Stated formally: given a string S of characters `PHR`, consider strings of form `(PH*R)*` that contain S as a subsequence, and output the smallest possible number of `P`'s in such a string. Or, alternatively, find the smallest number of chunks of the form `P?H*R?` that S can be split into.

**Example**

Let's look at input `RHRPHHHR`. The A button starts not held, so overcoming the initial obstacle `R` requires the button be pressed and then released (press #1). Next we are required to hold the button `H`, which again requires it first be pressed (press #2). Then, it can then be released afterwards to satisfy the `R` after it. Finally, the remaining `PHHHR` can be satisfied by a single press (press #3) followed by holding `HHH` and releasing `R`. So, the output count is 3.

Another way to see it, is that we can split the input string into 3 parts of form `PHH..HHR` where letters may be omitted.

```
R
HR
PHHHR

```

**Input format**

The input will be a list or string of elements representing press, hold, and release as your choice of:

* `P, H, R`
* `p, h, r`
* `1, 2, 3`
* `0, 1, 2`

matched in the order given. The input will not be empty.

**Test cases:**

```
P 1
H 1
R 1
HP 2
RHP 3
HHR 1
PHRH 2
RHRPHHHR 3
HHHHHH 1
PPRRHHPP 6
HPPRHRPRHPPRHPPHRP 12
PRHRHPHHPRRRHPPRHHPPRRRHRHPRPHPRPRHHRPPPRHPRP 28

```

**Leaderboard:**

```
var QUESTION_ID=152701,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/152701/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 5 votes
# Retina, 9 bytes

```
1>`P?H*R?

```

Try it online!

# Answer
> 3 votes
# Pyth, 13 bytes

```
tl:z"P?H*R?"3

```

**Try it here!** or **Verify all the test cases.**

Note that `1` also works in place of `3`.

### How it works?

```
tl:z"P?H*R?"3 | Full program. Takes input from STDIN, outputs to STDOUT.

  :z        3 | Split the input string on matches of...
    "P?H*R?"  | The regular expression "P?H*R?".
 l            | Get the length.
t             | Decrement (because splitting includes the empty string).

```

**More about the regex:**

```
P?     | P – The literal character P, case sensitive.
       | ? – Quantifier. Matches either one or zero times the previous character.
  H*   | H – The literal character H, case sensitive.
       | * – Quantifier. Matches any number of occurrences of the previous character.
    R? | R – The literal character R, case sensitive.
       | ? – Quantifier. Matches either one or zero times the previous character.

```

# Answer
> 2 votes
# Jelly, 10 bytes

```
o5ḄƝ%⁵>4S‘

```

A monadic chain taking a list (the `P,H,R : 0,1,2` option) and returning an integer, the count.

**Try it online!** or see the test-suite

### How?

Effectively works by getting all adjacent pairs then counting any that are not "continuation pairs" (`PR`, `PH`, `HR`, or `HH`) and adding one.

```
o5ḄƝ%⁵>4S‘ - Link: list of integers (in [0,1,2])  e.g.: [0,0,1,0,2,1,1,2,2,0] (representing PPHPRHHRRP)
o5         - logical OR with 5                          [5,5,1,5,2,1,1,2,2,5]
   Ɲ       - for all adjacent pairs:              i.e.: [5,5],[5,1],[1,5],[5,2],[2,1],[1,1],[1,2],[2,2],[2,5]
  Ḅ        -   convert from binary                      [ 15 ,  11 ,  7  ,  12 ,  5  ,  3  ,  4  ,  6  ,  9 ]
     ⁵     - literal ten
    %      - modulo                                     [  5 ,   1 ,  7  ,   2,   5  ,  3  ,  4  ,  6  ,  9 ]
      >4   - greater than four?                         [  1 ,   0 ,  1  ,   0,   1  ,  0  ,  0  ,  1  ,  1 ]
        S  - sum                                        5
         ‘ - increment                                  6

```

---

Previous 11 byte solution:

```
ḅ3Ɲạ3ḟ1,2L‘

```

Try it online! or see the test-suite

### How?

Works like the above, but in a completely different way...

```
ḅ3Ɲạ3ḟ1,2L‘ - Link: list of integers (in [0,1,2])  e.g.: [0,0,1,0,2,1,1,2,2,0] (representing PPHPRHHRRP)
  Ɲ         - for all adjacent pairs:              i.e.: [0,0],[0,1],[1,0],[0,2],[2,1],[1,1],[1,2],[2,2],[2,0]
ḅ3          -   convert from base three                  [ 0  ,  1  ,  3  ,  2  ,  7  ,  4  ,  5  ,  8  ,  6 ]
   ạ3       - absolute difference with three             [ 3  ,  2  ,  0  ,  1  ,  4  ,  1  ,  2  ,  5  ,  3 ]
     ḟ1,2   - filter discard if in [1,2]                 [ 3        ,  0        ,  4              ,  5  ,  3 ]
         L  - length                                     5
          ‘ - increment                                  6

```

and another, again quite different:

```
+19*Ɲ%13ḂS‘

```

(add 19 to each, then for adjacent pairs perform exponentiation, modulo by 13, modulo by 2, sum and add one).

# Answer
> 2 votes
## Batch, 69 bytes

```
@set/ab=2,n=0
@for %%b in (%*)do @set/an+=b/2^|!%%b,b=%%b
@echo %n%

```

Takes input as a list of 0-indexed command-line parameters, but you can use a list of letters `p, h, r` in either upper or lower case if you type `set /a p=0, h=1, r=2` first. Explanation: `b` maintains the last input (defaulting to `2` for released) and `n` the count of presses. Each input adds a press if the last input was a release or the current input is a press.

# Answer
> 2 votes
# Python 2, 44 bytes

Uses P-\>1 H-\>2 R-\>3

```
lambda a:sum(1/y|x/3for x,y in zip([3]+a,a))

```

# Answer
> 1 votes
# Deorst, 11 bytes

```
'P?H*R?'ggL

```

Try it online!

Uses Mr. Xcoder's regex

# Answer
> 1 votes
# Japt, 11 bytes

```
è"P?H*R?" É

```

Try it | Check all test cases

`è` counts the number of matches of the RegEx in the input and `É` subtracts 1.

# Answer
> 1 votes
# Python 2, 48 bytes

```
f=lambda a,*l:l==()or(a>l[0]or l[0]==a!=1)+f(*l)

```

Try it online!

Takes `0,1,2` as input.

# Answer
> 1 votes
# Jelly, 10 bytes

```
Pn1></µƝS‘

```

Try it online! or Test suite! (~~Stolen~~ Borrowed from Jonathan.)

**Alternative:**

```
P=1=</µƝS‘

```

Try it online!

```
Pn1></µƝS‘ | Monadic chain.

      µƝ   | Map over each pair of "neighbours" (x, y) in the list.
P          | And check whether their product...
 n1        | ... 1 if it doesn't equal 1, 0 otherwise...
   >       | Is higher than?
    </     | The pair reduced by "Smaller than?". 1 if x < y, else 0.
        S  | Sum.
         ‘ | Add 1.

```

---

### Jelly, 11 bytes

Saved 1 byte with help from caird coinheringaahing.

```
ḅ3Ɲf⁽vḲD¤L‘

```

Try it online!

# Answer
> 1 votes
# Husk, ~~6~~ 5 bytes

```
Lġo&ε

```

Try it online! Input is a list over `0,1,2` (the TIO link uses letters for easier copy-pasting of test cases).

## Explanation

I use the same general idea as Jonathan Allan's Jelly answer: split on occurrences of the "discontinuity pairs" PP, HP, RH, RR and RP, and count the resulting blocks. In the 0,1,2 encoding, these pairs are exactly those whose left element is 2 or right element is 0.

```
Lġo&ε  Input is a list.
 ġ     Split between pairs that do not satisfy:
    ε  the left element is at most 1
  o&   and the right element is truthy.
L      Length.

```

# Answer
> 1 votes
# Javascript (ES6), 30 bytes

```
f=s=>s.match(/P?H*R?/g).length-1
```

```
<input id=i oninput="o.innerText=f(i.value)" value="PHHR"><pre id=o>l
```

# Answer
> 1 votes
# Haskell, 36 bytes

```
f a=sum[1|(x,y)<-zip(2:a)a,x>1||y<1]

```

Try it online!

Uses the `0,1,2` encoding.

# Answer
> 1 votes
# Kotlin, 36 bytes

```
Regex("P?H*R?").findAll(i).count()-1

```

## Beautified

```
Regex("P?H*R?").findAll(i).count()-1

```

## Test

```
fun f(i:String) =
Regex("P?H*R?").findAll(i).count()-1
data class Test(val input: String, val output: Int)

val TESTS = listOf(
        Test("P", 1),
        Test("H", 1),
        Test("R", 1),
        Test("HP", 2),
        Test("RHP", 3),
        Test("HHR", 1),
        Test("PHRH", 2),
        Test("RHRPHHHR", 3),
        Test("HHHHHH", 1),
        Test("PPRRHHPP", 6),
        Test("HPPRHRPRHPPRHPPHRP", 12),
        Test("PRHRHPHHPRRRHPPRHHPPRRRHRHPRPHPRPRHHRPPPRHPRP", 28)
)

fun main(args: Array<String>) {
    for ((input, expectded) in TESTS) {
        val actual = f(input)
        if (actual != expectded) {
            throw AssertionError("$input $expectded $actual")
        }
    }
}

```

## TIO

TryItOnline

# Answer
> 0 votes
# , <sub>~~18~~</sub> 17 bytes

-1 Thanks to @FrownyFrog

```
1+1#.}:(<+:1=*)}.

```

Takes input in the form of `0,1,2`. The helper function on TIO converts the test cases to this form.

Try it online!

The logic of the comparisons may still be golfable. I'm twisting my brain into knots trying to think of more equivalent and shorter statements.

# Explanation (previous solution)

```
1+1#.2(</+:1=*/)\]

```

The only difference between the current solution and the previous one is how the comparisons are generated. The current solution explicitly compares adjacent elements by offsetting the array and the previous solution compares adjacent elements by looking at infixes of 2.

```
1 + 1 #. 2 (</ +: 1 = */)\ ]
         2               \ ]  On infixes of 2 on the input
                  1 = */        Is the infix 1 1 (two holds)?
            </                  Is the infix x y such that x < y?
               +:               These results NORed
    1 #.                       Add all of the results together (debase to base 1)
1 +                            Add one

```

This would be a lot cleaner if two holds did nothing. The code takes infixes of two and checks if they are not ascending and not two holds. If this is the case, then we add one to our final count. We have to add 1 to the end since we're off by one otherwise (or you could prepend an `_` or any value greater than 2).

The way it checks if the infix is two holds is by multiplying the two values together and seeing if it is one (two holds are `1 1`).

# Answer
> 0 votes
# Vim + `wc`, 25 bytes

```
:s/P\?H*R\?/a/g␊V!wc -c␊␘

```

is the return key and  is `Ctrl`+`X`

Try it online!

## Explanation

```
:s/P\?H*R\?/a/g␊    Replace all button presses with the character a
V!wc -c␊␘          Count the characters using the wc command

```

---
Tags: code-golf, sequence, subsequence
---


# Question
Title: Write numbers as a difference of Nth powers
## Challenge

There are many numbers which can be expressed as the difference of two squares, or as the difference of two cubes, or maybe even higher powers. Talking about squares, there are various ways of writing a number, say 75, as the difference of 2 squares. You can write:

```
75 = (10)^2 - (5)^2
   = (14)^2 - (11)^2
   = (38)^2 - (37)^2

```

So let's talk about the challenge. Firstly, the user enters a number and then he enters a value for n. You need to display all the ways in which that number can be written in the form of aⁿ - bⁿ.

## Input and Output

The input will be the number and the value of n. Your output shall have all such pairs of 'a' and 'b' such that the above-stated condition is met. The first number in the pair must be larger than the second. Please note that **a, b, n and the input number are all positive integers, and n \> 1**.

## Examples

```
50, 2 -> (none)

32, 2 -> (9,7), (6, 2)

7, 3 -> (2,1)

665, 6 -> (3, 2)

81, 4 -> (none)

```

## Scoring

This is , so the shortest code wins!

# Answer
# Jelly, 8 bytes

```
p*ƓIFẹ+d

```

This is a monadic link that takes the number as argument and reads **n** from STDIN.

Try it online!

### How it works

```
p*ƓIFẹ+d  Main link. Argument: k

p         Cartesian product; yield all pairs [b, a] with b and a in [1, ..., k].
  Ɠ       Get; read an integer n from STDIN.
 *        Power; map each [b, a] to [b**n, a**n].
   I      Increments; map each [b**n, a**n] to [a**n-b**n].
    F     Flatten the resulting list of singleton arrays.
     ẹ    Every; find all indices of k in the list we built.
      +   Add k to the indices to correct the offset.
       d  Divmod; map each index j to [j/k, j%k].

```
> 9 votes

# Answer
# Haskell, 42 bytes

```
k#n=[(a,b)|b<-[1..k],a<-[b..k],a^n-b^n==k]

```

Try it online!

## Ungolfed with UniHaskell and `-XUnicodeSyntax`

```
import UniHaskell

f     ∷ Int → Int → [(Int, Int)]
f k n = [(a, b) | b ← 1 … k, a ← b … k, a^n - b^n ≡ k]

```

Can't change much else...
> 6 votes

# Answer
# MATL, 11 bytes

```
t:i^&-!=&fh

```

Try it online! Or verify all test cases.

### Explanation

```
t     % Implicit input: M. Duplicate
:     % Range [1 2 ... M]
i     % Input: n
^     % Power, element-wise. Gives [1^n 2^n ... M^n]
&-    % Matrix of pairwise differences (size n×n)
!     % Transpose. Needed so the two numbers in each pair are sorted as required
=     % Is equal? Element-wise. Gives true for entries of the matrix equal to M
&f    % Row and column indices of true entries
h     % Concatenate horizontally. Implicit display

```
> 4 votes

# Answer
# 05AB1E, 9 bytes

Very inefficient for larger input values.

```
LãDImÆ¹QÏ

```

Try it online!

**Explanation**

```
L           # range [1 ... input_1]
 ã          # cartesian product with itself
  D         # duplicate
   Im       # raise each to the power of input_2
     Æ      # reduce each pair by subtraction
      ¹QÏ   # keep only values in the first copy which are true in this copy

```
> 4 votes

# Answer
# APL (Dyalog), 21 bytes

```
{o/⍨⍵=-/¨⍺*⍨¨o←,⍳2⍴⍵}

```

Try it online!

Left argument is `n`.
> 4 votes

# Answer
# Python 2, 65 bytes

```
lambda k,n:[(j%k,j/k)for j in range(k,k*k)if(j%k)**n-(j/k)**n==k]

```

Try it online!
> 4 votes

# Answer
# Python 3, 71 bytes

Thanks Mr.Xcoder for saving some bytes!

```
lambda x,n:[(a,b)for b in range(1,x)for a in[(b**n+x)**(1/n)]if a%1==0]

```

Try it online!

---

# Python 3, 69 bytes

```
lambda x,n:[(a,b)for b in range(1,x)for a in range(x)if a**n-b**n==x]

```

Try it online!

Use totallyhuman's x^2 brute force approach actually saves bytes.
> 2 votes

# Answer
# Jelly, 10 bytes

```
*Iċ³
ṗ2çÐf

```

A full program taking `i`, and `n` which prints out the pairs of `[b,a]` with an empty output when there are none.

**Try it online!**

### How?

```
*Iċ³ - Link 1, isValid?: pair of +ve integers, [b,a]; +ve integer, n
*    - exponentiate             -> [b^n,a^n]
 I   - incremental differences  -> [a^n-b^n]
   ³ - program's third argument -> i
  ċ  - count occurrences        -> 1 if a^n-b^n == i, otherwise 0

ṗ2çÐf - Main link: +ve integer i, +ve integer n
ṗ2    - second Cartesian power = [[1,1],[1,2],...,[1,i],[2,1],...,[2,i],...,[i,i]]
   Ðf - filter keeping if:
  ç   -   call last link (1) as a dyad (left = one of the pairs, right = n)
      - implicit print of Jelly representation of the list

```
> 2 votes

# Answer
# JavaScript (ES7), 64 bytes

A recursive function taking input in currying syntax `(n)(p)`. Returns a space-separated list of pairs of integers, or an empty string if no solution exists. Uses the same algorithm as user202729's Python answer.

```
n=>p=>(g=x=>x--?((y=(x**p+n)**(1/p))%1?[]:[y,x]+' ')+g(x):[])(n)

```

Or **60 bytes** with 0-terminated, encapsulated arrays:

```
n=>p=>(g=x=>x--&&((y=(x**p+n)**(1/p))%1?g(x):[y,x,g(x)]))(n)

```

This would output `[ 9, 7, [ 6, 2, 0 ] ]` for **f(32)(2)**.

### Test cases

```
let f =

n=>p=>(g=x=>x--?((y=(x**p+n)**(1/p))%1?[]:[y,x]+' ')+g(x):[])(n)

console.log(f(50)(2))
console.log(f(32)(2))
console.log(f(7)(3))
console.log(f(665)(6))
```
> 2 votes

# Answer
# Pyth, 14 bytes

```
f/.+^RvzTQ^SQ2

```

**Try it here!, Alternative!**
> 2 votes

# Answer
# Octave, 80 bytes

```
function r=f(n,p)[X Y]=meshgrid(1:n,1:n);r=[X(:) Y(:)](X(:).^p-Y(:).^p==n,:);end

```

Try it online!
> 1 votes

# Answer
# Perl 6, 45 bytes

```
->\k,\n{grep * **n-* **n==k,flat 1..k X 1..k}

```

Try it online!
> 1 votes

---
Tags: code-golf, math, number, number-theory, integer-partitions
---


title: Sum a Cubically cube's faces

text:
# Question
Title: Sum a Cubically cube's faces
Manually summing a Cubically cube's faces is tedious and time-consuming, sorta like writing code in Cubically itself.

In Most efficient cubifier, I asked you to translate ASCII to Cubically source. One of the answers there uses a cube initialization sequence and then modifies the resulting cube based on the sums of the pre-initialized cube. This method has been used in many Cubically-related programs since. When testing a new initialization sequence, one has to add up all the values on all the faces, which usually takes two or three minutes.

Your task is to automate this process for us!

You will take two inputs, an integer `n` and a string `c`. These may be read from command line arguments, function arguments, standard input, a file, or any combination of those. `c` will be a Cubically memory cube of size `n` as pretty-printed by the interpreter.

The Cubically interpreter dumps its cube to STDERR upon program termination, formatted nicely for simple viewing. Run an empty program in the Cubically interpreter and open the debug section to see the cube dump of an initialized cube. Add an argument `4` to see a 4x4x4, or `5` to see a 5x5x5, etc.

If `n` is 3, `c` will follow this format (the integers will be variable):

```
   000
   000
   000
111222333444
111222333444
111222333444
   555
   555
   555

```

Spaces, newlines, and all. If `n` is 4, `c` will look like this (also with variable integers):

```
    0000
    0000
    0000
    0000
1111222233334444
1111222233334444
1111222233334444
1111222233334444
    5555
    5555
    5555
    5555

```

Et cetera.

Your program will output six integers. The first integer will be the sum of all the numbers on the top face.

```
   000
   000          top face
   000
111222333444    left, front, right, and back faces, respectively
111222333444
111222333444
   555
   555          bottom face
   555

```

The second integer will be the sum of the left face, the third the front, the fourth the right, the fifth the back and the sixth the bottom.

So if `n` was 3 and `c` was this:

```
   242
   202
   242
000131555313
010121535343
000131555313
   424
   454
   424

```

Your program would output `20 1 14 43 24 33`.

Additional rules:

* The output integers must be delimited by non-integer characters. You may also choose to return an array.
* You may assume that the input is correct - `n` is an integer and `c` is a cube from Cubically's debugging output. So if `n` was `3.0` and `c` was `foo bar`, your program could break and still be valid.
* Your program only needs to work for `n > 1` and `n < 1260`. It *may* (attempt to) handle larger or smaller cube sizes, but it is not necessary.

This is , so the shortest code wins! If you need help, feel free to ask in the Cubically chatroom.

# Answer
# Jelly, ~~16~~ ~~14~~ 13 bytes

3 bytes thanks to Erik the Outgolfer.

```
ḟ⁶ỴV€€sS€ẎsS€

```

Try it online!
> 6 votes

# Answer
# Python 2, 155 150 147 123 121 120 bytes

Could probably be golfed quite a bit

**Edit:** -5 bytes by using a better method for removing the whitespaces

**Edit:** -3 bytes thanks to @Leaky Nun

**Edit:** -24 bytes by not removing whitespaces

**Edit:** -2 bytes by exploiting precedence

```
lambda n,a:[sum(sum(map(int,b[j*n:][:n]))for b in a.split("\n")[i*n:][:n])for i in range(3)for j in range(~i%2,i%2*2+2)]

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 16 bytes

```
¹|ðм€Sôεø¹ô€OO}˜

```

Try it online!
> 4 votes

# Answer
# Octave, ~~64~~ ~~59~~ 54 bytes

```
@(c,n)sum(im2col(c'-48,[n n],'distinct'))([2 5:8 10])

```

Try it online!

Previous answer:

```
@(c,n)sparse(kron((1:4)+[0;4;8],!!e(n)),1,c-48)([2 5:8 10])

```

Try it online!

Returns an array as output.
> 3 votes

# Answer
# Husk, 15 bytes

3 s and 2 `m`s

```
mṁṁiṁoC⁰TC⁰mf±¶

```

Try it online!

### Explanation

```
                  Takes input as two arguments, the first being n, the second, the cube
              ¶   Split second argument into a list of lines
           m      For each line
            f±    keep only the digits (remove spaces)
         C⁰       Cut into lists of length n
    ṁ             Map then concatenate
        T           transpose
     oC⁰            then cut into lists of length n
mṁṁi              Takes list of lists of strings (or, in Husk, a list of lists of lists of chars) and returns the sum of the digits in each list
m                 Map function over list of lists
 ṁ                  map then sum
  ṁ                   map then sum
   i                  convert character to integer

```
> 3 votes

# Answer
# Perl 5, 66 + 1 (-n) = 67 bytes

```
$j=$k<6?$k++/3:5;s/\d{3}/';$r[$j++]+='.$&=~s|.|+$&|gr/gee}{say"@r"

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~137~~ 127 bytes

-10 bytes thanks to @Halvard Hummel

```
lambda x,n:[sum(sum(map(int,x.split('\n')[b+j][a:a+n]))for j in range(n))for a,b in[[n,0],[0,n],[n,n],[2*n,n],[3*n,n],[n,2*n]]]

```

Try it online!
> 2 votes

# Answer
# Haskell, 128 bytes

```
s n c=filter(>=0)$map(\[x,y]->sum$map(\[v,w]->fromEnum((lines c)!!(x*n+v)!!(y*n+w))-48)$n%n)$3%4
n%m=sequence[[0..n-1],[0..m-1]]

```

Accepts a string with line breaks.
> 1 votes

# Answer
# APL (Dyalog Classic), ~~30~~ 27 bytes

```
{+/⍎¨6(⍺*2)⍴⍉⊃,⌿3⍺⍴⍵⊂⍨⍵∊⎕D}

```

Shaved off 3 bytes thanks to @Adám

is n  is c

## Explanation

```
                        ⍵⊂⍨⍵∊⎕D   c partitioned by ⎕D (digits 0..9)
                    3⍺⍴           reshape into 3 by n matrix
                 ,⌿              concatenate on first axis (results in n vectors)
              ⍉⊃                  ravel transpose mix (results in a simple string with all digits in side order)
      6(⍺*2)⍴                     reshape into 6 by n squared matrix (one row per side)
 +/⍎¨                            sum rows execute each (execute will turn characters into numbers)

```

Try it online!
> 1 votes

# Answer
# PowerShell, 236 bytes

```
param($n,$z)
function f($y){$y-replace' '-split'(.)'-ne''-join'+'|iex}
$a=$z-split"`n"
f $a[0..($n-1)]
$a[$n..(2*$n-1)]|%{$x="($('.'*$n))";$1,$2,$3,$4=$_-split$x-ne'';$h+=$1;$i+=$2;$j+=$3;$k+=$4}
$h,$i,$j,$k|%{f $_}
f $a[(2*$n)..(3*$n)]

```

Try it online!

Ooof, this is long. But, splitting and slicing of strings isn't one of PowerShell's strong suits, so I guess it's somewhat expected. Also -- So. Many. Dollars.

Takes in parameters `$n` and `$z` as the size and cube net, respectively. Then constructs a function that is used throughout. Here, we're removing spaces, splitting on each individual digit, removing the empty characters in between, joining all the characters together with a `+`, and then executing the resulting statement to get a number. For example, this turns `"123"` into `1+2+3` which when executed is `6`.

The next line `split`s the input cube net on newlines, storing the result into array `$a`. We then perform the function on the first `$n` lines and output the top face of the cube.

For the next set, we need to splice the strings based on the cube size. So, we loop through each line, constructing `$x` as the appropriate regex pattern (e.g., for size `$n=3` this will be `"(...)"`), split the string based on that pattern, again removing empty elements, and store those into four variables representing the four faces. Those are then string concatenated onto `h` through `k`.

The next line then ships `h` through `k` through the function to output the sides (left, front, right, back) of the cube.

Finally, we run the last `$n` lines through the function to output the bottom face of the cube.

All of the numbers are left on the pipeline, and output is implicit.
> 1 votes

# Answer
# Cubically, 19 bytes

```
r%0@%1@%2@%3@%4@%5@

```

Takes the cube from STDIN and the size as a command-line argument to the interpreter. Outputs the sum of the top face, a null byte, the left face, a null byte, ... the bottom face, and a null byte.

Try it online! ...which apparently displays null bytes as some sort of whitespace on my browser.

This language wasn't made for this challenge, but the challenge was made for the language.... is it still cheating? ;)
> 0 votes

---
Tags: code-golf, rubiks-cube, cubically
---


# Question
Title: Is this a three-digit number ending in one?
Given a nonnegative integer, return whether it is a three digit number ending in one, in any consistent integer base. In other words, the number needs to be represented in base-N, N being an integer greater than zero.

## Rules

* This is , so shortest answer wins.
* Since unary behaves weirdly, the behavior with input 310 is undefined.
* Standard loopholes are prohibited.

## Examples

True:

```
5
73
101
1073
17
22
36
55
99

```

False:

```
8
18
23
27
98
90
88
72
68

```

A handful of large numbers:

```
46656 true
46657 true
46658 true
46659 true
46660 true
46661 false
46662 false
46663 true
46664 false
46665 true
46666 true
46667 false
46668 false
46669 false
46670 true
46671 true

```

# Answer
> 10 votes
# JavaScript (ES7), ~~43~~ ~~40~~ 39 bytes

```
f=(n,b)=>n<b*b?0:n%b==1&n<b**3|f(n,-~b)

```

### Test cases

```
f=(n,b)=>n<b*b?0:n%b==1&n<b**3|f(n,-~b)

console.log('[Truthy]')
console.log(f(5))
console.log(f(73))
console.log(f(101))
console.log(f(1073))
console.log(f(17))
console.log(f(22))
console.log(f(36))
console.log(f(55))
console.log(f(99))
console.log(f(46656))
console.log(f(46657))
console.log(f(46658))
console.log(f(46659))
console.log(f(46660))
console.log(f(46663))
console.log(f(46665))
console.log(f(46666))
console.log(f(46670))
console.log(f(46671))

console.log('[Falsy]')
console.log(f(8))
console.log(f(18))
console.log(f(23))
console.log(f(27))
console.log(f(98))
console.log(f(90))
console.log(f(88))
console.log(f(72))
console.log(f(68))
console.log(f(46661))
console.log(f(46662))
console.log(f(46664))
console.log(f(46667))
console.log(f(46668))
console.log(f(46669))
```

### Commented

```
f = (n,           // given n = input
        b) =>     // and using b = base, initially undefined
  n < b * b ?     // if n is less than b²:
    0             //   n has less than 3 digits in base b or above -> failure
  :               // else:
    n % b == 1 &  //   return a truthy value if n is congruent to 1 modulo b
    n < b**3 |    //   and n is less than b³ (i.e. has less than 4 digits in base b)
    f(n, -~b)     //   or the above conditions are true for some greater value of b

```

# Answer
> 10 votes
# Jelly, 7 bytes

```
bRṫ€3ċJ

```

Returns the number of bases (non-zero being truthy, zero being falsy) in which the input is a three digit number ending in one.

Try it online!

### How it works

```
bRṫ€3ċJ  Main link. Argument: n

 R       Range; yield [1, ..., n].
b        Base; convert n to bases 1, ..., n.
  ṫ€3    Tail each 3; remove the first two elements of each digit array.
      J  Indices of [n]; yield [1].
     ċ   Count the number of times [1] appears in the result to the left.

```

# Answer
> 7 votes
# Python 3, ~~50~~ 47 bytes

-2 bytes thanks to @LeakyNun
-1 byte thanks to @Dennis

```
lambda n:any(i>n/i/i>n%i==1for i in range(2,n))

```

Try it online!

# Answer
> 6 votes
# Haskell, ~~41~~ 40 bytes

```
f n=or[mod n k==1|k<-[2..n],k^2<n,n<k^3]

```

*Thanks to @Zgarb for golfing off 1 byte!*

Try it online!

# Answer
> 5 votes
# Brachylog, 10 bytes

```
≥ℕ≜;?ḃ₍Ṫt1

```

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~11~~ 8 bytes

Saved 3 bytes thanks to *Adnan*.

```
Lв3ù€θ1å

```

Try it online!

**Explanation**

```
Lв            # convert input to bases [1 ... input]
  ʒg3Q}       # keep only elements of length 3
       €θ     # get the last item of each
         1å   # is there any 1?

```

# Answer
> 3 votes
# Jelly, 12 bytes

```
bRµL€żṪ€3,1e

```

Try it online!

# Answer
> 3 votes
# Mathematica, 43 bytes

```
!FreeQ[IntegerDigits[#,2~Range~#],{_,_,1}]&

```

Try it online!

or Try it online! (large numbers)

*Martin Ender saved 3 bytes*

# Answer
> 3 votes
# Clean, ~~58~~ 56 bytes

***-2*** *thanks to Dennis*

```
import StdEnv
@n=or[n>m^2&&n<m^3&&n rem m==1\\m<-[2..n]]

```

Try it online!

# Answer
> 3 votes
## Wolfram Language (Mathematica), 35 bytes

```
Or@@Array[x~Mod~#==1<x/#^2<#&,x=#]&

```

Try it online!

Explicitly checks whether **n % i = 1** and **i2 \< n \< i3** for any possible base **i**. For golfing purposes, the inequality is rearranged to **1 \< n/i2 \ 2 votes
# Husk, 10 bytes

```
€;1ṠMo↓2Bḣ

```

Try it online! Pretty close to the Jelly answer of Dennis.

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~21~~ ~~20~~ 14 bytesSBCS

-5 thanks to @ngn.

Purely arithmetic solution (doesn't actually do any base conversions) and thus very fast.

```
3∊⊢(|×∘⌈⍟)⍨1↓⍳

```

Try it online!

`⊢(``)⍨1↓⍳` on one dropped from the **ɩ**ndices 1…argument and the argument, apply:

`|` the division remainders

`×∘⌈` times the rounded-up

logN Argument

`3∊` is three a member of that?

# Answer
> 1 votes
# Pyth, 10 bytes

```
}]1>R2jLQS

```

**Verify all the test cases.**

# Answer
> 1 votes
# Husk, 15 bytes

```
V§&o=1→o=3LṠMBḣ

```

Try it online!

### Explanation

```
V§&(=1→)(=3L)ṠMBḣ  -- implicit input, for example: 5
             ṠMB   -- map "convert 5 to base" over..
                ḣ  --   range [1..5]
                   -- [[1,1,1,1,1],[1,0,1],[1,2],[1,1],[1,0]]
V                  -- does any of the elements satisfy the following
 §&( 1 )( 2 )      --   apply functions 1,2 and join with & (logical and)
         =3L       --     is length equals to 3?
    =1→            --     is last digit 1?

```

# Answer
> 1 votes
# PHP, 48+1 bytes

```
while(++$b**2<$n=$argn)$n%$b-1|$n>$b**3||die(1);

```

exits with `0` for falsy (or input `3`), `1` for truthy.
Run as pipe with `-nR` or try it online.

# Answer
> 1 votes
# C, 60 bytes

A function that returns non-zero if the argument can be represented as a three-digit number ending in 1:

```
i,j;f(n){for(j=0,i=sqrt(n);i>cbrt(n);)j+=n%i--==1;return j;}

```

Note: this works with GCC, where the functions are built-in. For other compilers, you probably need to ensure that the argument and return types are known:

```
#include<math.h>

```

# Explanation

The lowest base in which `n` is represented in 3 digits is `⌊∛n⌋`, and the lowest base in which `n` is represented in 2 digits is `⌊√n⌋`, so we simply test whether the number is congruent to 1 modulo any bases in the 3-digit range. We return the count of the number of bases satisfying the condition, giving a non-zero (truthy) or zero (falsy) value as appropriate.

# Test program

Pass any number of inputs as positional parameters:

```
#include<stdio.h>
int main(int c,char**v)
{
    while(*++v)
        printf("%s => %d\n", *v, f(atoi(*v)));
}

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 19 bytesSBCS

Dennis' method.

```
(⊂,1)∊2↓¨⊢⊥⍣¯1¨⍨1↓⍳

```

Try it online!

`(⊂,1)∊` Is `[1]` a member of

`2↓¨` two elements dropped from each of

`⊢⊥⍣¯1¨⍨` the argument represented in each of the bases

`1↓⍳` one dropped from the **ɩ**ndices 1 through the argument?

# Answer
> 0 votes
# Julia, 31 bytes

```
n->any(i>n/i^2>n%i==1for i=2:n)

```

Try it online!

# Answer
> 0 votes
# Pyt, ~~35~~ 33 bytes

```
←ĐĐ3=?∧∧:ŕĐ2⇹Ř⇹Ľ⅟⌊⁺3=⇹Đ2⇹Ř%*ž1⇹∈;

```

Explanation:

```
←ĐĐ                                             Push input onto stack 3 times
   3=?  :                       ;               If input equals 3, execute code after the question mark;otherwise, execute code after the colon. In either case, afterwards, execute the code after the semicolon
      ∧∧                                        Get 'True'
        :                                       Input not equal to 3
         ŕ                                      Remove 'False'
          Đ2⇹Ř                                  Push [2,3,...,n]
              ⇹Ľ⅟⌊⁺                             Push [floor(log_2(n))+1,floor(log_3(n))+1,...,floor(log_n(n))+1]
                   3=                           Is each element equal to 3
                     ⇹                          Swap the top two elements on the stack (putting n back on top)
                      Đ2⇹Ř                      Push [2,3,...,n]
                          %                     Push [n%2,n%3,...,n%n]
                           *                    Multiply [n%x] by the other array (i.e. is floor(log_x(n))+1=3?)
                            ž                   Remove all zeroes from the array
                             1⇹∈                Is 1 in the array?
                                ;               End conditional
                                                Implicit print

```

Try it online!

# Answer
> 0 votes
# \>\<\>, 42 bytes

```
1<v?)}:{*::+
n~\1-:::**{:}):?!n~:{:}$%1=:?

```

Try it online!

Returns `10` for truthy, `00` for falsey.

---
Tags: code-golf, number-theory, decision-problem, base-conversion
---


title: Finding Lonely Primes

text:
# Question
Title: Finding Lonely Primes
Lonely primes (as I call them) are primes, where given a number grid with width `w ≥ 3`, are primes which do not have any other primes adjacent to them orthogonally or diagonally.

For example, if we take this grid where `w = 12` (primes highlighted in bold):

```
1   **2**   **3**   4   **5**   6   **7**   8   9   10  **11**  12
**13**  14  15  16  **17**  18  **19**  20  21  22  **23**...
 ...86  87  88  89  90  91  92  93  94  95  96
**97**  98  99  100 **101** 102 **103** 104 105 106 **107** 108
**109** 110 111 112 **113** 114 115 116 117 118 119 120
```

You can see that only the two primes **103** and **107** have no primes orthogonally or diagonally adjecant whatsoever. I've skipped over a section because there's no lonely primes there. (except 37, actually)

Your task is to, given two inputs `w ≥ 3` and `i ≥ 1`, determine the first lonely prime in a number grid with width `w`, where said lonely prime must be greater than or equal to `i`. Inputs may be taken in any reasonable format (including taking them as strings). It is guaranteed there will be a lonely prime for width `w`.

The grid doesn't wrap around.

Examples:

```
w  i   output
11 5   11
12 104 107
12 157 157
9  1   151
12 12  37

```

As this is , shortest code wins!

# Answer
# C (gcc), ~~159~~ ~~158~~ ~~149~~ 145 bytes

* Saved a byte thanks to xanoetux; removing one newline character.
* Saved ~~nine~~ thirteen bytes thanks to ceilingcat; golfing a break condition.

```
P(n,d,b){for(d=b=1<n;n>++d;)b*=n%d>0;n=b;}F(w,i){w=P(i)&!(P(i-w)|P(i+w)|i%w>1&(P(--i)|P(i-w)|P(i+w))|++i%w>0&(P(++i)|P(i-w)|P(i+w)))?i-1:F(w,i);}

```

Try it online!
> 8 votes

# Answer
# JavaScript (ES6), ~~116~~ 104 bytes

Takes input in currying syntax `(w)(i)`.

```
w=>g=i=>!(C=(k,n=d=i+k)=>n>0?n%--d?C(k,n):d>1:1)(0)&[i,x=1,i-1].every(j=>C(x-w)&C(w+x--)|j%w<1)?i:g(i+1)

```

### Test cases

```
let f =

w=>g=i=>!(C=(k,n=d=i+k)=>n>0?n%--d?C(k,n):d>1:1)(0)&[i,x=1,i-1].every(j=>C(x-w)&C(w+x--)|j%w<1)?i:g(i+1)

console.log(f(11)(  5)) // 11
console.log(f(12)(104)) // 107
console.log(f(12)(157)) // 157
console.log(f( 9)(  1)) // 151
console.log(f(12)( 12)) // 37
```

### Commented

```
w =>                    // main function, taking w
  g = i =>              // g = recursive function, taking i
    !(                  //
      C = (             // define C:
        k,              //   a function taking an offset k
        n = d = i + k   //   and using n and d, initialized to i + k
      ) =>              //
        n > 0 ?         //   if n is strictly positive:
          n % --d ?     //     decrement d; if d does not divide n:
            C(k, n)     //       do a recursive call
          :             //     else:
            d > 1       //       return true if d > 1 (i.e. n is composite)
        :               //   else:
          1             //     return true (n is beyond the top of the grid)
    )(0) &              // !C(0) tests whether i is prime (or equal to 1, but this is safe)
    [                   // we now need to test the adjacent cells:
      i,                //   right side: i MOD w must not be equal to 0
      x = 1,            //   middle    : always tested (1 MOD w is never equal to 0)
      i - 1             //   left side : (i - 1) MOD w must not be equal to 0
    ]                   // for each value j defined above,
    .every(j =>         // and for x = 1, 0 and -1 respectively:
      C(x - w) &        //   test whether i - w + x is composite
      C(w + x--) |      //            and i + w + x is composite
      j % w < 1         //   or j MOD w equals 0, so that the above result is ignored
    ) ?                 // if all tests pass:
      i                 //   return i
    :                   // else:
      g(i + 1)          //   try again with i + 1

```
> 5 votes

# Answer
# Python 2, 144 bytes

```
f=lambda w,i,p=lambda n:all(n%j for j in range(2,n))*(n>1):i*(any(map(p,~-i%w*(i+~w,i-1,i+w-1)+(i-w,i+w)+i%w*(i-w+1,i+1,i-~w)))<p(i))or f(w,i+1)

```

Try it online!

Arguments in order: `w`, `i`.

No external modules used here.

# Python 2 \+ sympy, 127 bytes

```
import sympy
f=lambda w,i,p=sympy.isprime:i*(any(map(p,~-i%w*(i+~w,i-1,i+w-1)+(i-w,i+w)+i%w*(i-w+1,i+1,i-~w)))<p(i))or f(w,i+1)

```

Try it online!

Not worthy of a different post, since the only difference here is that it uses `sympy.isprime` instead of a manually implemented prime check function.
> 2 votes

# Answer
# MATL, 38 bytes

```
xx`@1G*:5MeZpt3Y6Z+>3LZ)ft2G<~)X<a~}2M

```

Try it online! Or verify all test cases.

### Explanation

The code essentially consists of a loop that keeps enlarging the grid as described in the challenge by one row at each iteration.

After creating the grid at each iteration, the last row is removed (we cannot know if those primes are lonely or not) and the remaining numbers are tested to see if at least one lonely prime exists. This is done via 2D convolution.

If there is some lonely prime we exit the loop and output the first such prime. Else we proceed with the next iteration, which will try a larger grid.

(The code actually uses a transposed version of the grid, which is enlarged by columns instead of by rows.)

```
xx        % Take two inputs (implicit): w, i. Delete them. They get copied
          % into clipboard G
`         % Do...while
  @       %   Push iteration index (1-based)
  1G      %   Push w
  *       %   Multiply
  :       %   Range from 1 to that
  5M      %   Push w again (from automatic clipboard M)
  e       %   Reshape into a matrix with w rows in column-major order
  Zp      %   Is prime? Element-wise
  t       %   Duplicate
  3Y6     %   Push neighbour mask: [1 1 1; 1 0 1; 1 1 1]
  Z+      %   2D convolution, maintaining size
  >       %   Greater than? Element-wise. Gives true for lonely primes
  3LZ)    %   Remove the last column
  f       %   Find linear indices of nonzeros
  t       %   Duplicate
  2G      %   Push i
  <~      %   Not less than?
  )       %   Use as logical index: this removes lonle primes less than i
  X<      %   Minimum. This gives either empty or a nonzero value
  a~      %   True if empty, false if nonzero. This is the loop condition.
          %   Thus the loop proceeds if no lonely prime was found
}         % Finally (execute on loop exit)
  2M      %   Push the first found lonely prime again
          % End (implicit). Display (implicit)

```
> 2 votes

# Answer
# Julia 0.6, 135 bytes

```
using Primes
f(w,i,p=isprime)=findfirst(j->(a=max(j-1,0);b=min(j+1,w);c=a:b;!any(p,v for v=[c;c+w;c-w]if v>0&&v!=j)&&p(j)&&j>=i),1:w*w)

```

TIO doesn't have the `Primes` package. It's 5 bytes shorter if I'm allowed to return all lonely primes (`findfirst` becomes `find`). Julia's attempt to move functionality out of `Base` is hurting golfing (not a goal of Julia), `Primes` was included in 0.4.

### Ungolfed (mostly)

```
function g(w,i)
    for j=i:w*w
        a,b=max(j-1,0),min(j+1,w)
        c=a:b
        !any(isprime,v for v=[c;c+w;c-w]if v>0&&v!=j)&&isprime(j)&&return j
    end
end

```
> 1 votes

# Answer
# Perl 6, ~~113~~ 104 bytes

```
->\w,\i{first {is-prime $_&none $_ «+«flat -w,w,(-w-1,-1,w-1)xx!($_%w==1),(1-w,1,w+1)xx!($_%%w)},i..*}

```

Try it online!
> 1 votes

# Answer
# Jelly, 20 bytes

```
+‘ÆRœ^ḷ,ḷ’dạ/Ṁ€ṂḊð1#

```

Try it online!

### How it works

```
+‘ÆRœ^ḷ,ḷ’dạ/Ṁ€ṂḊð1#  Main link. Left argument: i. Right argument: w.

                 ð    Combine the links to the left into a chain and begin a new,
                      dyadic chain with arguments i and w.
                  1#  Call the chain to the left with left argument n = i, i+1, ...
                      and right argument w until 1 of them returns a truthy value.
                      Return the match.
+                       Yield n+w.
 ‘                      Increment, yielding n+w+1.
  ÆR                    Yield all primes in [1, ..., n+w+1].
      ḷ                 Left; yield n.
    œ^                  Multiset OR; if n belongs to the prime range, remove it; if
                        it does not, append it.
       ,ḷ               Wrap the resulting array and n into a pair.
         ’              Decrement all involved integers.
          d             Divmod; map each integer k to [k/w, k%w].
           ạ/           Reduce by absolute difference, subtracting [n/w, n%w] from
                        each [k/w, k%w] and taking absolute values.
             Ṁ€         Take the maximum of each resulting pair.
                        A maximum of 0 means that n is not prime.
                        A maximum of 1 means that n has a prime neighbor.
               Ṃ        Take the minimum of the maxima.
                Ḋ       Dequeue; map the minimum m to [2, ..., m].
                        This array is non-empty/truthy iff m > 1.

```
> 1 votes

# Answer
# Jelly,  ~~30~~  29 bytes

My guess is this is probably beatable by a fair margin

```
ÆPŒR+€×¥+©⁸’:⁹Ġ®ṁLÞṪFÆPS’¬ð1#

```

A dyadic link taking `i` on the left and `w` on the right which returns the lonely prime.

**Try it online!**

### How?

```
ÆPŒR+€×¥+©⁸’:⁹Ġ®ṁLÞṪFÆPS’¬ð1# - Link: i, w                     e.g. 37, 12
                           1# - find the 1st match starting at i and counting up of...
                          ð   - ...everything to the left as a dyadic link
                              - (n = i+0; i+1; ... on the left and w on the right):
ÆP                            -   is i prime: 1 if so, 0 if not     1
  ŒR                          -   absolute range: [-1,0,1] or [0]   [-1,0,1]
       ¥                      -   last two links as a dyad (w on the right):
      ×                       -     multiply (vectorises)           [-12,0,12]
    +€                        -     add for €ach       [[-13,-1,11],[-12,0,12],[-11,1,13]]
                              -     - i.e. the offsets if including wrapping
          ⁸                   -   chain's left argument, i
        +                     -   add                  [[24,36,48],[25,37,49],[26,38,50]]
                              -     - i.e. the adjacents if including wrapping
         ©                    -   copy to the register
           ’                  -   decrement            [[23,35,47],[24,36,48],[25,37,49]]
             ⁹                -   chain's right argument, w
            :                 -   integer division               [[1,2,3],[2,3,4],[2,3,4]]
              Ġ               -   group indices by value         [[1],[2,3]]
                              -     - for a prime at the right this would  be [[1,2],[3]]
                              -     - for a prime not at an edge it would be [[1,2,3]]
               ®              -   recall from register [[24,36,48],[25,37,49],[26,38,50]]
                ṁ             -   mould like           [[24,36,48],[[25,37,49],[26,38,50]]]
                  Þ           -   sort by:
                 L            -     length             [[24,36,48],[[25,37,49],[26,38,50]]]
                   Ṫ          -   tail                             [[25,37,49],[26,38,50]]
                              -     - i.e the adjacents now excluding wrapping
                    F         -   flatten                          [25,37,49,26,38,50]
                     ÆP       -   is prime? (vectorises)           [0,1,0,0,0,0]
                       S      -   sum                              1
                        ’     -   decrement                        0
                         ¬    -   not                              1

```
> 0 votes

# Answer
# Clean, ~~181~~ ... 145 bytes

```
import StdEnv
@w i=hd[x+y\\y<-[0,w..],x<-[1..w]|x+y>=i&&[x+y]==[a+b\\a<-[y-w,y,y+w]|a>=0,b<-[x-1..x+1]|0<b&&b<w&&all((<)0o(rem)(a+b))[2..a+b-1]]]

```

Try it online!

**Ungolfed:**

```
@ w i
    = hd [
        x+y
        \\ y <- [0, w..]
        ,  x <- [1..w]
        | x+y >= i && [x+y] == [
            a+b
            \\ a <- [y-w, y, y+w]
            | a >= 0
            ,  b <- [x-1..x+1]
            | 0 < b && b < w && all ((<) 0 o (rem) (a+b)) [2..a+b-1]
            ]
        ]

```
> 0 votes

# Answer
# Java 8, ~~176~~ 165 bytes

```
w->i->{for(;!p(i)|p(i-w)|p(i+w)|i%w>1&(p(--i)|p(i-w)|p(i+w))|++i%w>0&(p(++i)|p(i-w)|p(i+w)););return~-i;}boolean p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n>1;}

```

Port of *Jonathan Frech*' C answer.
-11 bytes thanks to *@ceilingcat*.

Try it online.
> 0 votes

---
Tags: code-golf, number, primes, grid
---


title: Spiral out the Alphabet!

text:
# Question
Title: Spiral out the Alphabet!
Look at the following string. Notice a pattern?

```
ABEFNOPEFGH
DC G  Q   I
M  H  R   J
LKJI  S   K
D     T   L
C     U   M
BAZYXWV   N
E         O
D         P
C         Q
BAZYXWVUTSR

```

As some might have noticed, it's basically a spiral of the alphabet, where the distances between rows / columns are gradually increasing by 1 space / newline.

# Rigorous definition

* Let's have a counter **c**, which is initially 0.
* We write out the first **c + 1** letters of the alphabet from left to right: `A`.
* Then, from top to bottom the next **(c + 1)(c + 2)/2** letters (add `B`): `AB`.
* From left to right, the next **(c + 1)(c + 2)/2** (add `C`):

```
AB
 C

```
* And from bottom to top, the next **c + 1** letters (add `D`):

```
AB
DC

```
* Reached the end of the cycle. Hence, let's increment **c** (which becomes 1). Then, it starts back from the first step, the only difference being that instead of using the *first **c + 1*** letters of the alphabet, we use the *next **c + 1*** letters, starting from the last element of this cycle (`D` in this case, so we continue with `EFG...`). When `Z` is reached, it cycles back from `A`.

# Task

Given an integer **N** (which is positive for 1-indexing or non-negative for 0-indexing), output the first **N** cycles of the spiral.

# Rules

* You can either use the lowercase or the uppercase alphabet, but your choice must be consistent (only use one of them, mixing is not allowed).
* You can take input and provide output through any of the standard methods, in any programming language, while noting that these loopholes are forbidden by default.
* Acceptable output formats: multiline string, a list of strings representing lines, a list containing multiple lists of characters, each representing one line, or anything else you find suitable. In case you don't choose the first format, it would be nice to include a pretty-print version of your code.
* This is , so the shortest code in bytes (in each language) which fulfils the requirements wins!

---

# Test cases

The input integer will be separated by its corresponding output through a newline, and the tests will be separated using dashes. Note that these are 1-indexed.

```
1

AB
DC

--------

2

ABEF
DC G
M  H
LKJI

--------

3

ABEFNOP
DC G  Q
M  H  R
LKJI  S
D     T
C     U
BAZYXWV

-------

4

ABEFNOPEFGH
DC G  Q   I
M  H  R   J
LKJI  S   K
D     T   L
C     U   M
BAZYXWV   N
E         O
D         P
C         Q
BAZYXWVUTSR

-------
5

ABEFNOPEFGHFGHIJ
DC G  Q   I    K
M  H  R   J    L
LKJI  S   K    M
D     T   L    N
C     U   M    O
BAZYXWV   N    P
E         O    Q
D         P    R
C         Q    S
BAZYXWVUTSR    T
R              U
Q              V
P              W
O              X
NMLKJIHGFEDCBAZY

------

6

ABEFNOPEFGHFGHIJSTUVWX
DC G  Q   I    K     Y
M  H  R   J    L     Z
LKJI  S   K    M     A
D     T   L    N     B
C     U   M    O     C
BAZYXWV   N    P     D
E         O    Q     E
D         P    R     F
C         Q    S     G
BAZYXWVUTSR    T     H
R              U     I
Q              V     J
P              W     K
O              X     L
NMLKJIHGFEDCBAZY     M
S                    N
R                    O
Q                    P
P                    Q
O                    R
NMLKJIHGFEDCBAZYXWVUTS

```

# Answer
# Charcoal, 31 bytes

```
Ｆ⮌…⁰ＮＢ⁺²⊘×ι⁺³ι⭆α§α⁺λ÷×ι⊕×ι⁺⁹⊗ι⁶

```

Try it online! Link is to verbose version of code. Note: The deverbosifier outputs a trailing separator for some reason. Explanation:

```
Ｆ⮌…⁰ＮＢ

```

Draw boxes in reverse order of size (largest to smallest).

```
⁺²⊘×ι⁺³ι

```

Calculate the size of the box.

```
⭆α§α⁺λ

```

Draw the border of the box using a rotated alphabet.

```
÷×ι⊕×ι⁺⁹⊗ι⁶

```

Calculate the letter that would appear at the top left of the box (0-indexed).
> 9 votes

# Answer
# Python 2, 176 bytes

```
n=input()
k=n*-~n/2+1
a=eval(`[[' ']*k]*k`)
x=y=z=0
for s in range(4*n+4):exec s/4*(s/4+1)/2*"if'!'>a[y][x]:a[y][x]=chr(z%26+65);z+=1\nx+=abs(2-s%4)-1;y+=s%2-s%4/3*2\n"
print a

```

Try it online!

## Explanation

We construct an empty array of spaces of the right size, then move over it like this, starting in the top-left corner:

* 1 step →, 1 step ↓, 1 step ←, 1 step ↑
* 3 steps →, 3 steps ↓, 3 steps ←, 3 steps ↑
* 6 steps →, 6 steps ↓, 6 steps ←, 6 steps ↑
* 10 steps →, 10 steps ↓, 10 steps ←, 10 steps ↑
*

Every time we find a blank cell, we put a letter there and cycle to the next letter in the alphabet.

In the code, `s%4` is the direction (→↓←↑), and we step this many times:

```
TriangularNumber(s/4) = s/4*(s/4+1)/2.

```

## Golf opportunities

* Is there a shorter way to map `s%4` to `1,0,-1,0` than `abs(2-s%4)-1`?
* Is there a shorter way to map `s%4` to `0,1,0,-1` than `s%2-s%4/3*2`?

## Credits

* Mr. Xcoder saved a byte.
> 6 votes

# Answer
# C,  ~~305~~  281 bytes

*Thanks to @Mr. Xcoder for saving four bytes!*

```
#define L(x,y)l[x][y]=a++%26+65;
#define F for(
c,i,j,a,p;f(n){char**l=calloc(8,i=a=n*n*4);F;i--;memset(l[i],32,a))l[i]=malloc(a);F c=a=p=i=0;c<n;++c){F i=p;i<c+p+!c;)L(j=0,c+i++)F p=i;j<=-~c*(c+2)/2;)L(j++,c+i)F;c+i-1;)L(j-1,c+--i)F i=0;i<=c;)L(j+~i++,0)}F i=0;i<j;)puts(l[i++]);}

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~262~~ ~~260~~ ~~254~~ 245 bytes

```
lambda n:[[[' ',chr(65+(4*(i<j)+sum((i<j)*8+2+I*[5,9][i<j]+sum(2*R(I))for I in R(S(i,j)-1))+[i+j,-i-j][i<j])%26)][max(i,j)==S(i,j)*-~S(i,j)/2or i*j<1]for i in R(1+n*-~n/2)]for j in R(1+n*-~n/2)]
R=range
S=lambda x,y:int((8*max(x,y)+1)**.5+.99)/2

```

Try it online!

New method with more maths!

Returns a list of char-lists.

---

Old version:

# Python 2, ~~322~~ ~~321~~ ~~308~~ 298 bytes

```
R=range
n=input()
w=1+n*-~n/2;r=[w*[' ']for _ in R(w)];r[0][0]='A';l=R(1,w*w*9);c=lambda:chr(65+l.pop(0)%26)
for i in R(n+1):
 w=1+i*-~i/2;W=w-i
 for x in R(W,w):r[0][x]=c()
 for y in R(1,w):r[y][w-1]=c()
 for x in R(1,w):r[w-1][w+~x]=c()
 for x in R(1,w-W):r[w+~x][0]=c()
for l in r:print`l`[2::5]

```

Try it online!
> 2 votes

# Answer
# Perl 5, 177 +2 (-nl) = 179 bytes

2 bytes saved thanks to Xcali

```
sub n{chr 65+$c++%26}@O=(n);while($,++<$_){$_.=$"x$,for@O;push@O,($"x length$O[0])x$,;$O[0]=~s/ /n/eg;s/ $/n/e for@O;1while$O[-1]=~s/.*\K /n/e;s/^ /n/e for reverse@O}print for@O

```

Try it online
> 1 votes

# Answer
# APL (Dyalog Classic), 47 bytes

```
(⎕a⍴⍨≢i)@i⍴∘''⊃⌈/i←∪+\↓1⍪⊃⍪⌿(+\⍳⎕)⌿¨⊂⍪∘-⍨∘.≠⍨⍳2

```

Try it online!
> 0 votes

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


title: Follow the dots

text:
# Question
Title: Follow the dots
# The Challenge

Given a rectangular grid of characters

```
A B C D E
F G H I J
K L M N O
P Q R S T

```

and a grid with the same dimensions of dots and spaces

```
. .     .
  .   . .
  .   .
  . . .

```

Output the string which is generated by following the dots through the grid starting in the upper left corner. This example would yield `ABGLQRSNIJE`

## Notes

* You may take the input grids as 2D-arrays or the closest alternative in your language instead of a multiline string.
* You may use the NULL value of your language instead of spaces. But you have to use dots to mark the path.
* You don't need to separate dots on the same line with spaces. I just added them for readability.
* The smallest possible grid has the size 1x1.
* The start and end dot will have only one neighbour. The dots between them will always have exact two vertical or horizontal neighbours. This guarantees that the path is unambiguously.
* The path will not go diagonal.
* The characters in the grid will be either all upper- or lowercase characters in the range `[a-z]` whatever is most convenient for you.
* The path will always start in the upper left corner.

# Rules

# Test cases

### Grid #1

```
A B C A B C W
D E F G H U Q
X L U S D Q Z
A S U K W X I
W U K O A I M
A I A I O U P

```

```
. .
  . . .
      .
. . . .
.
.
=> ABEFGSKUSAWA

```

```
. . . . . . .
            .
. . .       .
.   . .     .
.           .
. . . . . . .
=> ABCABCWQZIMPUOIAIAWAXLUUK

```

### Grid #2

*Note the triple spaces in the second lines of the first and second examples.*

```
A B
C D

```

```
.

=> A

```

```
. .

=> AB

```

```
.
. .
=> ACD

```

### Grid #3

```
A

```

```
.
=> A

```

**Happy Coding!**

# Answer
# APL, 63 bytes

```
{⍺[(⊂1 1){×≢⍵:⍺,(V/⍵)∇⍵/⍨~V←(+=⌊/)+/¨2*⍨⍺-⍵⋄⍺}1↓(,⍵='.')/,⍳⍴⍵]}

```

This is a function that takes two character matrices (they must be matrices), the character grid as its left argument and the dots grid as its right argument. The matrix of dots may be smaller than the matrix of characters.

Explanation:

* `(,⍵='.')/,⍳⍴⍵`: get the positions of the dots, in row-column order
* `1↓`: drop the first one (it is known to be at `1 1`)
* `(⊂1 1){`...`}`: starting from `1 1`, run the following function, which follows the path (its left argument is its current position, its right argument are unvisited positions). It works by selecting the nearest unvisited dot each time. (If the assumptions from the question hold, this is correct.)
    + `×≢⍵:`: if there are still unvisited positions:
        - `+/¨2*⍨⍺-⍵`: find the Manhattan distance between each position and the current position
        - `V←(+=⌊/)`: for each position, see if its distance is equal to the smallest distance, and store this in `V`.
        - `⍵/⍨~`: select all positions for which this is not the case, these are the fields to visit next
        - `(V/⍵)`: find the position for which it *is* the case, this will be the next field
        - : run the function again with these new arguments
        - `⍺,`: the result is the current position, followed by the result of doing this for the rest of the list
    + `⋄⍺`: otherwise, just return the current position and stop (it's the last one)
* `⍺[`...`]`: for each position, select the corresponding element in the character grid.

Test cases:

```
      f←{⍺[(⊂1 1){×≢⍵:⍺,(V/⍵)∇⍵/⍨~V←(+=⌊/)+/¨2*⍨⍺-⍵⋄⍺}1↓(,⍵='.')/,⍳⍴⍵]}
      ⍝ example
      g0  ← 4 5⍴'ABCDEFGHIJKLMNOPQRST'
      d0  ← 4 5⍴'..  . . .. . .  ... '
      ⍝ test case 1
      g1  ← 6 7⍴'ABCACBWDEFGHUQXLUSDQZASUKWXIWUKOAIMAIAIOUP'
      d1a ← 6 7⍴'..      ...      .   ....   .      .      '
      d1b ← 6 7⍴'.......      ....   .. ..  ..     ........'
      ⍝ test case 2
      g2  ← 2 2⍴'ABCD'
      d2a ← 1 1⍴'.'
      d2b ← 1 2⍴'..'
      d2c ← 2 2⍴'. ..'
      ⍝ test case 3
      g3  ← 1 1⍴'A'
      d3  ← 1 1⍴'.'

      g0 f d0
ABGLQRSNIJE
      (⊂g1) f¨ d1a d1b
┌────────────┬─────────────────────────┐
│ABEFGSKUSAWA│ABCACBWQZIMPUOIAIAWAXLUUK│
└────────────┴─────────────────────────┘
      (⊂g2) f¨ d2a d2b d2c
┌─┬──┬───┐
│A│AB│ACD│
└─┴──┴───┘
      g3 f d3
A

```
> 4 votes

# Answer
# JavaScript (ES6), 122 bytes

```
c=>g=>c[l=~c.search`
`,i=p=0]+[...g].map(_=>i|!p?c[i=(d=n=>g[i-n-p?i-n:c]>" "&&(p=i)-n)(1)||d(-1)||d(l)||d(-l)]:"").join``

```

## Explanation

Takes the grids as multiline strings.

Feels like a decent attempt but I ran out of time while golfing so it could probably be improved.

```
var solution =

c=>g=>
  c[                            // add the starting letter to the output
    l=~c.search`
`,                              // l = line length
    i=p=0                       // i = current index, p = previous index
  ]+
  [...g].map(_=>                // loop
    i|!p?                       // if we have not finished yet
      c[i=                      // find the next index and return it's letter
        (d=n=>                  // d = function to check for a dot at offset n
          g[
            i-n-p?i-n           // if i - n != p, get the character at index i - n
            :c                  // else get index "c" (will return undefined, not a dot)
          ]>" "                 // if the character is a dot
          &&(p=i)-n             // set p to i and return i - n
        )
        (1)||d(-1)||d(l)||d(-l) // search for the next adjacent dot
      ]
    :""                         // if we have finished, return no letter
  )
  .join``                       // output all the returned letters
```

```
<textarea id="Characters" rows="6" cols="30">ABCABCW
DEFGHUQ
XLUSDQZ
ASUKWXI
WUKOAIM
AIAIOUP</textarea>
<textarea id="Grid" rows="6" cols="30">.......
      .
...   .
. ..  .
.     .
.......</textarea><br />
<button onclick="result.textContent=solution(Characters.value)(Grid.value)">Go</button>
<pre id="result"></pre>
```
> 3 votes

# Answer
# APL (Dyalog Classic), 43 bytes

```
{⍺[11 9∘○¨{⍵∪⍺∩∊⍵+⊂0j1*⍳4}⍣≡∘⊃⍨0j1⊥¨⍸⍵=⊃⍵]}

```

Try it online!
> 1 votes

---
Tags: code-golf, string, grid
---


title: Reconstruct My Matryoshka Dolls

text:
# Question
Title: Reconstruct My Matryoshka Dolls
# Background

A *matryoshka doll* (or Russian nesting doll) is a set of dolls that fit inside of each other. I've accidentally mixed up my collection of matryoshka dolls and I don't remember which one goes inside which.

# Objective

Given a list of *unique* strings, sort them into nested matryoshka dolls. Each string is an individual doll, and a matryoshka doll is a list of strings.

# Rules

Let `min(a,b)` be the lexicographic min of strings `a` and `b`. Let `a ⊂ b` denote that `a` is a substring of `b`. Then,

1. The list of matryoshka dolls must be sorted lexicographically
2. String `a` can *fit* into string `b` if `a ⊂ b`
3. If `a ⊂ b` and `a ⊂ c`, then `a` will go inside `min(b,c)`
4. If both `a ⊂ c` and `b ⊂ c`, but `a ⊄ b` `b ⊄ a`, then only `min(a,b)` will go inside `c`
5. If both `a ⊂ c` and `b ⊂ c`, and also `a ⊂ b`, then only `b` will go inside `c`. I.e., superstrings go before substrings so that the matryoshka isn't prematurely terminated.

# Examples

```
In:
hahaha, hah, lol, lololol, bahaha, bah, haha, ah

Out:
bahaha, bah, ah
hahaha, haha, hah
lololol, lol

In:
aa, aaaa, a, aaaaaaaaaa

Out:
aaaaaaaaaa, aaaa, aa, a

```

# Answer
# Python 2, 298 bytes

```
def f(x,E=enumerate):
 o=[]
 while any(x):
	for k,p in E(x):
	 e=0
	 if sum(i(p,j)for j in x)<1:
		for d,r in E(o):
		 if i(p,r[-1])*((r[-1]<e)or e==0):m,e=d,r[-1]
		if e:o[m]+=[p]
		else:o+=[[p]]
		x[k]=''
 print sorted(o)
i=lambda p,b:(b!=p)*any([p==b[j:j+len(p)]for j in range(len(b)-len(p)+1)])

```

Try it online!

*-28 bytes with tips from @dylnan, bug find by @Dennis, and bug fix by @Mr.Xcoder*
> 2 votes

---
Tags: code-golf, string
---


# Question
Title: Number of leap years between two given years (inclusive)
Is there a better way to calculate the number of leap years between two given years? I want to make my code shorter (in Python). Do you have any suggestions?

Here is my solution:

```
i=int
r=raw_input
t=i(r())
while t:
 b,d=map(i,r().split())
 c=0
 for y in range(b,d+1):
  if y%400==0 or y%4==0 and y%100:c+=1
 print c
 t-=1

```

# Answer
> 6 votes
### Quick wins (-6 bytes)

Using `i=int` actually costs 2 bytes, because the shortened expression is only used twice in the code. We can save 4 other bytes by using `<1` instead of `==0` and removing useless whitespace.

```
r=raw_input
t=int(r())
while t:
 b,d=map(int,r().split())
 c=0
 for y in range(b,d+1):
  if y%400<1or y%4<1and y%100:c+=1
 print c
 t-=1

```

### Getting rid of the for loop (-7 bytes)

Using **sum()**, **map()** and a lambda is shorter than a **for** loop with an additional variable. However, we need an explicit test on `y%100` to turn the result into a boolean.

```
r=raw_input
t=int(r())
while t:
 b,d=map(int,r().split())
 print sum(map(lambda y:y%400<1or y%4<1and y%100>0,range(b,d+1)))
 t-=1

```

### Using a built-in function and tweaking the way input is taken (-16 bytes)

Finally, importing and using `calendar.isleap` saves 7 more bytes. `input()` instead of `int(r())` saves another byte. Dropping `r=raw_input` and using it directly in the loop saves another 4 bytes. Finally, removing all unnecessary newlines saves 4 bytes too.

```
from calendar import*
t=input()
while t:b,d=map(int,raw_input().split());print sum(map(isleap,range(b,d+1)));t-=1

```

Try it online!

*Saved 3 bytes thanks to @user202729*

### Not using a built-in function anymore... (-3 bytes)

```
t=input()
while t:b,d=map(int,raw_input().split());print sum(y%400<1or y%4<1<=y%100for y in range(b,d+1));t-=1

```

Try it online!

All these changes have shortened the source code to **110 bytes**.

---
Tags: code-golf, tips, python
---