title: Output a Magical 8 Trapezium

text:
# Question
Title: Output a Magical 8 Trapezium
Your task is to output a Magical 8 Trapezium:

```
        1 × 8 + 1 = 9
       12 × 8 + 2 = 98
      123 × 8 + 3 = 987
     1234 × 8 + 4 = 9876
    12345 × 8 + 5 = 98765
   123456 × 8 + 6 = 987654
  1234567 × 8 + 7 = 9876543
 12345678 × 8 + 8 = 98765432
123456789 × 8 + 9 = 987654321

```
* Output in your chosen language in the fewest bytes possible.
* Note the number of spaces at the start of each line to maintain the trapezium shape.
* Trailing spaces are allowed.
* You can use `×` or the letter x - whichever you prefer.

# Answer
> 15 votes
## Python 2, 59 bytes

```
a=i=1
exec"print'%9d x 8 +'%a,i,'=',a*8+i;i+=1;a=a*10+i;"*9

```

The numbers `a` and `i` the equation `a * 8 + i` are generated arithmetically. Each line, `i` is incremented, and `a` has the next digit appended via `a=a*10+i`. For example, if `a=12345, i=5`, then `i` becomes `6`, so the new `a` is `12345*10 + 6` which is `123456`.

Storing these as numbers rather than strings lets us compute the RHS as given by the equation `a*8+i`, which is shorter than string reversing.

# Answer
> 7 votes
# , 37 bytes

```
i¸ 1 X 8 + 1 = 98ñYp|Eylp^Xf+$ylp

```

Try it online!

This contains unprintable, so here is a hexdump:

```
00000000: 69c2 b820 3120 5820 3820 2b20 3120 3d20  i.. 1 X 8 + 1 =
00000010: 391b 38c3 b159 707c 4579 6c70 015e 5866  9.8..Yp|Eylp.^Xf
00000020: 2b01 2479 6c70 18                        +.$ylp.

```

# Answer
> 5 votes
# Pyth, 32 bytes

```
VS9ss[*dK-9NSN" x 8 + "N" = "r9K

```

Try it online!

```
VS9ss[*dK-9NSN" x 8 + "N" = "r9K
VS9                                  # For N in 1..9
   s                                 # Join without delimiter
    s[                               # Reduce the array on + (flattens)
      *dK-9N                         # - Space, repeated K=(9-N) times
            SN                       # - The string sequence 1..N
              " x 8 + "              # - This string literal
                       N             # - N itself
                        " = "        # - This string literal
                             r9K     # - The string sequence 9..K

```

---

Thanks to @FryAmTheEggman for saving 2 bytes. Thanks to @KennyLau for saving 3 bytes.

# Answer
> 5 votes
# 05AB1E, ~~32~~ ~~31~~ ~~30~~ 28 bytes

Code:

```
TG9N-ð×NLJðN"x8+ÿ="€ðJžmN£J,

```

Uses the **CP-1252** encoding. Try it online!.

# Answer
> 5 votes
## PHP, ~~105~~ ~~89~~ ~~60~~ 57 bytes

my first golf try here (thanks to manatwork & user55641)

```
for(;$i++<9;)printf("%9s x 8 + $i = %s
",$s.=$i,$s*8+$i);

```

### 59

```
for(;$i++<9;)printf("%9s x 8 + $i = %s
",$s.=$i,$t.=10-$i);

```

### 89 (my own try)

```
for(;@++$i<=9;){printf("%9s x 8 + %s = %s\n",join(range(1,$i)),$i,join(range(9,10-$i)));}

```

### 105 (first)

```
for($j='123456789';@$j[$i++];){printf("%9s x 8 + %s = %s\n",substr($j,0,$i),$i,strrev(substr($j,-$i)));}

```

# Answer
> 4 votes
## CJam, ~~39~~ ~~38~~ 36 bytes

*Thanks to Optimizer for saving 2 bytes.*

```
9{)_,:)9Se[" x 8 + "@S'=S9_,fm4$<N}/

```

Test it here.

Same byte count:

```
9{)_,:)9Se[]"x8+"+:\'=9_,f-Y$<]S*n}/

```

This requires the latest version, available on Try it online!

# Answer
> 4 votes
# Python 2, ~~87~~ ~~84~~ ~~78~~ 75 bytes

```
s="123456789"
n=1
exec'print"%9s"%s[:n],"x 8 + %s ="%n,s[::-1][:n];n+=1;'*9

```

**Try it online**

A previous version uses some string magic.

```
R=range(1,10)
for n in R:print" "*(9-n)+`R`[1:n*3:3]+" x 8 + %d = "%n+`R`[-2:27-3*n:-3]

```

Casting `range(1,10)` to a string gives `[1, 2, 3, 4, 5, 6, 7, 8, 9]`, and this is nice since every number is only a single digit. So getting the string `123456789` from this is simple with ``range(1,10)`[1::3]`. The reversed range is  ``range(1,10)`[-2::-3]`. Then, to get only as far as I want each iteration, I slice it off at either `3*n`, or at `3*(9-n)` (`27-3*n`) for the reversed digits.

# Answer
> 4 votes
# Ruby, ~~77~~ ~~73~~ ~~65~~ 60 bytes

Try it online~

Major revamps from @manatwork

Another overhaul from @xsot

```
a=i=0;9.times{puts"%9d x 8 + %d = %d"%[a=a*10+i+=1,i,a*8+i]}

```

# Answer
> 4 votes
# Java 10, ~~151~~ ~~133~~ ~~130~~ ~~129~~ ~~126~~ 110 bytes

```
v->{String p="\n",r="";for(int n=123456789,i=9;i>0;n/=10,p+=" ")r=p+n+" x 8 + "+i+" = "+(n*8+i--)+r;return r;}

```

Try it online.

**Explanation:**

```
v->{                   // Method with empty unused parameter and String return-type
  String p="\n",       //  Prefix-String, starting at a newline
         r="";         //  Result-String, starting empty
  for(int n=123456789, //  Multiply-number, starting at 123456789
      i=9;i>0          //  Loop `i` in the range [9, 0):
      ;                //    After every iteration:
       n/=10,          //     Remove the last digit from the integer
       p+=" ")         //     Append a space after the prefix
    r=...+r;           //   Prepend the following to the result-String:
      p                //    The prefix-String
      +n               //    Followed by the integer
      +" x 8 + "       //    Followed by the literal String " x 8 + "
      +i               //    Followed by the loop-index `i`
      +" = "           //    Followed by the literal String " = "
      +(n*8+i--)       //    Followed by the result of that equation
  return r;}           //  Return the result-String

```

# Answer
> 4 votes
## Perl, 49 bytes

```
printf"%9s x 8 + $_ = %s
",$@.=$_,$_+8*$@for 1..9

```

### Usage

```
perl -e 'printf"%9s x 8 + $_ = %s
",$@.=$_,$_+8*$@for 1..9'

```

# Answer
> 3 votes
## Batch, 117 bytes

```
@echo off
set a=         12345678987654321
for /l %%i in (1,1,9)do call echo %%a:~%%i,9%% x 8 + %%i = %%a:~17,%%i%%

```

Yes, that is 16 % signs on one line; that's Batch for you!

# Answer
> 3 votes
## C#, 113 bytes

```
void f(){for(int n=1,i=1;i<10;n=10*n+ ++i)Console.WriteLine(new string(' ',9-i)+n+" x "+"8 + "+i+" = "+(n*8+i));}

```

if you have anyway to improve this solution feel free to share.

# Answer
> 2 votes
## PowerShell v2+, ~~85~~ ~~64~~ ~~58~~ ~~57~~ 52 bytes

```
8..0|%{" "*$_+-join(1..++$i+" x 8 + $i = "+9..++$_)}

```

Loops from 8 to 0 `8..0|%{...}` via the range operator. Each iteration, we output a string concatenation consisting of (the appropriate number of spaces `" "*$_`), plus a `-join`ed string of (a range from `1` to a pre-incremented helper number `++$i`, plus the middle bit `" x 8 + $i = "`, plus the final range from `9` to the current number `$_` pre-incremented).

One big trick here is we leverage the "left-preference" for typecasting, which allows us to "add" arrays together inside the `-join` parens, meaning we use only one `-join` operator.

### Example

```
PS C:\Tools\Scripts\golfing> .\magical-8-trapezium.ps1
        1 x 8 + 1 = 9
       12 x 8 + 2 = 98
      123 x 8 + 3 = 987
     1234 x 8 + 4 = 9876
    12345 x 8 + 5 = 98765
   123456 x 8 + 6 = 987654
  1234567 x 8 + 7 = 9876543
 12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

```

# Answer
> 2 votes
## Haskell, 92 bytes

```
s=(show=<<)
[1..9]>>= \x->([x..8]>>" ")++s[1..x]++" x 8 + "++s[x]++" = "++s[9,8..10-x]++"\n"

```

How it works:

```
s=(show=<<)                   -- helper function that turns a list of numbers into
                              -- a string without delimiters, e.g. [1,2] -> "12"

[1..9]>>=                     -- for each number 1 to 9
     ([x..8]>>" ")            -- take length of [x..8] copies of a space
     s[1..x]                  -- the digits from 1 to x
     " x 8 + "                -- a string literal
     s[x]                     -- the digit of x
     " = "                    -- another string literal
     s[9,8..10-x]             -- the digits from 9 down to 10-x
     "\n"                     -- an a newline

```

# Answer
> 2 votes
## Pyke, ~~30~~ 29 bytes

```
9Fd*~utj+9<\x8\+9i-\=ji>_dJ)X

```

Try it here!

```
9F                         )  -  for i in range(9):
  d*                          -       " " * i
        +                     -      ^ + V
       j                      -       j = V
    ~ut                       -        "123456789"
         9<                   -     ^[:9]
           \x8\+9i-\=         -    [^, "x", 8, "+", (9-i), "=", V]
                        _     -     reversed(V)
                     ji>      -      j[i:]
                         dJ   -   " ".join(^)
                            X - print(reversed(^))

```

# Answer
> 2 votes
## Retina, 66 bytes

Byte count assumes ISO 8859-1 encoding. The leading linefeed is significant.

```

123456789!9 = 987654321
+`^((.)+)\B.!.(.+).
 $1!$2$3¶$&
!
 x 8 +

```

Try it online!

# Answer
> 2 votes
# MATL, ~~38~~ ~~36~~ 35 bytes

```
9:"9@-Z"@:!V' x 8 + '@VO61O58@:-v!D

```

**Try it online!**

# Answer
> 2 votes
# C, 74 bytes

```
d(i,n){for(i=n=1;i<10;n=++i+n*10)printf("%9d x 8 + %d = %d\n",n,i,n*8+i);}

```

# Answer
> 2 votes
# J, 51 bytes

```
(|."1|.\p),.' x 8 + ',"1]p,.' = ',"1]\|.p=:u:49+i.9

```

Creates the string `123456789` and then operates on prefixes and suffixes of it to create the output.

### Usage

```
   (|."1|.\p),.' x 8 + ',"1]p,.' = ',"1]\|.p=:u:49+i.9
        1 x 8 + 1 = 9
       12 x 8 + 2 = 98
      123 x 8 + 3 = 987
     1234 x 8 + 4 = 9876
    12345 x 8 + 5 = 98765
   123456 x 8 + 6 = 987654
  1234567 x 8 + 7 = 9876543
 12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

```

# Answer
> 2 votes
# JavaScript ES6 (88)

Taking advantage of the new `repeat` method, backticks and templating...

```
i=10;for(y="";--i;)console.log(`${" ".repeat(i)+(y+=(x=10-i))} x 8 + ${x} = ${y*8+x}\n`)

```

# Answer
> 2 votes
# R, ~~107~~ 103 bytes

```
a=1;for(i in 2:10){cat(rep("",11-i),paste(a,"x",8,"+",(i-1),"=",strtoi(a)*8+(i-1)),"\n");a=paste0(a,i)}

```

**Ungolfed :**

```
a=1

for(i in 2:10)
    cat(rep("",11-i),paste(a,"x",8,"+",(i-1),"=",strtoi(a)*8+(i-1)),"\n")
    a=paste0(a,i)

```

**Result :**

```
        1 x 8 + 1 = 9
       12 x 8 + 2 = 98
      123 x 8 + 3 = 987
     1234 x 8 + 4 = 9876
    12345 x 8 + 5 = 98765
   123456 x 8 + 6 = 987654
  1234567 x 8 + 7 = 9876543
 12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

```

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~61~~ ~~52~~ 39 bytesSBCS

```
↑(⍳9)((¯9↑↑),' x 8 +',⊣,'= ',↑∘⌽)¨⊂1↓⎕D

```

Try it online!

-9 bytes by using the `10⊥` trick to parse the number, instead of a reduction. Thanks to @Adám for -13!

Explanation:

```
↑    ((¯9↑↑),' x 8 +',⊣,'= ',↑∘⌽)¨⊂1↓⎕D
                                     ⎕D  ⍝ Numbers from 0 to 9
                                   1↓    ⍝ Drop the 0
 (⍳9)(                          )¨⊂      ⍝ Do 9 times, N=current
                             ↑∘⌽         ⍝ Reverse the string (9..1) and cut off N elements
                      ⊣                  ⍝ N itself
      (   ↑)                             ⍝ Drop N elements off the 1..9 string...
      (¯9↑ )                             ⍝ ...then pad it back with spaces
            ,' x 8 +', ,'= ',            ⍝ Join with a few constant strings
↑                                        ⍝ Format

```

# Answer
> 1 votes
## JavaScript (ES6), 99 bytes

```
_=>[...Array(9)].map((n,i)=>`${n="        123456789".substr(i,9)} x 8 + ${++i} = ${n*8+i}`).join`\n`
_=>".........".replace(/./g,(n,i)=>`${n="        123456789".substr(i,9)} x 8 + ${++i) = ${n*8+i}\n`)

```

Where `\n` represents a literal newline character. The second version outputs a trailing newline. I came up with a formula for the numbers `('1'.repeat(9-i)+0+i)/9` but the padding was easier to do this way.

# Answer
> 1 votes
# Brainfuck, 232 bytes

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

```

Try it online!

Can be golfed much further...

# Answer
> 1 votes
## Javascript (using external library) (143 bytes)

```
n=>_.Range(1,9).WriteLine(v=>_.Range(0,10-v).Write("",x=>" ")+_.Range(1,v).Write("")+" x 8 + " + v + " = "+_.Range(10-v,v).Reverse().Write(""))

```

Link to lib: https://github.com/mvegh1/Enumerable/

Explanation of code: Create range 1 to 9, and for each value, write a line corresponding to the complex predicate. The predicate is passed the current integer value, and creates a range spanning 10-currentValue elements, in order to create that many spaces. Those spaces are concatenated with the formula part of the line, and then that is concatenated with the tailend of the range matching the number of elements as the frontend, in reverse order.

Note: In the image, the first line is off by one space because the console added a quotation mark since the return value is a string. The actual value is formatted correctly

# Answer
> 1 votes
# 05AB1E, 24 bytes

```
9Lε©LJ'x8'+®'=T®L-Jðý}.c

```

Try it online!

Uses a newer version than the challenge, which is now allowed.

# Answer
> 1 votes
# Canvas, 20 bytes

```
９｛Ｒ⤢x∙8∙+¹=¹◂±ｍ） ＊］ｒ

```

Try it here!

# Answer
> 1 votes
# VBA (Excel), 51 bytes

Using Immediate Window

```
For z=1To 9:a=a &z:?Spc(9-z)a" x 8 +"z"="a*8+z:Next

```

# Answer
> 0 votes
# k (77 bytes)

Could probably be shortened a bit more

```
-1@'((|t)#\:" "),'(t#\:n),'" x 8 + ",/:n,'" = ",/:(t:"I"$'n)#\:|n:"123456789";

```

Example:

```
k)-1@'((|t)#\:" "),'(t#\:n),'" x 8 + ",/:n,'" = ",/:(t:"I"$'n)#\:|n:"123456789";
         1 x 8 + 1 = 9
        12 x 8 + 2 = 98
       123 x 8 + 3 = 987
      1234 x 8 + 4 = 9876
     12345 x 8 + 5 = 98765
    123456 x 8 + 6 = 987654
   1234567 x 8 + 7 = 9876543
  12345678 x 8 + 8 = 98765432
 123456789 x 8 + 9 = 987654321

```

# Answer
> 0 votes
# golflua, 56 characters

```
p=""~@i=1,9p=p..i; w(S.q("%9s x 8 + %d = "..p*8+i,p,i))$

```

Sample run:

```
bash-4.3$ golflua -e 'p=""~@i=1,9p=p..i; w(S.q("%9s x 8 + %d = "..p*8+i,p,i))$'
        1 x 8 + 1 = 9
       12 x 8 + 2 = 98
      123 x 8 + 3 = 987
     1234 x 8 + 4 = 9876
    12345 x 8 + 5 = 98765
   123456 x 8 + 6 = 987654
  1234567 x 8 + 7 = 9876543
 12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321

```

# Answer
> 0 votes
# Object Pascal (FPC), ~~156~~ ~~127~~ 103 bytes

Trivial solution, ~~using the Format library func~~. Shaved some more bytes by using only integers and no strings. Reduced in size thanks to @manatwork (for teaching me some basic stuff about writeln).

```
var i,c:int64;begin i:=0;for c in[1..9]do begin i:=i*10+c;WriteLn(i:9,' x 8 + ',c,' = ',i*8+c);end;end.

```

Try it online!

Ungolfed:

```
var
  i, c: int64;
begin
  i := 0;
  for c in [1..9] do
  begin
    i := i*10+c;
    WriteLn(i:9, ' x 8 + ', c, ' = ', i*8+c);
  end;
end.

```

# Answer
> 0 votes
# ///, 149 bytes

```
/:/ x 8 + //-/ = //0/1234//_/9876//|/  /||||1:1-9
||| 12:2-98
|||123:3-987
|| 0:4-_
||05:5-_5
| 056:6-_54
|0567:7-_543
 05678:8-_5432
056789:9-_54321

```

Try it online!

# Answer
> 0 votes
# dc, 79 bytes

```
1[32P]sS[d0<S1-d0<R]sR[dZ9r-lRxrdn[ x 8 + ]PdZn[ = ]Pdd8*rZ+prd10*dZ+dZA>M]dsMx

```

Try it online!

Somewhat better than I expected. Started with a solution that juggled stack and an incremental register before realizing I only need to keep the left-most number around - since the value to be added is the number of digits the left-most number has, this can be determined via `Z` and the result can just be calculated according to the formula.

`[32P]sS[d0<S1-d0<R]sR` feels wasteful, but I couldn't come up with a much better way to handle the indentation. The main macro, `[dZ9r-lRxrdn[ x 8 + ]PdZn[ = ]Pdd8*rZ+prd10*dZ+dZA>M]dsMx` should be fairly self-explanatory based on my above description. The initial `1` just seeds the whole thing.

# Answer
> 0 votes
# Pyth - 30 bytes

First attempt, working on optimization.

```
VS9+*dK-9Njd[jkSN\×8\+N\=jkr9K

```

Try it online.

# Answer
> 0 votes
# Forth (gforth), 76 bytes

```
: f 0 10 1 do cr 10 * i + dup 9 .r ."  x 8 + "i . ." = "dup 8 * i + . loop ;

```

Try it online!

### Explanation

Start a value at 0. Starts a loop from 1 to 9. Each iteration:

* Multiply value by 10 and add the loop index
* output this value right-aligned
* output " x 8 + "
* output the loop index
* output " = "
* calculate results and output

### Code Explanation

```
: f                  \ start word definition
  0                  \ set up counter/value
  10 1 do            \ start a counted loop from 1 to 9
    cr               \ output a newline
    10 * i +         \ calculate the next value for the first term
    dup 9 .r         \ make a copy and then output in a right-aligned space of 9 characters
    ."  x 8 + "      \ output " x 8 +"
    i .              \ output the loop index
    ." = "           \ output " ="
    dup 8 * i +      \ perform the actual calculation
    .                \ output result
  loop               \ end the counted loop
;                    \ end the word definition

```

# Answer
> 0 votes
# Perl 6, 58 bytes

```
my $a;printf "%9s x 8 + $_ = %s\n",$a~=$_,$a.flip for 1..9

```

Try it online!

# Answer
> 0 votes
# Vyxal `C`, 24 bytes

```
`%x8+%=%`Ṅ9ɾ:ṅḂ"v¦$wY∩v%

```

Try it Online!

```
`%x8+%=%`                 # Take the string "%x8+%=%"
         Ṅ                # Join by spaces
                       v% # Replace %s in this with each of...
                      ∩   # Transposed..
                     Y    # Interleave...
           9ɾ:     $w     # 1...9 and...
           9ɾ ṅ           # "123456789"
               Ḃ"v¦       # Prefixes and reversed suffixes

```

# Answer
> 0 votes
# JavaScript, 70 bytes

```
alert = console.log; // for less frustration

for(n='1';m=n%10;n+=++m)alert(n.padStart(9)+` x 8 + ${m} = `+(n*8+m));
```

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


title: Find the walls!

text:
# Question
Title: Find the walls!
*This is a simpler variant of my previous challenge Don't touch the walls!, as suggested by Jonah.*

Given a multi-dimensional rectangular array of integers between 0 and 9, output all the elements which are "touching the edges".

Output is very flexible: it can be in any order, and may be flattened or partially nested, but must contain every edge element the correct number of times, and may not contain any others.

## Specification

"Touching the edges" is a hopefully fairly intuitive concept, but here is a specification:

Let's use this array, with shape `4, 3`.

```
[[1, 3, 0],
 [2, 6, 7],
 [4, 0, 2],
 [0, 0, 0]]

```

Using *one-based indexing*, we can index any element of the array using two integers in the ranges \\$ \[1, 4\] \\$ and \\$ \[1, 3\] \\$.

The elements which are touching the edge are those with coordinates of the form `1, y`, `4, y`, `x, 1`, or `x, 3`.

So, formally, we can say, for an element to be "touching the edge", at least one part of its multidimensional indices is either 1 (the minimum possible coordinate), or the maximum possible coordinate (which is the size of the array in the respective dimension).

Here is the same array with the elements which are "touching the edge" ***highlighted***:

```
[[***1***, ***3***, ***0***],
 [***2***, 6, ***7***],
 [***4***, 0, ***2***],
 [***0***, ***0***, ***0***]]

```

The output could be anything like:

```
1 3 0 2 7 4 2 0 0 0

```

```
[1, 2, 4, 0, [0, 0, [2, 7, 0], [3]]]

```

```
[[[[[[4]]]]], [[[0, 0, 0, 0]]], [[2, 2]], [1, 7, 3]]

```

---

For the 1-dimensional array `[3, 4, 9, 0, 0]`, the edges are `[***3***, 4, 9, 0, ***0***]`, so the output is `[3, 0]`.

---

For this 3-dimensional array:

```
[[[4, 0, 4, 1],
  [0, 0, 5, 8],
  [6, 0, 0, 0],
  [0, 3, 7, 0]],

 [[4, 9, 8, 5],
  [0, 6, 4, 0],
  [0, 0, 0, 3],
  [0, 9, 6, 1]],

 [[0, 4, 7, 9],
  [0, 2, 0, 6],
  [0, 0, 0, 0],
  [7, 0, 3, 0]],

 [[0, 5, 3, 5],
  [0, 0, 0, 0],
  [6, 5, 3, 0],
  [4, 6, 0, 8]]]

```

the edges are:

```
[[[***4***, ***0***, ***4***, ***1***],
  [***0***, ***0***, ***5***, ***8***],
  [***6***, ***0***, ***0***, ***0***],
  [***0***, ***3***, ***7***, ***0***]],

 [[***4***, ***9***, ***8***, ***5***],
  [***0***, 6, 4, ***0***],
  [***0***, 0, 0, ***3***],
  [***0***, ***9***, ***6***, ***1***]],

 [[***0***, ***4***, ***7***, ***9***],
  [***0***, 2, 0, ***6***],
  [***0***, 0, 0, ***0***],
  [***7***, ***0***, ***3***, ***0***]],

 [[***0***, ***5***, ***3***, ***5***],
  [***0***, ***0***, ***0***, ***0***],
  [***6***, ***5***, ***3***, ***0***],
  [***4***, ***6***, ***0***, ***8***]]]

```

The output is something like:

```
[4, 0, 4, 1, 0, 0, 5, 8, 6, 0, 0, 0, 0, 3, 7, 0, 4, 9, 8, 5, 0, 0, 0, 3, 0, 9, 6, 1, 0, 4, 7, 9, 0, 6, 0, 0, 7, 0, 3, 0, 0, 5, 3, 5, 0, 0, 0, 0, 6, 5, 3, 0, 4, 6, 0, 8]

```

Imagine each inner 2-dimensional array as a cross-section of a 3-dimensional box. The only elements which are not *touching the edges* are the ones on the *inside* of the box.

Note that arrays which have one of their dimensions as only 1, such as `[4]` or `[[3, 6, 5]]`, may need to be treated with care. Their respective outputs should be `[4]` and `[3, 6, 5]`.

## Rules

# Answer
> 7 votes
# Python 2, 38 bytes

```
def f(a):a[1:-1]*=a>[f];map(f,a[1:-1])

```

Try it online!

Expects a nested list and removes all non surface elements inplace.

#### How?

`a>[f]` uses that in Python 2 every list is greater than every function is greater than every number to check whether `a` is a nested or flat list.

If nested the middle of `a` is multiplied by one, in other words, nothing changes. The recursion will then descend one level.

If flat the middle of `a` is multiplied by zero, in other words, excised. This will stop the recursion because `map` will run over an empty list.

# Answer
> 5 votes
# , 25 24 bytes

```
#~&,(<:0&e.@:|"1]#:i.)@$

```

Try it online!

* Create multidimensional indices for each element using mixed base binary
* Mod each of those by the (input dimensions- 1)
* Check if the multidimensional index has a 0. If so, keep that element. Otherwise, remove it.

# Answer
> 4 votes
# Wolfram Language (Mathematica), 38 bytes

```
MapAt[#0,#,2;;-2]~Check~#/._MapAt->{}&

```

Try it online!

Replaces non-edge elements with `{}`.

# Answer
> 4 votes
# JavaScript, 44 bytes

```
f=a=>a.at?[a.shift(),a.pop()??a,a.map(f)]:[]

```

```
f=a=>a.at?[a.shift(),a.pop()??a,a.map(f)]:[]

test = a => console.log(JSON.stringify(f(a)))
test([[[4, 0, 4, 1],
  [0, 0, 5, 8],
  [6, 0, 0, 0],
  [0, 3, 7, 0]],

 [[4, 9, 8, 5],
  [0, 6, 4, 0],
  [0, 0, 0, 3],
  [0, 9, 6, 1]],

 [[0, 4, 7, 9],
  [0, 2, 0, 6],
  [0, 0, 0, 0],
  [7, 0, 3, 0]],

 [[0, 5, 3, 5],
  [0, 0, 0, 0],
  [6, 5, 3, 0],
  [4, 6, 0, 8]]])
test([[1, 3, 0],
 [2, 6, 7],
 [4, 0, 2],
 [0, 0, 0]])
test([4])
test([[3, 6, 5]])
```

# Answer
> 3 votes
# , ~~60~~ 59 bytes

*Edit: -1 byte thanks to @Giuseppe.*

```
\(a,i=which(a|1,T))a[i[apply(i,1,\(x)!all(x-1&x-dim(a))),]]
```

Attempt This Online!

# Answer
> 2 votes
# APL (dzaima/APL), 20 bytes

```
⊢⌿⍥,⍨1∊¨⍳∘⍴∊¨¨∘⊂1,¨⍴

```

Try it online!

shape (length along each dimension) of the array

`1,¨` prepend 1 to each

`∊¨¨∘⊂` for each of each of the following, is it a member of the corresponding element of that?

`⍳∘⍴` the indices of an array of the shape of the argument

`1∊¨` for each of those, is 1 a member?

`⌿⍥,⍨` use that flattened, to filter the flattened…

argument

# Answer
> 2 votes
# Factor, ~~73~~ ~~72~~ 83 bytes

```
: f ( x -- ) dup real? [ drop ] [ 1 cut 1 short cut* rot append . [ f ] each ] if ;

```

Try it online!

Recursive function that (maybe) slices both ends off the input, prints them, then calls itself on all the remaining elements until an atom (real number) is reached. ((Now handles arrays with a single element properly at the cost of 11 bytes...))

# Answer
> 2 votes
# BQN, 19 bytesSBCS

```
1¨⌾⊏⟜⍉⟜⌽⍟=⍟2∘≠˜⥊⊸/⥊

```

one for each

`⌾⊏` of the elements of the first major cells (n−1 dimensional sub-array)

`⟜⍉` of the single-step-rotated-axes version

`⟜⌽` of the reverse

`⍟=` done as many times as there are dimensions

`⍟2` done twice

`∘≠˜` of the self-inequality (an all-zero array of same shape)

`⥊⊸/` when flattened, filters

the flattened argument

Run online!

# Answer
> 2 votes
# Retina, 84 bytes

```
L`(?<=\[(\[(?(3)$)((])|(?<-3>\[)|\d|,)+)*)\d|\d(?=(((\[)|(?<-6>])|\d|,)+(?(6)^)])*])

```

Try it online! Outputs each edge element on its own line but link is to test suite that joins on commas for convenience. Explanation:

```
L`

```

List matches.

```
(?<=\[(\[(?(3)$)((])|(?<-3>\[)|\d|,)+)*)\d|

```

Similar to the following, but using a lookbehind to find whether the element is the first in any of its dimensions. Due to the way lookbehinds are evaluated, this version is harder to explain, so you'll just have to take my word for it that it's the mirror image of the following test.

```
\d(?=

```

Match a digit. In Retina 1 it's possible to use overlapping matches and captures to avoid using a lookahead but it costs 7 bytes to do that and you only save 4 so it's not worth it.

```
(((\[)|(?<-6>])|\d|,)+(?(6)^)

```

Match any number of brackets, digits, or commas, but there must be the same number of opening and closing brackets.

```
])*

```

Match the close bracket at the end of this subarray, thus considering the parent subarray. Go out as many dimensions as necessary.

```
])

```

Match an extra close bracket, showing that this element or one of its container subarrays was the last in its parent.

Replacing the `L` with `!` results in a version that works in Retina 0.8.2 but in this case it's no longer possible to use the same test suite.

# Answer
> 1 votes
# Python3, 95 bytes:

```
f=lambda x,t=0:[x]*t if x*0==0 else f(x[0],1)+[j for k in x[1:-1]if(j:=f(k,t or 0))]+f(x[-1],1)

```

Try it online!

# Answer
> 1 votes
# Jelly,  ~~12~~  11 bytes

```
ŒJ%þ`ṪỊ§TịF

```

A monadic Link that accepts a rectangular multi-dimensional list and yields the elements that are on its "surface".

**Try it online!**

### How?

```
ŒJ%þ`ṪỊ§TịF - Link: rectangular multi-dimensional list, M
ŒJ          - multi-dimensional indices of M -> [[1,1,1,...],...,[height,width,depth,...]]
    `       - use as both arguments of:
   þ        -   make a table of:
  %         -     modulo (vectorises)
     Ṫ      - tail -> [...[x%height,y%width,z%depth,...]...]
      Ị     - abs(x)<=1? (vectorises)
       §    - sums (of those)
        T   - truthy indices (of that)
          F - flatten (M) (N.B. same order as the indices produced by ŒJ)
         ị  - index-into

```

# Answer
> 1 votes
# 05AB1E, 26 bytes

```
˜s"DdiëdƶZ%2‹εZ≠i®.V"©.V˜Ï

```

05AB1E is very verbose with recursive approaches, and it's also not too good in most matrix-based challenges, so the combination ends up as this horrendously long program (although can probably still be golfed a bit).

Try it online or verify all test cases.

**Explanation:**

```
˜            # Flatten the (implicit) multi-dimensional input-list
 s           # Swap to get the actual input again
  "..."      # Push the recursive string explained below
       ©     # Store it in variable `®` (without popping)
        .V   # Evaluate and execute it as 05AB1E code,
             # using the multi-dimensional list as argument
          ˜  # Flatten the result as well
           Ï # Keep all values of the flattened input at the truthy (==1) indices
             # (after which the result is output implicitly)

D            # Copy the current list or integer
 dië         # If it's a list:
  i          #  If
 d           #  the current value is truthy after a >=0 check:
             #  (only a non-negative integer would be truthy, and lists falsey)
             #   Do nothing
   ë         #  Else (it's a list):
    d        #   Transform each integer to a 1 with a >=0 check
     ƶ       #   Multiply each 1 by its 1-based index
      Z      #   Push the flattened maximum integer (without popping)
       %     #   Modulo
        2‹   #   Check which are smaller than 2 (first row=1s; last row=0s)
             #   (all first and last items are now 1s)
    ε        #   Then map over each inner list:
     Z       #    Push the flattened maximum (without popping)
      ≠i     #    If this maximum is NOT 1:
        ®.V  #     Do a recursive call with the current inner list

```

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


# Question
Title: Smallest number such that concatenation is a square
# Challenge

Write a program or function that takes a number \\$n\\$ and returns the smallest \\$k\\$ such that concatenation \\$n'k\\$ is a square. This sequence is described by A071176 on the OEIS.

# I/O Examples

```
input --> output

1   -->    6 (4^2)
10  -->    0 (10^2)
35  -->  344 (188^2)
164 -->  836 (406^2)
284 --> 2596 (1686^2)

```

# Rules

# Answer
> 7 votes
# 05AB1E, 7 bytes

```
∞<.Δ«Å²

```

Try it online or verify all test cases.

# 05AB1E (legacy), 8 bytes

```
[N«Å²#}N

```

Try it online or verify all test cases.

Alternative 8-byter which works in both 05AB1E versions (credit to *@Grimmy*):

```
[N«Å²iNq

```

Try it online (no test suite due to the program terminate `q`).

**Explanation:**

```
∞         # Push an infinite list in the range [1, ...]
 <        # Decrease each by 1 to make the range [0, ...]
  .Δ      # Find the first value which is truthy for:
    «     #  Concat the value to the (implicit) input-integer
     Å²   #  And check whether it is a square number
          # (after which this found first value is output implicitly as result)

[         # Start an infinite loop:
 N«       #  Concat the 0-based loop index to the (implicit) input-integer
   Å²     #  If it's a square number:
     #    #   Stop the infinite loop
}N        # After the infinite loop has stopped: push the last index
          # (after which this found index is output implicitly as result)

[         # Start an infinite loop:
 N«       #  Concat the 0-based loop index to the (implicit) input-integer
   Å²i    #  If it's a square number:
      N   #   Push the index again
       q  #   And terminate the program
          #   (after which this index is output implicitly as result)

```

The legacy version didn't had the  builtin, and in the new version it isn't possible to push the last index `N` after a loop is terminated, which is why I decided to post both solutions.

# Answer
> 5 votes
# , ~~27~~ 21 bytes

```
(]+0<1|2%:,&.":)^:_&0

```

Try it online!

*-6 bytes thanks to FrownyFrog*

* `( )^:_` invoke the verb in parens continuously until it's output stops changing
* `&0` set the right argument -- the one that will change each iteration -- to 0 (the left argument, the input, will remain fixed)

Now let's break down what's in the parens

* `]+` the right arg plus...
* `0<` 0 or 1, depending on if 0 is less than...
* `1|` the reminder when 1 divides...
* `2%:` the square root of...
* `,&.":` the left arg (original input) catted with `,` the right arg "under" `&.` stringification `":`: ie, turn them both into strings, cat them, then convert back to an int

# Answer
> 5 votes
# Perl 6, 23 bytes

```
{(0...($_~*)**.5%%1)-1}

```

Try it online!

### Explanation

```
{                     }  # Anonymous codeblock
 (0...             )-1   # Find the first number
      ($_~*)             # That when appended to the input
            **.5         # Has a sqrt
                %%1      # That is whole

```

# Answer
> 4 votes
# JavaScript (ES7), 33 bytes

Takes input as a string.

```
f=(n,k=0)=>(n+k)**.5%1?f(n,k+1):k

```

Try it online!

# Answer
> 4 votes
# , 45 bytes

```
n=scan();while((paste0(n,+F):1)^.5%%1)F=F+1;F

```

Try it online!

Throws a warning for each iteration noting that it only uses the first element of the vector as a loop condition. This will run out of space for large inputs since it constructs a vector of length \\$n'k\\$ at each iteration; this version will work for larger inputs and should be a bit faster, at a cost of 4 bytes.

# Answer
> 4 votes
# Perl 5 `-pal`, 30 bytes

```
$_=0;$_++while"@F$_"**.5=~/\./

```

Try it online!

# Answer
> 4 votes
## C, ~~123~~ 115 bytes (thanks, Jo King!)

```
n,k,m=10,x,p;main(){scanf("%d",&n);for(;k<m||(m*=10);++k)for(p=0;x=n*m+k,p<=x;++p)if(p*p==x)return printf("%d",k);}

```

I noticed this version can fail on not-very-large inputs due to integer overflow. So I, did a separate version, with less overflow.

## C, less overflow. 117 bytes

```
n,k,m=10,x,p;main(){scanf("%d",&n);for(;k<m||(m*=10);++k)for(p=0;x=n*m+k,p*p<=x;++p)if(p*p==x)return printf("%d",k);}

```

## Pretty Printed:

```
n, k, m = 10, x, p;
main() {
    scanf("%d", &n);
    for (; k < m || (m *= 10); ++k)
        for (p = 0; x = n * m + k, p * p <= x; ++p)
            if (p * p == x)
                return printf("%d", k);
}

```

# Answer
> 4 votes
# C++ (clang), ~~194~~ \\$\cdots\\$ ~~128~~ 129 bytes

```
#import<string>
#define z std::to_string
int f(int n){for(int j=-1;;)for(long i=0,m=stol(z(n)+z(++j));i++<m;)if(i*i==m)return j;}

```

Try it online!

Added a byte to fix overflow error kindly pointed out by Deadcode.

# Answer
> 4 votes
# Python 2, ~~47~~ 49 bytes

```
f=lambda p,i=0:int(`p`+`i`)**.5%1and f(p,i+1)or i

```

Try it online!

# Answer
> 4 votes
# Brachylog, 8 bytes

```
;.c~^₂∧ℕ

```

Sadly enough it takes 3 bytes to check if a number is square and an extra  is needed if the input is a square itself.

## Explanation

```
;.c~^₂∧ℕ     # Find a value
;.c          #   that concatenate to the input
   ~^₂       #     gives a square number
      ∧ℕ     # and make sure that value is a number
             #   (otherwise we get the empty list for inputs that are square)

```

Try it online!

# Answer
> 3 votes
# Python 3, 51 bytes

```
f=lambda n,i=0:int(f'{n}{i}')**.5%1and f(n,i+1)or i

```

Try it online!

# Answer
> 3 votes
# Ruby -pl, 43 bytes

```
i=1;i+=1until"#{i*i}"[/^#$_(?!0.|$)/]
$_=$'

```

Try it online!

Tests each square until it finds one that starts with the input and is followed by a number with no leading zero. I thought going in this direction rather than the more natural one would be shorter, but now I'm doubting that it is.

# Answer
> 3 votes
# Pyth, ~~35~~ ~~33~~ ~~30~~ ~~23~~ 21 bytes

This is a program that uses only integer arithmetic. Since Python has arbitrary-precision integers, this is guaranteed to work for arbitrarily large numbers, whereas the square-root test used by most of the other answers fails with numbers greater than 252, having false positives with numbers very close to a perfect square.

Assumes that the input has no leading zeroes.

```
 f&J>K`*TTlzq+z`sJK)J

```

Try it online!

The leading space is needed to suppress printout of the value of `T` that resulted in loop termination, since `f` returns that value.

Ungolfed:

```
z = input()
for T in __import__('itertools').count(1):
    K = str(T*T);
    J = K[len(z):]
    if len(J)!=0 and z+str(int(J))==K:
        break
print(J)

```

# Packed Pyth, 19 bytes

Hex dump: `41 99 34 A7 D2 F0 2A A9 53 67 AE 2A FD 60 E7 2A 5A 99 40`

Try it online!

# Answer
> 3 votes
# Pyth, ~~18~~ ~~16~~ ~~15~~ ~~11~~ 10 bytes

Uses the floating point square root test, like most of the other answers. As such, the precision is eventually insufficient, and the smallest square it fails with is `4503599761588225` – with an input of `45035997`, it returns `61588224` instead of `61588225` as it should. The smallest input it fails with is `20256971`, returning `228498166` instead of `228498169` as it should. This is due to IEEE 754 floating point not being able to store precise integers greater than 252.

```
fsI@s+zT2Z

```

Try it online!

Ungolfed:

```
z = input()
Z = 0
for T in __import__('itertools').count(Z):
  tmp = int(z + str(T))**0.5
  if int(tmp) == tmp:
    print(T)
    break

```

Token by token explanation:

```
fsI@s+zT2Z
f            # (Implicitly print) First value of T for which the following is true:
         Z   # where T iterates over [Z, Z+1, Z+2, ...] with Z=0
     +zT     # the (string, since one of them is a string) concatenation of z and T
    s        # Converted from string to integer
   @    2    # To the 1/2 power
 sI          # is Invariant under floor conversion to integer

```

# Packed Pyth, 9 bytes

Hex dump: `CD CE 4C 0E 6A FD 54 65 68`

Try it online!

# Answer
> 2 votes
# Burlesque, 28 bytes

```
sajpsq~!_+2R@)S[jfeupjq[-jE!

```

Try it online!

Pretty sure this could be shorter, a lot of work is trying to drop N letters.

```
sa       #Find the length of the input to know how many characters to drop
j        #Put at bottom
ps       #Parse the string to {int}
q~!      #Boxed "starts with"
_+       #Concatenate to make {int !~} "starts with int"
2R@      # 2...inf
)S[      #Infinite list of squares
jfe      #Find an element that starts with int
up       #Turn int to string
jq[-jE!  #Drop (length of int) characters leaving the tail

```

# Answer
> 2 votes
# Japt, 10 bytes

```
@s+X ¬v1}a

```

Try it

# Answer
> 2 votes
# PHP, ~~53~~ ~~47~~ 44 bytes

```
for($k=-1;fmod(sqrt($argn.++$k),1););echo$k;

```

Try it online!

# Answer
> 2 votes
# Japt, 10 bytes

```
_siU ¬%1}f

```

Saved a byte thanks to @AZTECCO

Try it

# Answer
> 2 votes
# K (ngn/k), ~~21~~ 19 bytes

-2 bytes from @ovs's simplification

```
{(1!%.,/$x,)(1+)/0}

```

Try it online!

* `(cond)(code)/seed` set up a while-reduce, seeded with `0`, running the `(code)` clause until the `(cond)` clause returns a non-truthy value
    + `(1+)` code that increments its input
    + `(1!%.,/$x,)` the condition/check
        - `.,/$x,` append the current iteration value to the original input, convert each to a string, combine them, and eval the result (this converts the result to an integer)
        - `1!%` check if the remainder of the square root of the iteration value is non-zero

# Answer
> 1 votes
# JavaScript (Node.js), 38 Bytes

Try it Online!

```
f=(a,b=[0])=>(a+b)**.5%1?f(a,[++b]):+b

```

# Answer
> 1 votes
# Jelly, 8 bytes

```
0ṭVÆ²ɗ1#

```

Try it online!

A monadic link taking as its argument an integer and returning an integer.

## Explanation

```
0    ɗ1# | Starting with zero, find 1 integer where the following is true as a dyad, using the original argument as the right argument
 ṭ       | - Tag onto the end
  V      | - Evaluate after converting to string and concatenating
   Æ²    | - Check if perfect square

```

# Answer
> 1 votes
# Perl 5, ~~35~~ 40 bytes

```
$k=0;L:$_="$n$k"**.5;!/\./ or$k++,goto L

```

Try it online!

# Answer
> 1 votes
# cQuents, 13 bytes

```
#|1:#bA~N
?$$

```

Try it online!

## Explanation

```
#|1         output nth element in sequence (remove to output indefinitely)
   :        mode: sequence, output nth element in sequence
    #       conditional: count N up, when true, add to sequence
     b      call second line, passing
      A~N                             input concatenated to N

?$$         second line - sequence of squares - return true if a square and false if not

```

# Answer
> 1 votes
# Charcoal, 16 bytes

```
≔⁰ηＷ﹪₂Ｉ⁺θη¹≦⊕ηＩη

```

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

```
≔⁰η

```

Initialise the result to zero.

```
Ｗ﹪₂Ｉ⁺θη¹

```

Repeat until the concatenation is a square.

```
≦⊕η

```

Increment the result.

```
Ｉη

```

Output the result.

36 bytes for an efficient solution:

```
≔×χＮη

```

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

Multiply the input by 10.

```
≧⁺›₂η⌊₂ηη

```

Increment it unless it is already a square number.

```
Ｗ⌕ＩＸ⌈₂η²θ

```

Repeat until the square ceiling square root begins with the original input.

```
≧×χ

```

Multiply by 10.

```
η✂ＩＸ⌈₂η²Ｌθ

```

Output the suffix of the square ceiling square root.

# Answer
> 1 votes
# GolfScript, 24 bytes

I don't feel right to have a Burlesque answer without a GolfScript answer.(Please don't mind if this is a little bit slow, although they seem to produce the right result.)

```
-1{).2$\+~.),{.*}%?)!}do

```

Try it online!

## Explanation

-1                       # The counter for the current number (it is >= 0)
  {                      # Do at least 1 time until the number is a square number
   )                     #     Increment the counter

    .                    #     Copy the counter (to create an integer)
     2$                  #     Extract the 3rd-to-top to the top
       \                 #     Make sure that the casting to string works
        +                #     Join the numbers, as well as converting the
                         #     right operand to a string (input+count)
         ~               #     Evaluate the string to get a number

          .              #     Copy the number for the square number check
           ),            #     Generate range from 0 to the number
             {.*}%       #     Apply square for every number
                  ?      #     Find out where the number is inside the sequence
                         #     (yields -1 for nonexistent)

                   )     #     Increment, to make nonexistent false and others true
                    !    #     Negate, which means we shouldn't find the first non-square number.
                     }do # End do loop, use TOS as condition

                         # Output the counter at the end
```
</code></pre>

# Answer
> 1 votes
# AWK, 29 bytes

```
{while(($0x++)^.5%1);$0=x-1}1

```

Works with `mawk`, `gawk` and `nawk` on macOS and Ubuntu but not with TiO for some reason.

# Answer
> 1 votes
# RProgN 2, 13 bytes

```
x={x\.nš1%¬}é

```

# Explanation

```
x={x\.nš1%¬}é   #
x=              # Set 'x' to the input.
  {        }é   # Run the enclosed function with raising integers untill it returns truthy, and spit out that number
   x\.          # Place the input under the current number and concatenate them together
      nš        # Convert to a number and get the square root
        1%¬     # Is this a whole number?

```

Try it online!

# Answer
> 1 votes
# Java, ~~75~~ ~~63~~ 61 bytes

Two bytes less thanks to Kevin Cruijssen.

And another two less in the second version again thanks to Kevin Cruijssen!

```
n->{int j=0;for(;Math.sqrt(new Long(n+j))%1>0;j++);return j;}

```

Try it online!

I also have another version with my first (and very different) approach, which is ~~107~~ ~~92~~ ~~93~~ 91 bytes long:

```
n->{String a;for(long i=4;!(a=i*i+++"").matches(n+"([1-9].*|0)"););return a.split(n,2)[1];}

```

Try it online!

Both version have been tested against the first 10000 numbers.

# Answer
> 0 votes
# PHP, ~~83~~ 86 bytes

```
g:substr($k=$i*++$i,0,$l=strlen($n=$argn))==$n&&("$k")[$l]&&die(substr($k,$l));goto g;

```

Try it online!

-9 bytes thanks to @640KB and bugs fixed (+12). Only fails for case 10 currently.

## Ungolfed

```
<?php

$number=$argv[1];
$len = strlen($number);
$i=0;
do {
    $k = $i*$i;
    if (substr($k,0,$len)==$number && substr($k,$len,1)!='0') {
        die(substr($k,$len));
    }
    $i++;
} while (true);

?>

```

Try it online!

# Answer
> 0 votes
# Haskell, ~~93~~ 88 bytes

```
[j|i<-(show.(^2))<$>[0..],i/=n,n`isPrefixOf`i,j<-[drop(length n)i],j=="0"||j!!0/='0']!!0

```

Try it online!

# Answer
> 0 votes
# Lua, 96 bytes

```
n=io.read()i=0 while i do for j=0,n..i do if (n..i)+0==j*j then print(i)return end end i=i+1 end

```

Try it online!

# Answer
> 0 votes
# Vyxal, 6 bytes

```
≬?p∆²ṅ

```

Try it Online!

```
≬    ṅ # Find the first number where...
 ?p    # Prepending the input
   ∆²  # Produces a square?

```

Vyxal's square function uses `sympy.ntheory.primetest.is_square`, which works on arbitrary ints, so this won't fail on float precision.

# Answer
> 0 votes
## brev, 71 bytes

```
(define((s k)n)(if(integer?(sqrt((as-string conc)n k)))k((s(+ k 1))n)))

```

Test:

```
(map (s 0) '(1 10 35 164 284))
=> (6 0 344 836 2596)

```

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


# Question
Title: Can `a?b<c:b>c` be shortened in Javascript?
So I have the situation where I have one boolean value `a` and, if that one is `true` and `b<c` I want it to end up as `true`, if `a` is false and `b>c` I want it to resolve as `true` as well. If `b=c` I want it to be always false, no matter the value `b` and `c` are both numbers. My best approach so far is `a?b<c:b>c` or maybe `b^c^a^b<c`. Is there any shorter approach? I can’t stop thinking about it, and want confirmation this is the shortest possible way or find the solution...

# Answer
> 25 votes
## Yes, it can be shorter!

`c-b<a^a` beats `a?b<c:b>c` by 2 bytes. My tests show that it works for any integer, including negatives. The downside to this formula is that `a` is repeated twice, which may be unideal depending on your situation.

# Answer
> 11 votes
# I don't think it can be any shorter, at least in the most general case

See dingledooper's 7-bytes solution that works for integers.

If the target expression were `a?b<c:b>=c` (note the change on the second comparison), the two conditions are exactly the opposite, and we can get away with comparing `b` and `c` only once with `a^b>=c` or `!a^b<c`.

**But,** the target is `a?b<c:b>c`, and since `b<c` and `b>c` cannot be inferred from each other, you either need to

* mention `b` and `c` twice each, to carry out two separate comparisons, or
* somehow use the three states (negative, zero, positive) of `b-c`.

For the first method, you already have the optimal answer. For the second, the best I can get is `(c-b)*(a-.5)>0`, 14 bytes (TIO).

Also note that `b^c^a^b<c` doesn't quite work.

---
Tags: code-golf, tips, javascript
---


title: Check membership of an infinite list

text:
# Question
Title: Check membership of an infinite list
As input you will receive

* An integer \\$a\\$
* A list of integers that is *infinite* and *strictly-monotonic*1.

Your program should check **in finite time** if \\$a\\$ appears the list.

You should output one of two distinct values. One if \\$a\\$ appears in the list and the other if \\$a\\$ does not.

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

---

You may take an infinite lists in any of the following formats:

* A list, stream, iterator or generator if your language allows them to be infinite.
* A function or pointer to a function that outputs the next value when queried with no input.
* A function or pointer to a function that outputs the \\$n\\$th value when passed \\$n\\$ as an input.

Additionally you may repeatedly query STDIN with the assumption that each query will provide the next term in the sequence.

---

## Test cases

Since I cannot put infinite lists in the body of a challenge I will provide the first couple terms along with a description of the list and a definition in Haskell.

```
6
1 2 3 4 5 6 7 8 9 10 ... (positive integers) l=[1..]
 =>
True

```

---

```
6
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 ... (negative integers) l=[-1,-2..]
 =>
False

```

---

```
109
0 2 4 6 8 10 12 14 16 18 20 ... (non-negative even integers) l=[0,2..]
 =>
False

```

---

```
-5
200 199 198 197 196 195 194 193 192 ... (integers smaller than 201) l=[200,199..]
 =>
True

```

---

```
256
1 2 3 5 8 13 21 34 55 89 144 ... (unique Fibonacci numbers) l=1:2:zipWith(+)l(tail l)
 =>
False

```

---

```
1
1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 ... (integers less than 2) l=[1,0..]
 =>
True

```

1: A strictly monotonic sequence is either entirely increasing or entirely decreasing. This means if you take the differences between consecutive elements they will all have the same sign.

# Answer
> 25 votes
# Python 2, 43 bytes

Takes as input the target integer \\$a\\$, and a lambda function \\$g\\$. Since the list is always either strictly increasing or decreasing, we only need to check if \\$a\\$ appears in the next \\$ |a-g(0)|+1 \\$ numbers.

```
lambda a,g:a in map(g,range(abs(a-g(0))+1))

```

Try it online!

# Answer
> 9 votes
# Haskell, 33 bytes

```
t#l@(a:r)=t==a||(a<t)==(l<r)&&t#r

```

Try it online!

# Answer
> 7 votes
# convey, ~~144~~ 92 bytes

```
 v<<<<<<<<<<<
>;  >">>??>=@]
"">>,<1[v)>#,
v}^>)?:`(#>#^
v{^"9>v]^",^
>;@">>@`"#^
1>0   >>>^

```

Try it online!

Input is given as a list of integers with the first integer being the goal and the remaining being the list. Since there is no way to accept infinite input, this program instead only consumes a prefix of the input. You can see this in that there is a very long relay line to stop additional input.

### Explanation

To start we need to split the first element off the input, to be used. To do this I use a simple switch, and because we want to use the input a bunch I feed it into a sort of generating vortex to continuously pump out new copies.

Now we split the main stream in two, and calculate the differences on one of the parts. This will tell us if the list is ascending or descending.

Now we use the difference stream to redirect the main stream, to the two different comparison sites. If the list is ascending we want to go until the element is greater than or equal to n if it is descending we want to go until it is less than or equal to n.

So that stream coming out now will give us some ones and then at some point switch to zeros. What we are concerned about is the first number that gives a zero. We want to know if it is equal to n. So we create another stream and get whether that is equal to n.

At this point I'm going to stop with the gifs, since they really look like the end product mostly. We redirect the streams with each other, discarding all the elements before the comparison starts giving zero. Then we use a lock to grab just the first equality. We output this and send a signal to stop taking input. With no input the machine slowly winds down and halts.

# Answer
> 6 votes
# Python 3.8 (pre-release), 61 bytes

```
def f(l,v):
 a=l()
 while(a-v)*(b:=a-l())>0:a-=b
 return a==v

```

Try it online!

Input is a function that returns the next value on every call and an integer.

---

# Python 3.8 (pre-release), ~~70~~ 69 bytes

1 byte shorter thanks to @JonathanAllan.

```
def g(l,v):
 a=next(l)
 while(a-v)*(b:=a-next(l))>0:a-=b
 return a==v

```

Try it online!

Input is a generator and an integer, can probably be shorter with one of other input formats.

# Answer
> 5 votes
# Haskell, 43 bytes

```
a#k@(b:c)|k>c=(-a)#map(0-)k|b<a=a#c|1>0=b>a

```

Try it online!

This outputs `False` if the integer is present and `True` if it is not although I have added a `not` to the handler because that sort of output is confusing to me.

---

## Explanation

The first check we do is `k>c`, that is whether the input is greater than its own tail. Since this list is strictly monotonic the heads of these lists cannot be equal so `k>c` is a short way of comparing their heads. This check thus tells us whether the first element is larger than the second and by extension whether the input is decreasing. If the input is decreasing we negate everything to make it increasing

```
(-a)#map(0-)k

```

The next check is whether `b<a`, that is the head of the list is less than the thing we are looking for. If it is then we should find `a` later in the list so we discard `b` and go again

```
a#c

```

If that fails then `a<=b` meaning that either `b` is `a` or `b` should come before `a`. Since `b` is the first element we know that the only way for `a` to be present is for it to be `b`. Thus we halt returning

```
b>a

```

Which is a shorter way of writing `b/=a` since we know already that `b>=a`.

# Answer
> 4 votes
# Bash \+ GNU utilities, ~~47~~ ~~44~~ ~~43~~ 42 bytes

```
read m
sed 1$[(m-($1))**2]q\;i$m|grep ^$1$

```

Try the test suite online!

*3 bytes off thanks to user41805's pointing out that a single `sed` could be used to replace both the `echo` and the `head`.*

*1 more byte thanks to user41805 again.*

*And now 1 more from user41805.*

The target integer (the integer \\$a\\$ in the challenge description) is passed as an argument, and the infinite list is read from stdin. (The challenge says: "Additionally you may repeatedly query STDIN with the assumption that each query will provide the next term in the sequence.")

The output is the program's exit code (0 for truthy, 1 for falsey).

---

**Explanation:**

The program reads the first number in the infinite list into \\$m\\$.

Let \\$a\\$ be the target integer that we're looking for (it's `$1` in the program). In principle we need to check, after \\$m\\$, at most \\$\left| m-a \right|\\$ additional values in the infinite list, because we're starting at \\$m\\$ and either going up by at least 1 for each number in the list or going down by at least 1 for each number in the list.

However, the program actually checks (more than) \\$(m-a)^2\\$ additional values. That's OK, because \\$(m-a)^2\ge\left|m-a\right|\\$. We may be checking additional (unnecessary) values, but that's harmless.

The original version checked exactly \\$(m-a)^2\\$ additional numbers (using `head`). Unfortunately, replacing `head -${n}` with `sed -${n}q` doesn't work if the value of `n` is 0, so we need to enlarge the number of items checked. To do this, I simply prepend a `1` to the number (which takes one fewer byte than adding 1 to it).

The golfing benefit in doing all this is that, in bash, squaring a number requires fewer bytes than taking the absolute value of a number (as far as I can see).

# Answer
> 3 votes
# Pyth, ~~20~~ ~~17~~ ~~16~~ 9 bytes

Takes `a` on STDIN, then a list of values on STDIN.

**Edit:** Wow, under 10 bytes now! Really shows how powerful Pyth is :P

```
}Q+JEmEaJ

```

Try it online!

Port of @dingledooper's Python answer.

```
}Q+JEmEaJ
 Q              # Initialize Q to be the first input from STDIN
   JE           # Initialize J to be the next input from STDIN
}Q              # Return true if Q is in:
  +             #   The union of
   JE           #      - the first element of the sequence
     mEaJ(Q)    #      - abs(J-Q) more inputs from STDIN (Q appended implicitly)

```

---

**8 bytes**, if we can return the index of `a` in the list

```
x+JEmEaJ

```

Try it online!

```
x+JEmEaJ
x          (Q)  # Find index of Q in:
 +              #   The union of:
  JEmEaJ(Q)     # J and the next abs(J-Q) elements

```

# Answer
> 3 votes
# 05AB1E, ~~14~~ 13 bytes

```
D¥нdiIë(I(}.i

```

-1 byte thanks to *@Grimmy*.

05AB1E has infinite lists, but no functions. So it assumes the infinite list is already at the top of the stack. Assuming this is allowed for stack-based languages according to the meta, but it explicitly mentions functions, so not sure how to handle it here.

Alternatively, the infinite list can be put in a pre-defined variable (i.e. `X`), in which case this would be 15 bytes with that `X` as additional leading byte.

Try it online or verify all test cases. The second line of the header contains the infinite list(s). In the output the first 10 values are printed as example sublist, so you know which infinite list was used in the program.

**Explanation:**

05AB1E has a builtin to check if an integer is in an infinite list that is guaranteed to be non-decreasing, which is `.i`. Using that builtin, we have the following program:

```
D         # Duplicate the infinite list at the top of the stack
 ¥        # Take it's deltas / forward-differences
  н       # Pop and push the first difference of this list
   di     # If it's non-negative:
     I    #  Simply push the input-integer
    ë     # Else (it's negative):
     (    #  Negate all values in the infinite list
      I(  #  Push the input-integer, and negate it as well
    }     # After the if-else, where we now have a non-decreasing infinite list
     .i   # Check if the (possibly negative) input we pushed is inside this infinite list
          # (after which the result is output implicitly)

```

Note that this approach only works because the infinite list is guaranteed to be either only increasing or only decreasing. With an infinite list that is both (i.e. \\$a(n) = \left\lfloor10\tan(n)\right\rfloor\\$`[0, 15, -22, -2, 11, -34, -3, 8, -68, -5, ...]`), this approach of course wouldn't work.

# Answer
> 3 votes
# K (ngn/k), 21 bytes

```
{|/x=y'!1+|/-:\x-y.0}

```

Try it online!

## Explanation

*x* is number, *y* is function representing infinite list.

* `1+|/-:\x-y.0` equivalent to `1 + abs(x - y(0))`
* `!` range
* `y'` apply *y* to each element
* `|/x=` find *x*

# Answer
> 2 votes
# GolfScript, 33 bytes

```
(@:k\-abs:r;0:g;{(k=g+:g;}r*;r!g+

```

Try it online!

This is a very, very quick and dirty way of doing this problem.

TL;DR

Check if the first number is the number we're looking for. If not, then find the difference between our number (finite) and the first number (finite) to get the maximum number of elements we need to search (finite). This is a clusterfuck, clumsy, and messy, but it does the job adequately. There's probably a builtin I'm missing, but I'll come back to this later to refine it and to make code short enough worthy of an explanation.

# Answer
> 2 votes
# Charcoal, 24 bytes

```
ＮθＮηＮζＷ›Π⁻⟦θη⟧ζ⁰Ｎζ№⟦ηζ⟧θ

```

Try it online! Link is to verbose version of code. Reads each value as a separate line on STDIN and outputs `-` only if `a` appears in the monotonic list. Explanation:

```
Ｎθ

```

Input `a`.

```
ＮηＮζ

```

Input the first two terms of the list.

```
Ｗ›Π⁻⟦θη⟧ζ⁰

```

Repeat while the last term of the list so far lies between `a` and the first term.

```
Ｎζ

```

Read another term from the list.

```
№⟦ηζ⟧θ

```

Output `-` if `a` is the first term or the term just read.

# Answer
> 2 votes
# APL (Dyalog Unicode), 15 bytesSBCS

```
{⍵∊⍺⍺⍳1+|⍵-⍺⍺1}

```

Try it online! Uses dingledooper's idea.

```
{             } ⍝ Operator accepting function on the left and integer on the right
   ⍺⍺           ⍝ Apply the input function to
     ⍳           ⍝ the range of integers from 1 to
      1+         ⍝ 1 plus
        |        ⍝ the absolute value of
         ⍵-      ⍝ the input number minus
           ⍺⍺1   ⍝ the first value of the input function.
 ⍵∊              ⍝ Finally check if the input number is in that list.

```

# Answer
> 2 votes
# Ruby, 39 bytes

```
->a,g{[]!=[a]&(0..a*a+g[0]**2).map(&g)}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~7~~ 6 bytes

```
α¬>£0å

```

Try it online! or verify all test cases.

Takes the infinite list input via the stack, like Kevin's 05AB1E answer.

```
α              # absolute difference of the number with each element of the infinite list
               # this list contains 0 iff the original list contains the number
 ¬             # get the first element
  >            # increment
   £           # get the first n elements, where n = first element + 1
    0å         # check if 0 is in those elements

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 31 bytes

```
#2@Range@Abs[#-#2@0]~MemberQ~#&

```

Port of dingledooper's python 2 solution.

Try it online!

Other similar attempts:

```
⌊#⌋==#&&#>=1&@InverseFunction[#2]@#&

```

and:

```
Tr[1^Solve[#2@x==#,x,PositiveIntegers]]==1&

```

# 9 bytes

Mathematica doesn't have iterators or generators in the same way python does, but Regions and Domains take their place. If you allow Regions as an equivalent,

```
{#}∈#2&

```

just tests if the 1d point of the first argument is in the Region. RAW (Rules as written) don't allow Regions, so I'm going to leave the port as the main answer.

Try it online!

The best solution is just Mathematica's built-in `Element` over a domain, but Domains do not seem to be able to be defined by the users, only the premade handful exist.

# Answer
> 2 votes
# Desmos, 41 bytes

```
f(k)=∑_{n=0}^{(k-g(0))^2}0^{(g(n)-k)^2}

```

Because Desmos does not support infinite lists and does not support functions as arguments, the input list should be represented as a function named `g`.

Pretty much a port of dingledooper's Python answer, except I replaced absolute value with square because that is golfier.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# JavaScript (ES7), 49 bytes

*Using @dingledooper's method*

Takes input as `(integer)(generating_function)`. Returns \\$0\\$ or \\$1\\$.

```
n=>g=>(F=k=>k*k>(g(0)-n)**2?0:g(k)-n?F(k+1):1)(0)

```

Try it online!

---

# JavaScript (ES6), 54 bytes

Takes input as `(integer)(generating_function)`. Returns a Boolean value.

```
n=>g=>(F=k=>(v=g(k),g(1)>g(0)?v<n:v>n)?F(k+1):v)(0)==n

```

Try it online!

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

```
t;f(a,p)int*p;{for(t=abs(a-*p)+2;t-->0;)t=*p++-a?t:-1;++t;}

```

Takes a pointer to an "infinite" array. The way I implement this is to only calculate the numbers that are used (and then a "safe buffer" at the end to make sure I don't have any off-by-one errors, but this won't skew the result).

Es un puerto de la solución de dingledooper.

*-1 byte thanks to ceilingcat!*

Try it online!

# Answer
> 1 votes
# Pip `-x`, 24 bytes

```
W(Y(bi))CMa=yCM(bUi)_a=y

```

Uses the third format of infinite list: "A function... that outputs the nth value when passed n as an input." Takes a number and a function as command-line arguments. Attempt This Online!

### Explanation

```
W(Y(bi))CMa=yCM(bUi)_a=y
                          a is the number, b is the function, i is 0 (implicit)
W                         While...
   (bi)                     Call b with argument i
  Y                         Yank the result into y
 (     )CMa                 Compare that value with a (returns -1, 0, or 1)
           =                Equals
            yCM             Compare y with
               (b  )        Call b with argument
                 Ui         Increment i
                          ... loop:
                    _       No-op
                          When the loop exits, we've either reached or passed a
                     a=y  1 if the most recent sequence value equals a, 0 otherwise
                          Autoprint (implicit)

```

# Answer
> 0 votes
# Perl 5, 55 bytes

```
sub f{$f=pop;@L=($F=&$f,map&$f,0..abs$_[0]-$F);pop~~@L}

```

Try it online!

More or less a translation of @dingledooper's Python2 answer.

# Answer
> 0 votes
# perl -lE, 34 bytes

```
$t=<>;{$_=<>;$_<$t?redo:say$_==$t}

```

Try it online!

Prints `1` followed by a newline if the first element of the list appears elsewhere; otherwise, it just prints a newline. The program terminates after reading the first number which is equal or larger than the first number.

# Answer
> 0 votes
# Java (JDK), 67 bytes

```
a->s->{int p=s.get(),n;for(;p*(n=p-s.get())>a*n;)p-=n;return p==a;}

```

Try it online!

# Credits

# Answer
> 0 votes
# C++ (gcc), 114 bytes 106 bytes

```
#include<iostream>
int f(int a){int p,t;std::cin>>t;if(t-=a)for(;p=t,std::cin>>t,t-=a,p*t>t*t;);return!t;}

```

Try it online!

---

**Explanation :**

Our only hope of finding \\$\alpha\\$ in the future terms of the list \\$t\\$ is if :

* We don't skip over \\$\alpha \implies\\$ The difference of \\$\alpha\\$ and \\$t\_n\\$ doesn't change signs \\$\implies \left(\alpha - t\_n\right)\cdot\left(\alpha - t\_{n-1}\right)\>0 \space \forall \space n\in N, n \> 1\\$.(If it is zero, one of the terms is our target)
* The series approaches our target \\$\implies {\left| \alpha - t\_n\right|} \< {\left| \alpha - t\_{n-1}\right|}\\$

We can then combine these two conditions :
$$ {\left| \alpha - t\_n\right|} \< {\left| \alpha - t\_{n-1}\right|} $$ $$ \implies {\left| \alpha - t\_n\right|} \cdot {\left| \alpha - t\_{n-1}\right|} \< {\left( \alpha - t\_{n-1}\right)}^2$$ $$ \text{Since we need that}\left(\alpha - t\_n\right)\cdot\left(\alpha - t\_{n-1}\right)\>0, $$ $$ \text{Condition } P \equiv \left( {\left| \alpha - t\_n\right|} \< {\left| \alpha - t\_{n-1}\right|} \right) \land \left( \left(\alpha - t\_n\right)\cdot\left(\alpha - t\_{n-1}\right)\>0 \right) $$ $$ P \equiv \left(\alpha - t\_n\right)\cdot\left(\alpha - t\_{n-1}\right) \< {\left(\alpha - t\_{n-1}\right)}^2 $$

Hence if \\$P\\$ is found to be false the either the target has been found or we have passed it (or never reach it).

# Answer
> 0 votes
# Ruby, 56 bytes

```
f=->a,g,t=1{a==g[t]||(g[2]-g[1])*(g[t]-a)<0&&f[a,g,t+1]}

```

Recursively, checks if current term `g[t] == a`, then return `true`. Else, check if the **product** of difference `g[2] - g[1]` and `a - g[t]` are of opposite sign, if yes, then return `false`

Try it online!

---

# Ruby, 40 bytes

*Port of dingledooper's Python answer!*

```
->a,g{(1..(a-g[0]).abs+1).map(&g).any?a}

```

Try it online!

# Answer
> 0 votes
# Julia, 23 bytes

```
N\~=N∈.~(0:abs(N-~0))

```

Try it online!

takes a zero-indexed function as input

port of dingledooper's solution. The solution I found on my own was exactly double the length

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


title: How tall are the mushrooms?

text:
# Question
Title: How tall are the mushrooms?
In this challenge you will receive a list of non-negative integers. Each one represents a mushroom with a cap of that radius centered at that location. So a `0` means that it occupies no space at all, a `1` means that its cap only occupies space above it, a `2` means it occupies space above it and one unit to the left and right etc. More generally for size \\$n\\$ a total of \\$2n-1\\$ spaces are occupied, with the exception of 0 which occupies 0 spaces (i.e. there's no mushroom at all).

Mushroom caps can't occupy the same space as each other but mushrooms can have different heights to avoid collisions.

So for example here we have two mushrooms. They can't be in the same row since they would occupy the same space but if they are given different heights there is no issue:

```
          =-=-=
            |
  =-=-=-=-= |
      |     |
[ 0,0,3,0,0,2,0 ]

```

(Stems are drawn with `|` for clarity, but can't collide)

Your task is to take as input a list of mushrooms and output a list of heights, one for each input mushroom, such that there is no collisions between mushrooms and they occupy the fewest total rows.

For example here we have a worked case:

```
=-=-= =-=-=-=-=-=-= =
  |         |       |
  | =-=-=   |   =-=-=
  |   |     |     | |
  =-=-=     =-=-=-=-=
  | | |     |   | | |
[ 2,2,2,0,0,4,0,3,2,1 ] <- Widths
[ 2,0,1,0,0,2,0,0,1,2 ] -> Heights

```

(Stems are drawn with `|`, and extra spacer rows are added between layers for clarity)

For any input there are a wide variety of valid answers, you are allowed to output any 1 of them or all of them. You may also consistently use 1-indexed heights instead of 0-indexed heights if you wish.

This is so the goal will be to minimize the size of your source code as measured in bytes.

## Selected examples

Here are some selected examples with possible solutions:

This one defeats a certain greedy algorithm:

```
  =-=-= =
    |   |
=-=-= =-=-=-=-=
  | |   | |
[ 2,2,0,1,3 ] <- Width
[ 0,1,0,1,0 ] -> Height

```

This one requires everything to be on its own row:

```
    =-=-=-=-=-=-=
          |
  =-=-=-=-=-=-=
        | |
    =-=-= |
      | | |
    = | | |
    | | | |
=-=-= | | |
  | | | | |
[ 2,1,2,4,4 ] <- Width
[ 0,1,2,3,4 ] -> Height

```

# Answer
> 3 votes
# JavaScript (ES7),  ~~146 131~~  129 bytes

*Saved 15 bytes thanks to @Neil!*

Returns a single solution as a space-separated string.

```
f=(a,...B)=>(F=(x,b,o,w=a[x])=>1/w&&b.every((v,i,[...c])=>v&(c[i]|=m=4**w/2-1<<x>>w,m)||F(x+1,c,O=[o]+i+' ')))(0,B)?f(a,...B,0):O

```

Try it online!

### How?

We generate one bitmask per mushroom cap and attempt to dispatch them among \\$N\\$ rows without any collision, trying all possible distributions. We start with \\$N=0\\$ (which is obviously unlikely to work) and increment \\$N\\$ until a solution is found.

The pattern for a mushroom cap of width \\$w\\$ and position \\$x\\$ is computed with:

$$\left\lceil\frac{4^w}{2}-1\right\rceil$$

which generates \\$max(0,2w-1)\\$ consecutive \\$1\\$'s.

The final bitmask is obtained by shifting this pattern by \\$x\\$ positions to the left and \\$w\\$ positions to the right.

# Answer
> 3 votes
# Jelly, 23 bytes

```
Ḥ’R_"+"JJṗL;Ɱ"ẎQƑɗƇƲṀÞḢ

```

A monadic Link that accepts a list of non-negative integers and yields a list of positive integers specifying the levels (i.e. 1-indexed heights).

**Try it online!**

### How?

Inefficient brute-force...

```
Ḥ’R_"+"JJṗL;Ɱ"ẎQƑɗƇƲṀÞḢ - Link: cap sizes
Ḥ                       - double (the cap sizes)
 ’                      - decrement (these)
  R                     - range (those) - i.e. [[1..2*n-1] for each cap size, n]
    "                   - zip (those) and (cap sizes) applying:
   _                    -   subtraction - i.e. make these offsets like [...,-1,0,1,...]
       J                - range of length (cap sizes) -> [1..length(cap sizes)]
      "                 - zip (the offsets) with (the range) applying:
     +                  -   addition -> covered indices of each mushroom, "covers"
                   Ʋ    - last four links as a monad - f(covers):
        J               -   range of length -> same as [1..length(cap sizes)]
          L             -   length -> same as length(cap sizes)
         ṗ              -   (range) Cartesian power (length)
                              -> all lists of the same length as cap sizes
                                 using alphabet [1..length(cap sixes)]
                  Ƈ     -   filter keep those (arrangements) for which:
                 ɗ      -     last three links as a dyad - f(arrangement, covers):
             "          -       zip with:
            Ɱ           -         map with:
           ;            -           concatenate -> coordinates
              Ẏ         -       tighten
                Ƒ       -       is invariant under?:
               Q        -         deduplicate
                     Þ  - sort by:
                    Ṁ   -   maximum value
                      Ḣ - head

```

# Answer
> 2 votes
# Charcoal, ~~115~~ ~~112~~ 102 bytes

```
≔⟦⟦⟦⟧⟦⟧⟧⟧ηＦＥθ÷×÷⊖Ｘ⁴ι²Ｘ²κＸ²ι«≔⟦⟧ζＦη«≔§κ¹εＦΦＬε¬＆§ελι⊞ζ⟦⁺§κ⁰⟦λ⟧Ｅε⎇⁼νλ⁺μιμ⟧⊞§κ⁰Ｌε⊞ει⊞ζκ»≔ζη»≔ＥηＬ⊟ιζＩ§η⌕ζ⌊ζ

```

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

```
≔⟦⟦⟦⟧⟦⟧⟧⟧η

```

Start with no mushrooms placed.

```
ＦＥθ÷×÷⊖Ｘ⁴ι²Ｘ²κＸ²ι«

```

For each mushroom, calculate a bitmask corresponding to the space that it occupies. Edit: Saved 3 bytes by using my golf to @Arnauld's formula.

```
≔⟦⟧ζ

```

Start collecting placements that include this mushroom.

```
Ｆη«

```

Loop over the existing placements.

```
≔§κ¹ε

```

Get the bitmasks for the heights as this gets used a lot.

```
ＦΦＬε¬＆§ελι

```

Find whether this mushroom can be placed at any existing height.

```
⊞ζ⟦⁺§κ⁰⟦λ⟧Ｅε⎇⁼νλ⁺μιμ⟧

```

Generate a placement for putting this mushroom at that height.

```
⊞§κ⁰Ｌε⊞ει⊞ζκ

```

Generate a placement for putting this mushroom at a new height.

```
»≔ζη

```

Save the new placements as the current placements.

```
≔ＥηＬ⊟ιζ

```

Get the heights of all of the placements.

```
Ｉ§η⌕ζ⌊ζ

```

Output one of the placements with minimal height.

Previous less inefficient 112-byte version:

```
≔⟦⟦⟦⟧⟦⟧⟧⟧ηＦＥθ÷×÷⊖Ｘ⁴ι²Ｘ²κＸ²ι¿ι«≔⟦⟧ζＦη«≔§κ¹εＦΦＬε¬＆§ελι⊞ζ⟦⁺§κ⁰⟦λ⟧Ｅε⎇⁼νλ⁺μιμ⟧⊞§κ⁰Ｌε⊞ει⊞ζκ»≔ζη»Ｆη⊞§κ⁰¦⁰≔ＥηＬ⊟ιζＩ§η⌕ζ⌊ζ

```

Try it online! Link is to verbose version of code. Explanation: Always places zero-width mushrooms at zero height instead of at all possible heights.

# Answer
> 2 votes
# Python3, 248 bytes:

```
from itertools import*
E=enumerate
C=lambda x,c,I:[i for i,a in E(x)if a*((a-1+i>=I-c+1 and i<I)or(i-a+1<=I+c-1 and i>I))]
f=lambda x:min([i for i in product(*[range(j+1)for j in x])if all(all(i[t]!=m for t in C(x,x[n],n))for n,m in E(i))],key=max)

```

Try it online!

Heights are 0-indexed.

A longer, no-import solution:

```
E=enumerate
def F(x):r={j:a for a,b in min(f(x),key=len).items()for j in b};return[r[i]*(a>0)for i,a in E(x)]
C=lambda x,c,I:{*[i for i,a in E(x)if a*((a-1+i>=I-c+1 and i<I)or(i-a+1<=I+c-1 and i>I))]+[I]}
def f(x,c=0,d={0:[]}):
 if len(x)==c:yield d;return
 for i in d:
  if not C(x,x[c],c)&set(d[i]):yield from f(x,c+1,{**d,i:d[i]+[c]})
 yield from f(x,c+1,{**d,max(d)+1:[c]})

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~45~~ 43 bytes

```
εD(Ÿ¦¨N+}[DN.Œ.Δε˜DÙQ}P}Zd#\}ε€ÅsIgÝ¨åN*}øO

```

Brute-force approach.

Try it online or verify both test cases.

**Explanation:**

Step 1: Change each value in the input to a list of indices it can reach:

```
ε            # Map over each value of the (implicit) input-list:
 D(          #  Create a negative copy
   Ÿ         #  Pop both, and push a list in the range [n,-n]
    ¦¨       #  Remove the first and last to make the range (n,-n)
             #  (or empty the list if n=0)
      N+     #  Add the current map-index as offset
}            # Close the map

```

Try just this first step.

Step 2: Indefinitely loop up from \\$N=0\\$ and get all \\$N\\$-element combinations of the list of lists. Stop as soon as we've found a partition for which all inner indices are unique.

```
[            # Start an infinite loop:
 D           #  Duplicate the list we've created in step 1
  N          #  Push the loop-index `N`
   .Œ        #  Pop both, and get all N-sized partitions of the list
     .Δ      #  Find the first partition that's truthy for:
             #  (or -1 if none are truthy)
       ε     #   Map over each part:
        ˜    #    Flatten the list of lists of indices
         DÙQ #    Check whether all indices are unique:
         D   #     Duplicate it
          Ù  #     Uniquify this copy
           Q #     Check if both lists are still the same
       }P    #   After the map: check if all parts were truthy
      }Z     #  After the find_first: push the maximum (without popping)
             #  (which results in "-" for -1)
        d    #  If this is a non-negative integer (0 for "-", 1 otherwise)
         #   #   Stop the infinite loop, since we have a hit
         \   #  (else:) discard the -1 that's still on the stack
}            # Close the infinite loop

```

Try just the first two steps.

Step 3: Convert this found result of parts of index-ranges to a list of heights to output:

```
ε            # Map over each part in this partition:
 €           #  Inner map over each inner index-range (-n,n):
  Ås         #   Pop and leave just the middle value
             #   (this is the offset we've added in step 1,
             #    or [] if the list was empty for n=0)
    IgÝ¨     #  Push a list in the range [0, input-length):
    I        #   Push the input-list
     g       #   Pop and push its length
      Ý      #   Pop and push a list in the range [0,length]
       ¨     #   Remove the last item to make the range [0,length)
        å    #  Check for each if it's in the earlier list
         N*  #  Multiply each by the 0-based map-index,
             #  which are the heights
}ø           # After the map: zip/transpose; swapping rows/columns
  O          # Sum each inner list (mapping each to its max, since each inner
             # list will only contain (at most) one non-0 height)
             # (after which this list of heights is output implicitly)

```

*Note: It outputs the first result it can find, so for the second example test case, it outputs this list of mushroom-heights:*

```
    =-=-=       =-=-=
      |           |
  =-=-=     =-=-=-=-=
    | |         | |
=-=-= =-=-=-=-=-=-= =
[ 2,2,2,0,0,4,0,3,2,1 ] <- Widths
[ 0,1,2,0,0,0,0,1,2,0 ] -> Heights

```

# Answer
> 1 votes
# Python, ~~293~~ ~~264~~ ~~263~~ 262 bytes

*-1 bytes thanks to @Kevin Cruijssen*

```
j=lambda h:min((((n:=h.copy()).__setitem__(a+b,n.pop(a)|n.pop(b)))or j(n)for a in h for b in h if not h[a]&h[b]),default=h,key=len)
def f(w):
    r=[0]*len(w);i=0
    for K in j({(i,):set(range(-x-~i,x+i))for i,x in enumerate(w)}):
        for k in K:r[k]=i
        i+=1
    return r
```

Attempt This Online!

Note: it's extremely inefficient.

A slightly more efficient (and longer) variant:

```
from itertools import*
j=lambda h:min((((n:=h.copy()).__setitem__(a+b,n.pop(a)|n.pop(b)))or j(n) for a,b in combinations(h,2)if not h[a]&h[b]),default=h,key=len)
def f(w):
    r=[0]*len(w);i=0
    for K in j({(i,):set(range(-x+1+i,x+i))for i,x in enumerate(w) if x}):
        for k in K:r[k]=i
        i+=1
    return r
```

Attempt This Online!

# Answer
> 1 votes
## Clojure, ~~214~~ 227 bytes

```
(defn f([W](:H(nth(flatten(for[m(range)](f m 0 W[][1])))0)))([m i W H O](if-let[w(nth W i nil)](for[h(range(if(= w 0)1 m))O[(into O(for[d(range(+(- w)1)w)][(+ i d)h]))]:when(apply distinct? O)](f m(inc i)W(conj H h)O)){:H H})))

```

TIO.

Buggy code:

```
(defn f([W](:H(nth(flatten(f 0 W[][1]))0)))([i W H O](if-let[w(nth W i nil)](for[m(range)h(range(if(= w 0)1 m))O[(into O(for[d(range(+(- w)1)w)][(+ i d)h]))]:when(apply distinct? O)](f(inc i)W(conj H h)O)){:H H})))

```

I thought I could move the `for[m(range)...` from the initial function call inside the recursion, but apparently it leads to a wrong output in come cases.

Less golfed:

```
(defn f
  ([widths] (first (flatten (for [max-height (range)] (f max-height 0 widths [] [])))))

  ([max-height ix widths heights occupied]
   (if (-> widths count (= ix))
     {:heights heights :occupied occupied}
     (for [w [(widths ix)]
           h (range (if (= w 0) 1 max-height))
           :let [new-occupied (for [dx (range (-> w - inc) w)] [(+ ix dx) h])
                 occupied (into occupied new-occupied)]
           :when (apply distinct? nil occupied)] ; Cannot call `distinct?` without any arguments, thus the `nil` is there.
       (f max-height (inc ix) widths
          (conj heights h)
          occupied)))))

```

# Answer
> 1 votes
# JavaScript (Node.js), ~~143~~ 142 bytes

```
f=(a,i=x=[])=>(g=y=>1/a[y.length]?x.some(i=>g(O=[...y,i])):!a.some((P,p)=>a.some((Q,q)=>y[p]==y[q]&p<q&P+Q>q-p+1&&P*Q)))([])?O:f(a,x.push(+i))

```

Try it online!

# Answer
> 1 votes
# Vyxal, 28 bytes

```
d‹ɾ-:ż+:£₌żLÞẊ'¥¨£v"ÞfÞu;⁽G∵

```

Try it Online!

Port of Jelly. Outputs a list of 1-indexed heights.

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


title: Square root of ASCII art

text:
# Question
Title: Square root of ASCII art
You are working as an intern for a mathematician who *really* hates TeX, LaTeX, etc. So much so that he has decided to abandon all typesetting whatsoever and make you do all the formatting in ASCII. You got tired of this after a while and decided to start automating parts of it, starting with square roots.

Here's how a square root is made:

```
###  this is the input
###
###

_____  put a row of underscores stretching one character off either side on top
 ###
 ###
 ###

   _____  put a diagonal of slashes in front going the height of the input
  / ###
 /  ###
/   ###

      _____ put a diagonal of backslashes in front of that, going up half of the input's height rounded up
     / ###
 \  /  ###
  \/   ###

```

And that's it!

### Rules

You are to make a program or function that takes in a string, list of strings (i.e. lines), or array of characters, and outputs the input transformed according to the description above (not necessarily by the exact same order or process)

You may assume that the input is rectangular if preferred. Trailing whitespace is neither required nor disallowed.

This is , so the shortest answer in bytes wins.

### Examples:

```
Input:
40
Output:
  ____
\/ 40

Input:
  ____
\/ 40
Output:
   ________
  /   ____
\/  \/ 40

Input:
/|
 |
 |
_|_
Output:
      _____
     / /|
    /   |
\  /    |
 \/    _|_

Input:
#  #
#  #
#####
   #
   #
Output:
        _______
       / #  #
      /  #  #
\    /   #####
 \  /       #
  \/        #

```

# Answer
> 7 votes
# Python 2, 196 bytes

```
x=Q=input()
l=len(x)
k=(l+1)/2
q=l+k
x=[[' ']*(q+1)+list(y)for y in x]
for i in range(k):x[i+l/2][i]='\\'
for j in range(l):x[j][q-j-1]='/'
print'\n'.join([' '*q+'_'*(2+len(Q[0]))]+map(''.join,x))

```

Try it online!

-2 bytes thanks to Step Hen

-13 bytes thanks to Jonathan Allan

# Answer
> 7 votes
# SOGL V0.12, 27 bytes

```
1w⁄2+╔*00žl»╚;lH╚@Κ№↕h┼№↕;┼

```

Try it Here! ( added for ease-of-use; the program expects the input on stack)

# Answer
> 6 votes
# Python 3, 138 147 Bytes

```
def f(l):h=len(l);w=len(l[0]);c=int(h/2);print('\n'.join([(h*2-c)*' '+w*'_']+[(i*' '+'\\'+(h-i-1)*2*' '+'/'+i*' ')[c:]+s for(i,s)in enumerate(l)]))

```

Variable 'l' is a list of strings, each string a line. Readable Version:

```
def f(l):
  height = len(l)
  width = len(l[0])
  half_height_floor = int(height / 2)

  print((height * 2 - half_height_floor) * ' ' + width * '_')

  for (index, line) in enumerate(l):
    #build a V based on the location of the line
    #surrounding V whitespace
    outer_space = index * ' '

    #inner V whitespace
    inner_space = (height - index - 1) * 2 * ' ' #inner v space

    #complete V
    v = outer_space + '\\' + inner_space + '/' + outer_space

    #left half_height_floor chars removed
    v_chopped = v[half_height_floor:]

    print(v_chopped + line)

```

Forms a square root symbol with a complete V then shaves off the left accordingly.

Try it Online!

# Answer
> 5 votes
# Charcoal, 32 bytes

```
ＷＳ⊞υιＰ⪫υ¶↖Ｐ×_⁺²⌈ＥυＬι↙↙Ｌυ↑↖÷⁺¹Ｌυ²

```

Try it online! Link is to verbose version of code. 29-byte version that assumes rectangular input:

```
ＷＳ⊞υιＰ⪫υ¶↖Ｐ×_⁺²Ｌθ↙↙Ｌυ↑↖÷⁺¹Ｌυ²

```

# Answer
> 4 votes
# Python 2,  ~~131~~  130 bytes

```
x=input()
n=len(x)
s=" "
for v in[s*2*n+"_"*(2+len(x[0]))]+[s*i+"\\"+s*2*(n+~i)+"/"+s*-~i+r for i,r in enumerate(x)]:print v[n/2:]

```

A full program taking a list of lines as input with the rectangular-only allowance (actually that the first line is one of the longest).

**Try it online!**

# Answer
> 2 votes
# Java 8, 244 bytes

A very long solution, but probably close to the shortest for Java. This lambda takes lines of input as a `String[]` and returns a `String`. All lines must have the same length.

Based on the example outputs, I assumed that there's no need to append a space to each line in the input, so the program doesn't.

Thanks to *Jonathan Allan* for reminding me about the `~` operator.

```
l->{int h=l.length,w=l[0].length(),a=h/2,i=w+3,x=h+a+h%2;String s="",t=s;for(;--i>0;)t+="_";for(;i++<x;)s+=" ";t=s+t;for(i=0;i<h;)t+="\n"+s.substring(0,i<a?x+~i:i-a)+(i<a?"":"\\"+s.substring(0,(h+~i)*2))+"/"+s.substring(0,i+1)+l[i++];return t;}

```

Try It Online

## Ungolfed

```
l -> {
    int
        h = l.length,
        w = l[0].length(),
        a = h / 2,
        i = w + 3,
        x = h + a + h % 2
    ;
    String
        s = "",
        t = s
    ;
    for (; --i > 0; )
        t += "_";
    for (; i++ < x; )
        s += " ";
    t = s + t;
    for (i = 0; i < h; )
        t +=
            "\n"
            + s.substring(0, i < a ? x + ~i : i - a)
            + (i < a ? "" : "\\" + s.substring(0, (h + ~i) * 2))
            + "/"
            + s.substring(0, i + 1)
            + l[i++]
        ;
    return t;
}

```

## Acknowledgments

* -2 bytes thanks to *Kevin Cruijssen*

# Answer
> 2 votes
# Vyxal `a`, 67 bytes

```
L3*½⌈ð*₴⁰hL⇧\_*,ƛ¥⁰L½⌊-:0≥[:ð*\\+₴⁰L½⌈ε‹|_⁰L½⌈]&›ð*₴⁰L¥εð*\/¥ð*++₴,

```

Try it Online!

**Don't ask how it works**. It's a giant mess.

# Answer
> 2 votes
# Vyxal, ~~40~~ 32 bytes

```
ẏṘ\\$꘍øm↵:IǏfL:£Nvȯ$Z¥?hL⇧\_*꘍p⁋

```

Try it Online! or verify all test cases.

*-8 bytes from porting 05AB1E*

# Answer
> 1 votes
# Japt, 46 bytes

```

l *2
£Vç hY'\ h~Y'/ +S+XÃuVç +'_p2+Ug l¹msV/4

```

Leading newline is part of the program. Input and output is an array of strings representing lines.

Try it online! using the `-R` flag to join the resulting array with newlines.

# Answer
> 1 votes
# Perl 5, 177 185 160 bytes

```
$s=$f=int((@t=<>)*1.5+.5);print" "x$f;print"_"x length$t[0];print"_
";$b=-int(@t/2);for(0..$#t){--$s;print$_==$s?"/":$_==$b?"\\":" " for 0..$f;print$t[$_];++$b}

```

Try it online!

Changelog:

* needed more bytes to fix a bug (it assumed a *square* input first)
* fixed another bug and used some tips from comments (thanks Dada!)

# Answer
> 1 votes
## JavaScript (ES6), 140 bytes

Takes input as an array of strings / returns an array of strings.

```
a=>[a[0].replace(/./g,'_'),...a].map((r,y)=>[...a,...a].map((_,x)=>x-y+1|y-.5<l/2?l*2-x-y?' ':'/':'\\',c=y?' ':'_').join``+c+r+c,l=a.length)

```

### Test cases

```
let f =

a=>[a[0].replace(/./g,'_'),...a].map((r,y)=>[...a,...a].map((_,x)=>x-y+1|y-.5<l/2?l*2-x-y?' ':'/':'\\',c=y?' ':'_').join``+c+r+c,l=a.length)

console.log(
  f([
    '40'
  ]).join`\n`
)

console.log(
  f([
    '  ____',
    '\\/ 40 '
  ]).join`\n`
)

console.log(
  f([
    '/| ',
    ' | ',
    ' | ',
    '_|_'
  ]).join`\n`
)

console.log(
  f([
    '#  # ',
    '#  # ',
    '#####',
    '   # ',
    '   # '
  ]).join`\n`
)
```

# Answer
> 1 votes
# C (clang), ~~169~~ 151 bytes

*-18 thanks to @ceilingcat*

```
#define P printf("%*c"
i;k;f(**l,c){P,i=c+c-c/2,32);for(k=strlen(*l)+3;--k;)P,1,95);for(;P,1,10),k<c;P"%s",k,32,*l++))P,i-k-P,k++<c/2?0:k-c/2,92),47);}

```

Try it online!

# Answer
> 0 votes
## C++, 291 bytes

The function assumes that all the strings in the vector passed as parameter have the same length

```
#include<vector>
#include<string>
#define S std::string
#define T size()
void f(std::vector<S>&c){c.insert(c.begin(),S(c[0].T+1,'_'));int i,j=0;for(i=1;i<c.T;++i){c[i]='/'+S(i,' ')+c[i];if(i>=c.T/2)c[i]='\\'+S((c.T-i-1)*2,' ')+c[i];}for(auto&a:c)j=j>a.T?j:a.T;for(auto&a:c)a=S(j-a.T,' ')+a;}

```

# Answer
> 0 votes
# Dyalog APL, 95 bytes

```
{((' '/⍨y+x),'_'/⍨2+⊃⌽⍴⍵)⍪⍉(x-y)↓⍉(⊖(x(-x)↑⌽y y⍴'\',' '\⍨y←⌈x÷2),x x⍴'/',' '\⍨x←⊃⍴⍵),' ',⍵,' '}

```

Try it online!

# Answer
> 0 votes
**C, 485 bytes**

This program takes up to 999 characters from standard input and reads them into an array. It prints them 1 at a time to standard output with the changes your challenge indicated. It assumes the input is rectangular.

```
#include<stdio.h>
#define p(a)putc(a,stdout);
#define P j+j/2+1
a[999],i,j,k,l,m,n,q;char c;pad(a){m=P;if(a&&!k){m-=1;}for(n=0;n!=m;n++){q=32;if((!a||k)&&n==c){c--;q=47;}else if((P-c+1)>j/2+1&&(P)/2-n==c-2){q=92;}p(q);}}int main(){k=i=j=0;x:if(read(0,&c,1)){if('\n'==(a[i++]=c)){if(!j){l=i;}j++;}goto x;}i--;if('\n'==a[i-1]){i--;}else{j++;}c=P-2;for(;k!=i;k++){if(!k||a[k]==10){if(a[k]==10){p(10);}pad(1);if(!k){l++;while(l-->0){p(95);}p(10);pad(0);}if(a[k]==10){continue;}}p(a[k]);}}

```

# Answer
> 0 votes
# Perl 5, 159 bytes

```
@a=map{$m=(y///c)>$m?y///c:$m;$_}<>;$_=$"x($l=@a/2-.5).'\\/'.$"x@a;for$i(1..@a){$a[-$i]=$_.$a[-$i];s| \\|\\ |;s|/ | /|;$i>$l&&y/\\/ /}chop;say$_.'_'x++$m,$/,@a

```

Try it online!

# Answer
> 0 votes
# Canvas, 26 bytes

```
Ｌ├_×；∔ｒ↔ｌ╷＼ ；∔＋ｌ½：／； ＊；∔＋↔

```

Try it here!

# Answer
> 0 votes
# 05AB1E, 35 bytes

```
ā<R'\úíº.c.BD2äĆ˜g©δ.£søIнgÌ'_×®úš»

```

Input as a rectangular list of strings-lines (rectangular isn't completely necessary, as long the first line is the longest).

Try it online or verify all test cases or see the step-by-step output.

**Explanation:**

```
ā             # Push a list in the range [1, (implicit) input-length]
 <            # Decrease each by 1 to the range [0, length)
  R           # Reverse it to the range (length, 0]
   '\        '# Push string "\"
     ú        # Pad "\" with the integer amount of leading spaces
      í       # Reverse each, so the spaces are trailing
       º      # Mirror each line
        .c    # Centralize (implicitly joins by newlines)
          .B  # Box it (split on newlines, and add trailing spaces)
D             # Duplicate it
 2ä           # Split it into two equal-sized parts (where the first is longer
              # for odd-length lists)
   Ć          # Enclose: append its own head
    ˜         # Flatten
     g        # Pop and push the length
      ©       # Store it in variable `®` (without popping)
       δ      # Map over each string:
        .£    #  Only leave the last `®` amount of characters
s             # Swap so the input-list is at the top
 ø            # Create pairs of the two lists
  Iн          # Push the first line of the input-list
    g         # Pop and push its length
     Ì        # Increase it by 2
      '_×    '# Pop and push a string of that many "_"
         ®ú   # Pad `®` amount of leading spaces
           š  # Prepend it to the list
            » # Join each inner list by spaces, and then the strings by newlines
              # (after which the result is output implicitly)

```

`2äĆ˜g` could alternatively be `gD;î+` for the same byte-count (length; duplicate; halve; ceil; sum together): try it online.

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