# Question
Title: How many matchstick moves to change a number?
Using the matchstick numbers here: Count the Matchsticks

```
 _        _   _         _    _    _    _    _
| |   |   _|  _|  |_|  |_   |_     |  |_|  |_|
|_|   |  |_   _|    |   _|  |_|    |  |_|   _|

```

How many matchsticks must be moved and/or removed to change one number into another?

You will take two single digit numbers (0 to 9) as input (however works for you language), and return the number of moves needed to convert from the first input number to second input number, as though they were written in matchsticks. If no such operation is possible output some sort of 'Error Response' (any consistent output other a than a positive number or zero (if the output is a number, could be from -1 -\> -Infinity) or you let the program crash):

Input: 9 0
Output: 1

Input: 8 9
Output: 1

Input: 0 1
Output: 4

Input: 7 8
Output: 'Error response'

Input: 8 7
Output: 4

Input: 2 5
Output: 2

Input: 2 3
Output: 1

Input: 5 6
Output: 'Error response'

Input: 4 4
Output: 0

Input: 6 7
Output: 4

Here is the full table of first and second inputs, and each cell is the output:

| input 1 v/input 2 \> | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| **0** | 0 | 4 | 2 | 2 | 3 | 2 | 1 | 3 | err | 1 |
| **1** | err | 0 | err | err | err | err | err | err | err | err |
| **2** | err | 4 | 0 | 1 | 3 | 2 | err | 3 | err | err |
| **3** | err | 3 | 1 | 0 | 2 | 1 | err | 2 | err | err |
| **4** | err | 2 | err | err | 0 | err | err | 2 | err | err |
| **5** | err | 4 | 2 | 1 | 2 | 0 | err | 3 | err | err |
| **6** | 1 | 4 | 2 | 2 | 3 | 1 | 0 | 4 | err | 1 |
| **7** | err | 1 | err | err | err | err | err | 0 | err | err |
| **8** | 1 | 5 | 2 | 2 | 3 | 2 | 1 | 4 | 0 | 1 |
| **9** | 1 | 4 | 2 | 1 | 2 | 1 | 1 | 3 | err | 0 |

# Answer
# Python 3, ~~116~~ ~~99~~ ~~95~~ 89 bytes

*Thanks to ovs for informing me about byte literals.* *2 bytes saved by l4m2.* *6 bytes saved by emanresuA.*

```
r=b'w][:koR{'
g=lambda x,y:bin(r[x]&~r[y]).count('1')
lambda x,y:g(x,y)<g(y,x)or g(x,y)

```

Try it online!

# Python 3.10+, ~~97~~ ~~93~~ 87 bytes

*Thanks to Kevin Cruijssen for this golf*

```
lambda x,y:g(x,y)<g(y,x)or g(x,y)
r=b'w][:koR{'
g=lambda x,y:(r[x]&~r[y]).bit_count()
```

Attempt This Online!
> 8 votes

# Answer
# JavaScript, ~~98~~ ~~97~~ ~~88~~ 82 bytes

-6 bytes from tsh

```
f=

x=>y=>n(x=r[x])>n(y=r[y])||n(y&~x)
r=[2,91,40,9,81,5,4,27,0,1]
n=c=>c&&n(c>>1)+c%2

arrx=[...Array(11)];
fb=(a,b)=>f(a)(b)===true?'-':f(a)(b)
document.write('<table>'+arrx.map((_,i)=>'<tr>'+arrx.map((_,j)=>'<td>'+(i*j?fb(i-1,j-1):'<b>'+(i+j?i+j-1:'')+'</b>')+'</td>').join``+'</tr>').join``+'</table>')
```

Digit map `0,5,6,1,2,3,4`

Maybe longer than Python cuz `n` and `r`
> 6 votes

# Answer
# 05AB1E, 25 bytes

```
•Q¡ĀŠL›š»•₃вIèÂ±&b1öÂ`@iθ

```

Input as a pair of integers; outputs the pair as error value (if this is not allowed, a trailing `ë®` can be added to output `-1` instead).

Port of *@l4m2*'s JavaScript answer, so make sure to upvote him/her as well!

Try it online or verify all test cases.

**Explanation:**

```
                 #  e.g. input = [2,1]
•Q¡ĀŠL›š»•       # Push compressed integer 1867012004107141926
                 #  STACK: 1867012004107141926
 ₃в              # Convert it to base-95 as list
                 #  STACK: [2,91,40,9,81,5,4,27,0,1]
   Iè            # 0-based index the input-pair into this list
                 #  STACK: [40,91]
     Â           # Bifurcate it, short for Duplicate & Reverse copy
                 #  STACK: [40,91],[91,40]
      ±          # Bitwise-NOT the values in the copy
                 #  STACK: [40,91],[-92,-41]
       &         # Bitwise-AND the values at the same positions together
                 #  STACK: [32,83]
        b        # Convert each to a binary string
                 #  STACK: [100000,1010011]
         1ö      # Convert both from base-1 to base-10 to sum its digits
                 #  STACK: [1,4]
           Â     # Bifurcate it again
                 #  STACK: [1,4],[4,1]
            `    # Pop the copy and push both integers separated to the stack
                 #  STACK: [1,4],4,1
             @   # Check if the first >= the second
                 #  STACK: [1,4],1
              i  # If this is truthy (1):
               θ #  Pop and leave the last value of the pair
                 #   STACK: 4
                 #  (after which it is output implicitly as result)
                 # (implicit else)
                 #  (the implicit input is output implicitly as result)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•Q¡ĀŠL›š»•` is `1867012004107141926` and `•Q¡ĀŠL›š»•₃в` is `[2,91,40,9,81,5,4,27,0,1]`.
> 4 votes

# Answer
# APL+WIN, 50 bytes

Prompts for first integer then second. index origin = 0

```
(((+/-/m)*.5)*2)++/</m←⌽(7⍴2)⊤⎕av⍳'wì][:koR{'[⎕,⎕]

(+/-/m)*.5 Takes square root of difference between matches to throw an error if negative.

```
> 3 votes

# Answer
# Charcoal, 45 bytes

```
Ｆ²⊞υ§⪪”)∧|XＣ¬πＸt？×”⁷ＮＵＭυΣ⭆ι⁻λ§§υ¬κμ⎇›⊟υΣυωＩ⊟υ

```

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

```
Ｆ²⊞υ§⪪”)∧|XＣ¬πＸt？×”⁷Ｎ

```

Input the two digits and extract their bit patterns for the seven segment display from the compressed string.

```
ＵＭυΣ⭆ι⁻λ§§υ¬κμ

```

Count how many segments are superfluous for each digit relative to the other. (Conveniently this still works even though I'm using string "arithmetic".)

```
⎇›⊟υΣυωＩ⊟υ

```

If the first digit has at least as many superfluous segments as the second then output that number.
> 2 votes

# Answer
# Husk, 42 bytes

```
?_1ṁ>0₂¹³>0Σ₂
¤z-!m(↑_7*2ḋ+3c)"];yfZ\\a|zt

```

Try it online!

This feels frustratingly long, principally because of my contorted way to construct the matrix of outputs (below), so can probably be golfed better.

We use a 7x10 matrix of `0`s & `1`s to represent the absence/presence of a matchstick at each of the 7 positions in each of 10 digits.
Husk doesn't have built-in compression for integers or arrays, but a 7-bit row can be conveniently encoded by the (8-bit) codepoint of one character, and converted using `ḋc` (binary digits of codepoints).
**But** the straightforward string representation of the rows is `"w`>|i]_d\177}"`, which includes characters not present in Husk's codepage. Only by subtracting 3 from each value do we arrive at a string - `"t];yfZ\\a|z"` in which all characters are present in Husk's 256-character codepage. We then move the zero row (`t`) to the end, to account for Husk's 1-based indexing. So now we've got `ḋ+3c` to decode.
**But now** when we try to access this as a matrix, the row for the digit `2` \- corresponding to bits `0,1,1,1,1,1,0` fails, because the binary representation starts with a zero, and Husk drops the leading zero. Luckily it ends with a zero too, so we can work-around by doubling every row and taking the last 7 elements. So now we've got `↑_7*2ḋ+3c`, which additionally needs parentheses now because it's too many functions to combine using any of Husk's multi-function combinators. So `(↑_7*2ḋ+3c)`.
Frustratingly long.

After that, we just zip-subtract the relevant rows from each other: `¤z-!`, check whether the sum is less than zero, and if it is, return `-1`: `?_1`...`>0Σ₂`, otherwise return the number of subracted elements that are greater than one `ṁ>0₂¹³`.
> 2 votes

# Answer
# Pyth, 41 Bytes

```
K"wD>nMk{Fo"Lsjb2M|<yGyHy.&G_hHg.*mC@KdQ

```

Takes something like `[2, 3]` as input, and prints `True` as error value.

Try it online!

# Explanation

```
                                                Q=eval(input())
K"wD>nMk{Fo"                                   K="wD>nMk{Fo"
             L                                  y=lambda b:
              s                                  sum(
               jb2                                base(b,2))
                  M                             g=lambda G,H:
                     yG                           y(G)
                    <                             <
                       yH                         y(H)
                   |                             or
                         y                        y(
                            G                      G
                          .&                       &
                             _hH                   ~H)
                                g               g(
                                 .*              *
                                   mC@Kd         [(lambda d:ord(K[d]))(i) for i in
                                        Q        Q])

```
> 1 votes

---
Tags: code-golf
---


# Question
Title: N numbers closest to zero staying balanced
**Objective**: Given a positive integer `n`:

* If `n` is odd, output the list of `n` numbers closest to `0` in increasing order
* If `n` is even, output a Falsey value.

**Test cases**:

```
5 -> [-2,-1,0,1,2]
4 -> false (or any Falsey value)
1 -> [0]

```

---

## Reference implementation

```
function update(){
  var num = +document.getElementById("yield").value;
  if(num){
    var out = document.getElementById("output");
    if(num % 2 == 1){
      // base is balanced
      var baseArr = [];
      for(var i=0;i<num;i++){
        baseArr.push(i-Math.floor(num/2));
      }
      out.innerHTML = baseArr.join(" ");
    } else {
      out.innerHTML = "false";
    }
  } else {
    out.innerHTML = "<i>enter input</i>";
  }
}

setInterval(update,1);
```

```
* {
  font-family: "Constantia", "Consolas", monospace;
}

[type="number"] {
  width: 10px;
  width: 2em;
}

#output {
  font-family: "Consolas", monospace;
}
```

```
Input: <input type="number" id="yield" value="3"> is <span id="output"><i>enter input</i></span>
```

# Answer
> 6 votes
# Pyth, 10 bytes

```
*-R/Q2Q%Q2

```

Try it online.

### How it works

```
            (implicit) Store the input in Q.
   /Q2      Calculate Q/2 (integer division).
 -R   Q     Subtract that value (-R) from each element in [0, ..., Q-1] (Q).
*      %Q2  Repeat the resulting array Q%2 times.

```

# Answer
> 5 votes
# Mathematica, ~~32~~ ~~30~~ 24 bytes

```
OddQ@#&&Range@#-(#+1)/2&

```

Code-golfing trick: The last argument to `And` doesn't have to be a boolean.

# Answer
> 5 votes
## APL, ~~16~~ ~~15~~ 13 bytes

Thanks to @Dennis for -2 bytes!

```
⌊(⍳⊢×2|⊢)-÷∘2

```

This is a monadic train that gives an empty array for even input. Below is the diagram:

```
┌────┴─────┐
⌊ ┌────────┼─┐
┌─┴─┐      - ∘
⍳ ┌─┼───┐   ┌┴┐
  ⊢ × ┌─┼─┐ ÷ 2
      2 | ⊢

```

First, `⊢×2|⊢` gives the input times its mod 2; that is, odds will give themselves, and evens give 0. We use  to create a list of numbers from 1 to that (`⍳0` gives the empty array), and then we subtract half the input and floor.

# Answer
> 5 votes
# Brachylog, 9 bytes

```
%₂1&~l≠≜o

```

Try it online!

### Explanation

An interesting (ab)use of Brachylog's backtracking algorithm:

```
%₂1        First, assert that the input mod 2 is 1 (if not, the predicate fails)
   &       Then, the input
    ~l      is the length of some list
      ≠     in which all elements are different
       ≜   Generate a list that matches those conditions
           Brachylog will try to fill the array with integers, starting from 0 and
            increasing in absolute value; since they all have to be different, the result
            will be of the form [0, 1, -1, 2, -2, ...]
        o  Sort ascending

```

# Answer
> 4 votes
## Haskell, ~~37~~ ~~36~~ 31 bytes

```
g n=take(n*mod n 2)[-div n 2..]

```

Unbalanced is indicated by the empty list. Usage example: `g 7` -\> `[-3,-2,-1,0,1,2,3]`.

@xnor found 5 bytes. Thanks!

# Answer
> 4 votes
# JavaScript (ES6), ~~44~~ ~~43~~ ~~42~~ 41 bytes

crossed out 44 is still regular 44 ;(

```
n=>[...Array(n&1&&n--)].map((x,i)=>i-n/2)

```

For odd inputs, returns a integer array of length `x`, centered at `0`; for even, returns 0. I think this is as short as it can get. (Saved a couple bytes thanks to @edc65 and @ןnɟuɐɯɹɐןoɯ!)

ES6 alternative: (42 bytes, thanks to @intrepidcoder)

```
x=>x%2&&[for(y of Array(x--).keys())y-x/2]

```

Suggestions welcome!

# Answer
> 4 votes
## PowerShell, ~~50~~ 52 Bytes

```
param($a)$b=$a/2-.5;(0,((0-$b)..$b-join' '))[($a%2)]

```

Oof. Pretty verbose answer. Takes input `$a`, then sets a new variable `$b` as the "floor" of `$a/2`. Generates a new number range from `(0-$b)` to `$b`, then `join`s the range with spaces, and has that as the second element of a two-element array (the first element is `0`). Then uses `$a%2` to index into that array for output.

Alternate version using more "traditional" if/else flow, at 54 bytes:

```
param($a)$b=$a/2-.5;if($a%2){(0-$b)..$b-join' ';exit}0

```

Edit - Needed to add some logic to output a falsey value if the input is even

# Answer
> 4 votes
# J, 12 bytes

```
i:@%~2&!*2&|

```

This is a monadic verb that returns `0` (falsy) for even numbers. Try it online with J.js.

### Test run

```
   (i:@%~2&!*2&|) 3
_1 0 1
   (i:@%~2&!*2&|) 2
0

```

### How it works

```
              Right argument: y
         2&|  Take y modulo 2.
     2&!      Calculate y C 2 = y(y-1)/2.
        *     Multiply the results.
   %~         Divide the product by y.
              This yields (y-1)*(y%2)/2 = (y-1)/2 (y even) | 0 (y odd).
  @           Take the result and...
i:              apply the bilateral index generator z -> (-z ... z).

```

# Answer
> 3 votes
# Python 2, ~~34~~ 32 Bytes

Right now I'm not sure if I can output whatever I want if it's not balanced, so currently this just returns an empty list in the case of an unbalance-able base. It's an anonymous lambda function, so give it a name to use it.

```
lambda k:k%2*range(-k/2+1,-~k/2)

```

# Answer
> 3 votes
## Minkolang 0.10, 18 bytes

```
nd2%?.d2:~r[dN1+].

```

### Explanation

```
n          Take input as integer (k)
d2%?.      Duplicate k and stop if it's even
d2:~       Duplicate k, then divide by 2 and negate to get first number
r          Put k on top
[    ].    Loop k times and then stop
 dN1+      Duplicate, output as integer, and increment

```

# Answer
> 3 votes
# DUP, 31 bytes

```
[a:a;2/b:[b;_[$b;<][$1+]#][0]?]

```

`Try it here.`

Anonymous lambda. Usage:

```
5[a:a;2/b:[b;_[$b;<][$1+]#][0]?]!

```

# Explanation

```
[                             ] {lambda}
 a:                             {store input to a}
   a;2/                         {divmod a by 2}
       b:                       {store quotient to b, top of stack is now remainder}
         [               ][ ]?  {conditional}
          b;_                   {if remainder is 1, get b and negate it}
             [    ][   ]#         {while loop}
              $b;<                {while top of stack is less than b}
                    $1+           {duplicate and increment}
                           0    {otherwise, leave falsy value}

```

# Answer
> 3 votes
# Vyxal, 8 bytes

```
∷$½:N$ṡ∧

```

Try it Online!

## Explanation

```
∷$½:N$ṡ∧
∷          Parity
 $         Swap (putting the input on top again)
  ½        Half
   :       Duplicate
    N      Negate
     $     Swap
      ṡ    Range from a to b
       ∧   Logical AND

```

# Answer
> 2 votes
# CJam, ~~13~~ 12 bytes

```
{_2md@,@f-*}

```

This is an anonymous function that pops an integer from the stack and pushes a digit array (odd base) or an empty array (even base) in return. Try it online in the CJam interpreter.

### How it works

```
_          e# Copy the input (N).
 2md       e# Push N/2 and N%2.
    @      e# Rotate N on top of the stack.
     ,     e# Push [0 ... N-1].
      @    e# Rotate N/2 on top of the stack.
       f-  e# Subtract N/2 from each element of [0 ... N-1].
         * e# Repeat the resulting array N%2 times.

```

# Answer
> 2 votes
# Japt, ~~21~~ 19 bytes

**Japt** is a shortened version of **Ja**vaScri**pt**.

```
U%2&&(X=-U/2+K o1-X

```

For odd inputs, returns a integer array of length `x`, centered at `0`; for even, returns 0. Rough JS translation:

```
output(U%2&&(X=-U/2+.5).range(1-X));

```

where `x.range(y)` creates a list of integers from `x` to `y`. Test it online!

---

In modern Japt, this is only 11 bytes:

```
u ©Uo-U/2-½

```

Try it online!

# Answer
> 2 votes
# O, 18

```
M(.e\2/.@{_}dmrr]p

```

Live demo.

# Answer
> 2 votes
# Vitsy, ~~27~~ 25 Bytes

I'm gonna golf this down tomorrow, but I really ought to go to bed now.

```
D2M)[&1]D1-i*}\[D2/NaO2+]
D                             Duplicate the input.
 2M)[&1]                      If the input is even (input%2=0) generate a new stack
                              and push 1 to it.
        D                     Duplicate the top value - if it wasn't even, this will be the input. Otherwise, it's one.
         1-                   Subtract one (to balance around zero)
           i*                 Additively invert
             }                Shift over an item in the stack - this ensures that
                              we have either the input or one on top.
              \[        ]     Repeat input times.
                D2/N          Duplicate the top item and print it out.
                    aO        Newline (I'm pretty sure this is valid separation)
                      2+      Add one to the top item of the stack.

```

# Answer
> 2 votes
# TeaScript, 16 bytes ~~18~~

```
x%2Þr(xØ)ßl-x/2)

```

Pretty simple. The special characters are actually just "abbreviations" for longer code sequences.

I still haven't made permalinks so you'll have to copy paste into the interpreter

### Explanation

```
x%2 &&    // If x is NOT even return falsy, else...
r(x--)    // Range 0-input. Subtracts one from input
m(#       // Loop through range
  l-      // Current item in loop, minus...
    x/2   // input - 1, divided by two
)

```

This answer is non-competing

# Answer
> 2 votes
## R, 30 bytes

```
function(n)(x=(1-n)/2*n%%2):-x

```

Roughly, `x:-x` returns the integers from `x` to `-x`, where I set `x` to `(1-n)/2`. I also use the modulo-2 factor `n%%2` in the definition of `x` to force `x` to zero when `n` is even, in which case, `0:0` returns `0` (falsey).

# Answer
> 2 votes
# , 21 chars / 37 bytes

```
ô[…Ѧ(ï&1⅋ï‡)]ć⇀_-ï/2⸩

```

`Try it here (Firefox only).`

Here's a 20-char / 35-byte answer (non-competing, since the answer uses changes implemented after the question was asked):

```
ô(ï%2⅋ѨĶ(ï‡)ć⇀$-ï/2⸩

```

`Try it here (Firefox only).`

# Answer
> 2 votes
# F#, 38 bytes

The falsey result is an empty list.

```
let O n=if n%2<1 then[]else[-n/2..n/2]

```

# Answer
> 2 votes
# MathGolf, 6 (or 4?) bytes

```
½k¥¿╤<

```

Outputs `0` as falsey output.

Try it online.

If we're allowed to output `[0]` as falsey output, even though \\$n=1\\$ results in `[0]` as truthy output as well, this could be **4 bytes** instead:

```
¥*½╤

```

Try it online.

**Explanation:**

```
½       # Integer-divide the (implicit) input-integer by 2
 k      # Push the input-integer again
  ¥     # Modulo-2
   ¿    # If input%2 is truthy / 1 / odd:
    ╤   #  Pop the input//2 and push a list in the range [-input//2, input//2]
        # Else (it's falsey / 0 / even instead):
     <  #  Check if the (implicit) input is smaller than input//2, which is falsey / 0
        # (after which the entire stack joined together is output implicitly as result)

¥       # Modulo-2 on the (implicit) input-integer (1 if odd; 0 if even)
 *      # Multiply that by the (implicit) input-integer
  ½     # Integer-divide it by 2
   ╤    # Pop and push a list in the range [-(input%2*input//2), input%2*input//2]
        # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 2 votes
# , 26 bytes

```
a=scan();-(i=a%/%2*a%%2):i

```

Try it online!

Integer-divide input by 2, and multiply by input modulo 2 (so it becomes zero if input is even). Then output the range of integers from negative to positive of this value.

(for a fairer comparison with the previous (half-decade-old!)  answer, the approach here would be 28 bytes as a function).

# Answer
> 2 votes
# Python 3.8 (pre-release), 37 bytes

```
lambda x:x%2*[*range(-x//2+1,x//2+1)]

```

Try it online!

# Answer
> 1 votes
# Perl, 36 bytes

I have a feeling this can be shortened:

```
$,=$";$n=<>;print$n%2?-$n/2..$n/2:0;

```

Range treats floats as integers, so, e.g. 5/2 = 2.5 gets silently converted to 2.

(If formatting doesn't matter, then remove `$,=$";` for a total of 30 bytes).

# Answer
> 1 votes
## Powershell, 49 bytes

```
param($a)$b=$a/2-.5;"[$(-$b..$b-join",")]"*($a%2)

```

Even numbers evaluated to `$false` since they provide an empty line output.

```
("[$(-$b..$b-join",")]"*($a%2))-eq $True ===> False

```

Odd numbers output the exact reference string. You can save 4 more bytes (now `45`) by removing the `[]` from the output string.

```
PS> .\balanced.ps1 4

PS> .\balanced.ps1 5
[-2,-1,0,1,2]

PS> .\balanced.ps1 0

PS> .\balanced.ps1 1
[0]

PS>

```

## Powershell, 36 Bytes

```
param($a)$b=$a/2-.5;(-$b..$b)*($a%2)

```

This has the same falsey result but outputs the list of numbers separated by newlines:

```
PS> .\balanced-newline.ps1 4

PS> .\balanced-newline.ps1 1
0

PS> .\balanced-newline.ps1 5
-2
-1
0
1
2

PS>

```

# Answer
> 1 votes
# Perl 6, 25 bytes

The shortest lambda expression I could come up with that outputs a list rather than a range is:

```
{$_%2&&|((1-$_)/2..$_/2)} # 25

```

Testing:

```
for 0..10 -> $a {
  if {$_%2&&|((1-$_)/2..$_/2)}($a) -> $b {
    say "$a.fmt('%5s')  $b"
  } else {
    say "$a.fmt('%5s')  False"
  }
}

```

```
    0  False
    1  0
    2  False
    3  -1 0 1
    4  False
    5  -2 -1 0 1 2
    6  False
    7  -3 -2 -1 0 1 2 3
    8  False
    9  -4 -3 -2 -1 0 1 2 3 4
   10  False

```

This takes advantage of the fact that Perl 6 treats the number `0` as a false value. If the output had to be exactly `False` you could replace `$_%2` with `$_!%%2`.

# Answer
> 1 votes
# 05AB1E, 8 bytes

Code:

```
È#¹;D(ŸR

```

Try it online!

Explanation:

```
È#        # If input % 2 == 0, end the program
  ¹       # Push the first input from the register
   ;      # Halve, push input / 2 rounded down
    D     # Duplicate top of the stack
     (    # Negate
      Ÿ   # Inclusive range, pushes [a .. b]
       R  # Reverse the array

```

Uses **CP-1252** encoding.

# Answer
> 1 votes
# Jelly, 6 5 bytes

```
HŒRxḂ

```

Try it online!

## Explanation

```
HŒRxḂ   Main monadic link
H       Halve
 ŒR     Balanced range
   x    Repeat
    Ḃ    parity of n

```

*-1 byte by finding out there's almost a builtin for this*

# Answer
> 1 votes
# Risky, 10 bytes

```
0?+0*:?\2__?+0-_?/2

```

Try it online!

## Explanation

```
0     range
?         input
+       +
0         0
*   repeat
:     0 ≠
?         input
\       mod
2         2
_ map
_
?         item
+       +
0         0
-   -
_
?         input
/       /
2         2

```

# Answer
> 0 votes
# Java, 145 bytes

```
public class c{static void c(int n){for(int i=n/2*-1;i<=n/2;i++){if(n%2==0){System.out.print("false");break;}System.out.print(i);}}}

```

Explanation: Sorry, I know this is really long. I didn't see an answer for java so I decided to put one in. Let me know if I need to write the main function (Im not sure if thats the policy or not). Basically it divides the number by two and multiplies it by -1 for the lower bound and for the upper bound it just uses the number divided by two. I'm kind of new to this page so if I didn't format anything right then let me know. Also, I know that answers can be shortened with lambda functions but I don't know how to use them and Im not sure if Java supports them.

Here is a more readable version which is less golfed:

```
public class StackOverflow {
static void c(int n){
    for (int i = n/2*-1; i<=n/2; i++){
        if(n%2==0){
            System.out.print("false");
            break;
        }
        System.out.print(" " + i);
    }
}
}

```

# Answer
> 0 votes
# PHP, 50 bytes

```
<?=($n=$argv[1])&1?join(_,range(-$k=$n/2|0,$k)):0;

```

program, takes input from STDIN, prints `_` delimited list or `0`.

or

```
function f($n){return$n&1?range(-$k=$n/2|0,$k):0;}

```

function takes argument, returns array or `0`.

# Answer
> 0 votes
# Ruby, 27 bytes

```
->n{[*0-n/2..n/2]if n.odd?}

```

Creates an anonymous lambda function that will return the array of `n` numbers closest to 0 if n is odd, and returns nil (a falsey value in ruby) otherwise.

Ruby rounds its integer division towards -infinity, but `0-n/2` is shorter than `-n/2+1` (since the minus sign is there anyway), and because n is now considered positive, the rounding works in my favour.

### Old Version (28 bytes)

```
->n{[*-n/2+1..n/2]if n.odd?}

```

# Answer
> 0 votes
## Ruby, 25 bytes

```
->n{n%2>0&&[*(-n/=2)..n]}

```

# Answer
> 0 votes
# Japt, 8 bytes

Outputs `0` for even inputs.

```
u ©Uo-Uz

```

Try it

```
u ©Uo-Uz     :Implicit input of integer U
u            :Modulo 2
  ©          :Logical AND with
   Uo        :Range [0,U)
     -       :From each subtract
      Uz     :U floor divided by 2

```

# Answer
> 0 votes
# GolfScript, 15 bytes

```
~:&,{&2/-}%&2%*

```

Try it online!

```
~:&               # Assign n to &                    5                  4
   ,              # Make an array from 0 to n-1      [0 1 2 3 4]        [0 1 2 3]
    {    }%       # For every element in the array
     &2/-         # Subtract n/2                     [-2 -1 0 1 2]      [-2 -1 0 1]
           &2%*   # Multiply the array by n%2        [-2 -1 0 1 2]      []

```

# Answer
> 0 votes
# Nibbles, 5 bytes (10 nibbles)

```
^`%$~.`,@-

```

## Verbose version

```
^   # Repeat
  `% $ ~   # (input mod 2) times; save the value of input div 2
  .   # Map
    `, @   # Range from 0 to (input - 1)
    -   # argument - saved value

```

# Answer
> 0 votes
# JavaScript (Node.js), 41 bytes

```
f=(n,y=~n/2)=>y%1+!n?'':[++y,...f(n-1,y)]

```

Try it online!

Output empty string as false

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


title: Triangle of triangles

text:
# Question
Title: Triangle of triangles
Given an integer \\$n \geq 2\\$, print a triangle of height \\$n\\$ of (triangles of height \\$n\\$ of asterisks), as in this SO question.

For \\$n=2\\$, print:

```
    *
   ***
 *  *  *
*********

```

For \\$n=3\\$, print:

```
            *
           ***
          *****
       *    *    *
      ***  ***  ***
     ***************
  *    *    *    *    *
 ***  ***  ***  ***  ***
*************************

```

For \\$n=4\\$, print:

```
                        *
                       ***
                      *****
                     *******
                 *      *      *
                ***    ***    ***
               *****  *****  *****
              *********************
          *      *      *      *      *
         ***    ***    ***    ***    ***
        *****  *****  *****  *****  *****
       ***********************************
   *      *      *      *      *      *      *
  ***    ***    ***    ***    ***    ***    ***
 *****  *****  *****  *****  *****  *****  *****
*************************************************

```

And so on. Some rules:

* I write "print", but a function returning a string or list of lines is fine too.
* Trailing whitespace on each line is allowed, but not leading whitespace.
* Trailing blank lines are allowed.
* This is : write the shortest program you can, measured in bytes.

# Answer
# Python 3 with numpy, ~~79~~ 74 bytes

```
lambda n:where(kron(*[c_[:n]>=abs(r_[1-n:n])]*2),*'* ')
from numpy import*

```

Try it online!

-5 thanks to ovs, with the use of `where`.

Step-by-step example of how it works:

```
>>> from numpy import*
>>> (n:=2)
2
>>> (Y:=c_[:n])
array([[0],
       [1]])
>>> (X:=r_[1-n:n])
array([-1,  0,  1])
>>> (Z:=Y>=abs(X))    # Broadcasts.
array([[False,  True, False],
       [ True,  True,  True]])
>>> (A:=kron(*[Z]*2))    # Listify, double, and unpack to give the same argument twice.
array([[False, False, False, False,  True, False, False, False, False],
       [False, False, False,  True,  True,  True, False, False, False],
       [False,  True, False, False,  True, False, False,  True, False],
       [ True,  True,  True,  True,  True,  True,  True,  True,  True]])
>>> (B:=where(A,*"* "))    # Select asterisk for true and space for false.
array([[' ', ' ', ' ', ' ', '*', ' ', ' ', ' ', ' '],
       [' ', ' ', ' ', '*', '*', '*', ' ', ' ', ' '],
       [' ', '*', ' ', ' ', '*', ' ', ' ', '*', ' '],
       ['*', '*', '*', '*', '*', '*', '*', '*', '*']], dtype='<U1')

```
> 12 votes

# Answer
# MATL, ~~29~~ ~~16~~ 15 bytes

```
ZvG:!<~PtX*42*c

```

**Try it online!**

### How it works

Consider input `3` as an example. The stack is shown upside down, with the most recent element below.

```
Zv    % Implicit input. Symmetric range
      % STACK: [1 2 3 2 1]
G:    % Push input again. Range
      % STACK: [1 2 3 2 1],
               [1 2 3]
!     % Transpose
      % STACK: [1 2 3 2 1],
               [1
                2
                3]
<~    % Less than?, negate; element-wise with broadcast
      % STACK: [1 1 1 1 1
                0 1 1 1 0
                0 0 1 0 0]
P     % Flip vertically
      % STACK: [0 0 1 0 0
                0 1 1 1 0
                1 1 1 1 1]
tX*   % Duplicate. Kronecker product
      % STACK: [0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
                0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0
                0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
                0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0
                0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0
                0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0
                0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0
                0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0
                1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
42*   % Multiply by 42 (ASCII for '*'). Convert to char
      % Implicit display. Char 0 is displayed as space
      % STACK: ['            *            '
                '           ***           '
                '          *****          '
                '       *    *    *       '
                '      ***  ***  ***      '
                '     ***************     '
                '  *    *    *    *    *  '
                ' ***  ***  ***  ***  *** '
                '*************************']

```
> 8 votes

# Answer
# , 37 31 bytes

```
' *'{~[:,./^:2[:*/~i.>:/|@i:@<:

```

Try it online!

*-6 after seeing the phrase "Kronecker product" in m90's python answer, realizing that's what I was doing, and finding a golfier implementation in this essay.*
> 8 votes

# Answer
# Python 3.8, ~~91~~ ~~86~~ 84 bytes

-2 bytes thanks to Lynn!

```
lambda n:[f"{(o%n*'**'+'*').center(w:=2*n-1)*(o//n*2+1):^{w*w}}"for o in range(n*n)]

```

Try it online!
> 5 votes

# Answer
# C (gcc), ~~160~~ ~~153~~ 148 bytes

```
p(c,n){n&&p(putchar(c),n-1);}r;t;l;i;f(n){for(r=0;r<n*n;p(10,1))for(t=r/n,l=r++%n,p(32,(n+~t)*(n*2-1)),i=t-~t;i--;p(32,n+~l))p(32,n+~l),p(42,l-~l);}

```

Try it online!

*Saved 7 bytes thanks to ceilingcat!!!*
> 5 votes

# Answer
# C (gcc), 107 bytes

```
m,x,y;f(n){for(y=n*n;y--;)for(x*=x=m=2*n-1;x--;)putchar(abs(x%m-n+1)+y%n<n&abs(x/m-n+1)+y/n<n?42:x?32:10);}

```

Try it online!

-1 byte by ceilingcat
> 5 votes

# Answer
# Charcoal, 25 bytes

```
ＮθＦθＦ⊕⊗ι«Ｊ×⊖⊗θ⁻κι×θιＧ↗↘θ*

```

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

```
Ｎθ

```

Input `n`.

```
Ｆθ

```

Loop over each row.

```
Ｆ⊕⊗ι«

```

Loop over each of the `2i+1` triangles in each row.

```
Ｊ×⊖⊗θ⁻κι×θι

```

Jump to the (bottom left of the) triangle.

```
Ｇ↗↘θ*

```

Draw the triangle.

24 bytes if a leading blank line is allowed:

```
ＮθＦθ«Ｍ×⊖⊗θ⊗ιθＦ⊕⊗ι«Ｇ↖↙θ*←

```

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

```
Ｎθ

```

Input `n`.

```
Ｆθ«

```

Loop over each row.

```
Ｍ×⊖⊗θ⊗ιθ

```

Jump to the end of the row.

```
Ｆ⊕⊗ι«

```

Loop over each of the `2i+1` triangles in each row.

```
Ｇ↖↙θ*

```

Draw the triangle.

Move to the next triangle.
> 4 votes

# Answer
# Ruby, 76 bytes

```
->n{(0...n*n).map{|i|((?**(i%n*2+1)).center(j=n*2-1)*(i/n*2+1)).center j*j}}

```

Try it online!
> 4 votes

# Answer
# Ruby, ~~82~~ 74 bytes

```
->n{(r=1.step n+=n-1,2).map{|x|r.map{|y|((?**y).center(n)*x).center n*n}}}

```

Try it online!

Good golfers copy, great golfers steal.
> 3 votes

# Answer
# Vyxal `j`, 25 bytes

```
d‹£²ʁƛ?%›‛***Ḣ¥⋏n?ḭd›*¥²⋏

```

Try it Online!

I think mirroring might help, but cannot think of how
> 2 votes

# Answer
# Japt, ~~18 17~~ 16 bytes

```
ÇÑÄ
ïÈçYçÑ ûUÌÃû

```

Try it

```
o_ÑÄ         - range [0..input] *2+1
ï          - pair each with itself
 È         - then pass pairs by f(X,Y)
  ç        - repeat result X times
   YçÑ    - repeat '*' Y times
ûNÑÉ       - centre pad
Ãû         - centre pad all

```
> 2 votes

# Answer
# Vyxal `C`, 15 bytes

```
ƛd‹?ɾ×*vømøĊ*;f

```

Try it Online!

```
ƛ            ;  # Map 1...n to...
   ?ɾ           # 1...input...
     ×*         # Asterisks
       vøm      # Each palindromised
          øĊ    # Centered
            *   # Repeated...
 d‹             # (2 * value) - 1 times
              f # Flatten
                # (C flag) output centered

```

17 bytes without the flag by appending a `øĊ`.
> 2 votes

# Answer
# Python 3.8 (pre-release), ~~111~~ 100 bytes

```
f=lambda n,b=['*'],p=1:p>2 and b or f(n,[f'{2*r*l+l:^{(2*n-1)**p}}'for r in range(n)for l in b],p+1)

```

Try it online!

Nowhere near the best Python 3 answers, but it's got recursion. See my answer on the source SO question for an ungolfed version with the same mechanisms.

*-11 bytes thanks to @ovs*
> 2 votes

# Answer
# , 82 bytes

```
function(n)write(c(" ","*")[1+(z=outer(c(n:1,2:n),1:n,"<="))%x%z],1,(2*n-1)^2,,"")

```

Try it online!
> 1 votes

# Answer
# Pip, 39 bytes

```
YPZ0Xa-_.1X_M\,a(J*Z_M_*^yMMy)TRt"* "Jn

```

Replit! Or, here's a 41-byte equivalent in Pip Classic: Try it online!

### Explanation

We create a structure out of 0's and 1's and then use it for both the micro- and macro-structure of the desired output.

```
YPZ0Xa-_.1X_M\,a
               a  First command-line argument
             \,   Inclusive range from 1 to that number
            M     To each element of that range, map this function:
     a-_           a minus the function argument
   0X              That many 0's
           _       Function argument
         1X        That many 1's
        .          Concatenate those two strings
 PZ                Palindromize
Y                 Yank the resulting list of strings into the y variable

```

For example, with an input of 3, `y` is `[00100; 01110; 11111]`.

```
(J*Z_M_*^yMMy)TRt"* "Jn
          MMy            Map this function to each character of each string in y:
         y                Take another copy of y
        ^                 Split it into a list of lists of characters
      _*                  Multiply each character by the function argument
     M                   To each sublist of the resulting list, map this function:
   Z_                     Transpose
 J*                       Join each sublist of the transposition into a single string
(            )TR         Transliterate the result:
                t         Replace characters "10"
                 "* "     with characters "* "
                     Jn  Join on newlines

```
> 1 votes

# Answer
# Julia 1.0, 68 bytes

```
~n=2n-1
!n=[' '^(2n^2-j*~n-i)*rpad('*'^~i,~n)^~j for i=1:n,j=1:n][:]

```

Try it online!

I wish Julia had a `center` function

output is a list of lines
> 1 votes

# Answer
# Kotlin, 186 bytes

```
val p={n:Int->for(p in n downTo 1)for(l in n downTo 1)for(g in n-1 downTo 1-n)for(c in n-1 downTo 1-n)print(when{p+Math.abs(g)<=n&&l+Math.abs(c)<=n->'*'
g!=1-n||c!=1-n->' '
else->'\n'})}

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 19 bytes

```
·ÅÉεIL'*×.Bí€û×}˜.c

```

Try it online or verify all test cases.

**Explanation:**

```
·                # Double the (implicit) input-integer
 ÅÉ              # Push a list of all odd numbers smaller than or equal to this 2*input
   ε             # Map over each odd integer:
    IL           #  Push a list in the range [1,input] again
      '*×       '#  Repeat "*" each integer amount of times as string
         .B      #  Box this list of strings, adding trailing spaces to make them all of
                 #  equal length
           í     #  Reverse each so the spaces are leading
            €û   #  Palindromize each string
              ×  #  Repeat each the current odd integer amount of times
   }˜            # After the map: flatten the list of lists
     .c          # Join this list of strings by newlines, and centralize it
                 # (after which it is output implicitly as result)

```
> 0 votes

# Answer
# 05AB1E, 16 bytes

```
L'*×j.ºиøā·<×˜.C

```

Try it online!

```
L                -- range from 1 to n
 '*×             -- repeat "*" that many times
    j            -- pad to length n with spaces to the left
     .º          -- self-intersected mirror
       и         -- for each string, make a list of n copies
        ø        -- transpose to get the rows of the big triangle
         ā       -- get the range from 1 to the number of rows (n)
          ·<     -- double and decrement to get a list of the first n odd numbers
            ×    -- repeat each string in the i-th row 2*i-1 times
             ˜   -- flatten into a list of lines
              .C -- center and join by newlines

```

Try it with step-by-step output!
> 0 votes

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


title: Make a Radiation Hardened Quine

text:
# Question
Title: Make a Radiation Hardened Quine
Your task is to make a quine, that is a non-empty computer program that prints it's own source without reading it. In addition if you remove any one byte from your original program the new program should print the source of your original program.

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

# Answer
> 8 votes
# Gol\>\<\>, ~~49~~ 45 bytes

```
<<H~Kla}\`q%2l}}ss2"<\
<<H~Kla}\`q%2l}}ss2"<\

```

Try it online!

Verification!

I did this in Gol\>\<\> rather than \>\<\> because the former has the handy `K` operator that copies the top `n` items on the stack, which makes duplicating the clean copy of the source code easier.

### Explanation:

This works by having two copies of the executing code, and redirecting to the second one if the first is damaged. This fails when the last `\` or the middle newline is removed, both of which are compensated for later.

```
<<                       Redirect left
                    <\  Switch to other source code if this line is irradiated
                   "     Push source with wrapping string literal
                ss2      Push quote
              }}         Move "< to end
          q%2l           If the length of the stack is not right
        \`               Push an extra \
       }                 Move the \ to the end
      a                  Newline
    Kl                   Duplicate the stack
   ~                     Pop the extra newline
  H                      Halt and print stack

```

# Answer
> 3 votes
# Vyxal `D`, ~~73~~ 51 bytes

```
`#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`Ṙ:₂ßĖ#`
`#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`Ṙ:₂ßĖ#`

```

Try it Online!

```
`#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`        # push this string to the stack
                  Ṙ:      # reverse the string and push a copy
                    ₂ßĖ   # execute the top if the length is even

# EXECUTION at this point the stack is [ qṘ:7ẎṘ+…,QṘ:₂ßĖ# ]

               Ṙq         # quote and revert => [ `#Ėß₂:ṘQ,…+ṘẎ7:Ṙq` ]
            Ẏ7:           # get the 7 first char => [ `#Ėß₂:ṘQ,…+ṘẎ7:Ṙq` , `#Ėß₂:Ṙ ]
          +Ṙ              # revert and add => [`#Ėß₂:ṘQ,…+ṘẎ7:Ṙq`Ṙ:₂ßĖ#`]
       Q,…                # print, reprint and quit
 #Ėß₂:Ṙ                   # does nothing since the program ended

# END OF EXECUTION

                       #` # comment

```

When any char of the string is removed `₂ß` prevents the execution

* if a ```` is removed, no code of the line will execute because the line will be either comented, either one single string either a mix of both and no execute fire
* if  is removed, the code will execute normally (as the deletion is not in the string)
* if any of `Ṙ:ßĖ` is removed, the code will be either equal to `0`, `1`, a commented code or there will be no execution. This has no incidence and the code will executein the second line

In any case the first execute will either have the string untouched or a string without incidence, in wich case, the second execute will have the string untouched.

The program ends at the first sucessful execute since there is a quit instruction in the string

# Answer
> 2 votes
# Klein 000, ~~196~~ ~~190~~ ~~176~~ ~~144~~ 138 bytes

```
<<+55.?.?.?(48*2+56*2*59*!(2+)?!@!?)+2(!*95*2*65+2*84(?.?.?.55+<<"</
<<+55.?.?.?(48*2+56*2*59*!(2+)?!@!?)+2(!*95*2*65+2*84(?.?.?.55+<<"</

```

Try it online!

---
Tags: code-golf, quine, radiation-hardening
---


title: Verifying a horizontal ASCII pet snake

text:
# Question
Title: Verifying a horizontal ASCII pet snake
Recently there have been a couple of ASCII pet snake challenges (e.g. here)

```
            0 0
  0        0 0 000
00 0     00       000 0      0
    000 0            0 0   00
       0                000

```

This challenge is to take a randomly generated horizontal pet snake (height of five lines, length of 30), and verify that :

* Each column has only one `0`
* Each `0` is "connected" to the `0` before and after it (vertically spaced by 0 or 1 line only)

Final output can be `true` or `1` if the snake is valid, or `false` or `0` if the snake is invalid

## Edit—Clarification

Assume the input:

* Is a string
* Contains only ' ', '0', and '\n'
* Has exactly 30 characters each line
* Has exactly 5 lines

I.e. verify whether the snake is connected, and that there are no stray chars. No need to validate the "canvas" that the snake is printed on.

# Answer
> 14 votes
# JavaScript (ES2018), ~~62~~ 54 bytes

```
s=>!/0(.{30}|.{60,62}(.{31})*)0|( .{30}){4} /s.test(s)

```

Input is a single string:

* without trailing new line
* contain only space, '0', and '\n'
* 30 characters each line, 5 lines, 154 character in total

Flag `s` means a dot match anything (including '\n'). This feature currently supported by Chrome 63+, Opera 50+, Safari 11.1+, based on compat-table. You may test this function with these supported browser. You will get an exception when loading the page if your browser do not support this feature.

How it works:

* No column with no `0`:
    + do not match `/( .{30}){4} /`
* No two `0`s in one column:
    + do not match `/0.{30}(.{31})*0/`
* No `0` not connect to its neighbors:
    + do not match `/0.{60}(.{31})*0/`, `/0.{62}(.{31})*0/`

Merge all these regex, and you will finally got this one.

```
f =

s=>!/0(.{30}|.{60,62}(.{31})*)0|( .{30}){4} /s.test(s)
```

```
<textarea id=i style="width:100%;height:100px">            0 0
  0        0 0 000
00 0     00       000 0      0
    000 0            0 0   00
       0                000   </textarea>
<button onclick="o.value=f(i.value.slice(0,154))">Validate</button>
Result: <output id=o></output>
```

Thanks to Martin Ender point out that do a single `!` operator may save 8 bytes.

# Answer
> 9 votes
# SnakeEx, 51 bytes

This is obviously the right language for the task. :^D

```
s:({c<L>}{c<R>}0[(<R> <L>)(<L> <R>)_?])%{30}
c:0 *$

```

Matches the entire input if it is a valid snake; fails to match if it's not. Try it here!

### Explanation

SnakeEx is a 2-D pattern matching language. A program consists of a list of definitions for "snakes," which crawl around the input matching characters, changing directions, and spawning other snakes. In our program, we define two snakes, `s` and `c`.

We'll start with `c` because it's simpler. Its definition is `0 *$`, which should be quite readable if you know regex: match `0`, followed by zero or more spaces, followed by the edge of the grid. The main catch here: this matching can proceed in any direction. We're going to use `c` both upward and downward from the snake, to verify that there are no extra `0`s in each column.

Now for the main snake, `s`. It takes the form `(...)%{30}`, which means "match the contents of the parentheses 30 times"--once for each `0` in the snake. So far, so good. What goes inside the parentheses?

```
{c<L>}

```

This spawns a new `c` snake, turned left 90 degrees. The direction is relative to the `s` snake's direction, so the new snake moves toward the top of the grid (the main snake is moving toward the right). The `c` snake checks that the current grid cell is a `0` and that every cell above it is a space. If it fails, the whole match fails. If it succeeds, we continue with

```
{c<R>}

```

which does the same thing, only turned right (toward the bottom of the grid).

Note that these spawns don't affect the position of the match pointer in the main snake. They're a bit like lookaheads in regex. (Maybe here we could call them "lookbesides"?) So after verifying that we're pointing to a `0` and the rest of the column contains only spaces, we need to actually match the `0`:

```
0

```

Now the match pointer is on the character to the right of the `0`. We need to check three different options: the snake angles down, the snake angles up, or the snake goes straight. For this, we can use an OR expression:

```
[...]

```

Inside our OR, we have three possibilities:

```
(<R> <L>)

```

Turn right, match a space, and turn left again (snake angles down).

```
(<L> <R>)

```

Turn left, match a space, and turn right again (snake angles up).

```
_?

```

Match zero or one underscores. Since there are no underscores in the input, this will always be an empty match (snake goes straight).

After matching one of the above three options, the match pointer should be pointing to the `0` in the next column, ready to match the parenthesized expression again.

# Answer
> 3 votes
# Jelly, 16 bytes

```
Zµi€”0IỊ;ċ€⁶=4ƊẠ

```

Try it online!

Assumes that the input string will always only contain only spaces and zeros. Takes input as a list of strings (each representing a line), and outputs **1** if truthy, **0** otherwise.

## Explanation

```
Zµi€”0IỊ;ċ€⁶=4ƊẠ | Monadic full program.
Z                | Transpose.
 µ               | Start a new monadic chain.
  i€”0           | Retrieve the first index of 0 in each column.
      IỊ         | Check whether their increments are insignificant (element-wise).
        ;     Ɗ  | Append the result of the following:
         ċ€⁶     | In each list of characters, count the occurrences of a space.
            =4   | Check whether they equal 4 (returns a boolean array).
               Ạ | All. Check whether all the elements are truthy.

```

# Answer
> 3 votes
# Husk, 12 bytes

Depending on rule clarifications, may be **11 bytes** or **13 bytes**.

```
±Λ=;1Ẋ×≈mηfT

```

Try it online!

Input is a list of lines containing only spaces and 0s; if a single string is required, prepend  to the program to split into lines. The TIO link already does this for clarity. Output is 0 or 1; if any falsy and truthy values are fine, the `±` can be removed.

## Explanation

```
±Λ=;1Ẋ×≈mηfT  Implicit input: a list of lines.
           T  Transpose into list of columns.
        m     For each column,
         ηf   get list of indices of truthy elements.
              In Husk, whitespace characters are falsy and other are truthy,
              so this gets us the indices of 0s on each column.
     Ẋ        For each adjacent pair of these index lists,
      ×       for all pairs drawn from the two lists,
       ≈      give 1 if they differ by at most 1, otherwise 0.
              For each adjacent pair, this produces a list of 1s and 0s.
 Λ            Do all of these lists
  =;1         equal [1]? Return either 0 or 30 (length of the outer list + 1).
±             Signum; convert to 0 or 1.

```

The idea is to use `×≈` to guarantee that (a) all columns contain precisely one 0, and (b) their positions differ by at most one. As an example, consider the 8-column input

```
0  0  0
 000 0
  00   0

```

First, `mηfT` transforms it to the list of index lists

```
[[1],[2],[2,3],[1,2,3],[],[2],[1],[3]]

```

Then `Ẋ×≈` gives

```
[[1],[1,1],[1,1,0,1,1,1],[],[],[1],[0]]

```

Each `1` corresponds to a pair of indices that differ by at most 1, and each `0` corresponds to a pair that doesn't. Each result equals `[1]` precisely when both lists have one index, and the indices differ by at most 1.

# Answer
> 2 votes
# CJam, ~~35~~ 34 bytes

```
{z_{'0e=1=}%:*\'0f#2ew::-[W0X]-!*}

```

Try it online! Input is a rectangular array of arrays of characters. Assumes input only contains  and `0`.

## Explanation:

```
{z_{'0e=1=}%:*\'0f#2ew::-[W0X]-!*}   Function taking a character matrix:
 z                                      Transpose.
   {      }%                            Consider whether each row
      e=                                  contains
        1=                                exactly one
    '0                                    of the character '0'.
            :*                            This must be true for every row.
                  #                     Next, find the position
               '0                         of the character '0'
                 f                        at every row
  _           \                           in the original input.
                       :-               Find the differences between
                      :                   each
                   2                      pair
                    ew                    of adjacent elements (in other words, compute
                                            the increments).
                                        For the snake to be valid, this array of increments
                                            must only contain {0, 1, -1}, so
                              -         Remove from this list
                         [   ]            the elements
                          W                 -1,
                           0                0,
                            X               and 1,
                               !          and then check whether the array is empty.
                                *       The previous code tested two different properties
                                          of the matrix; they both must be true for a
                                          valid snake.

```

# Answer
> 2 votes
# 05AB1E, 18 bytes

```
ζDε0k}¥Ä2‹sεþg}ìPΘ

```

Try it online!

**Explanation**

```
ζ                    # transpose
 D                   # duplicate
  ε  }               # for each row in the first copy (column of input)
   0k                # get the index of the first 0
      ¥Ä             # calculate absolute delta's
        2‹           # check that each is less than 2
          sε  }      # for each row in the second copy (column of input)
            þg       # calculate the length of the string with non-digits removed
               ì     # concatenate the lists
                P    # calculate product
                 Θ   # truthify (turn false values to 0)

```

# Answer
> 2 votes
# C (gcc), ~~246~~ ~~245~~ ~~232~~ ~~215~~ 212 bytes

```
#define F)exit(1);
#define L for(i=l=0;i<30;i++)
#define X b[7][i]
char b[8][31];k,j,l;main(i){for(;j++<5;){gets(b);L{if(i[*b]>47){if(X++F memset(b[j+1]+i-1,l=1,3);}else if(!X&b[j][i]F}k+=!!l;}if(k<5 F L if(!X F}

```

Try it online!

Figured I'd take my favorite language to this (even though as I can see from the many other, smaller entries it's probably far from ideal for this sort of challenge) and C what I could manage. The program's approach to the problem is relatively straightforward, just with a lot of byte penny-pinching; it takes the snake on stdin and gives its result in the return value of main (thus the exit code; ~~as requested in the problem 0 indicates an invalid snake and 1 valid even though for an exit code that's weird~~ as typical for exit codes 0 is a valid snake and 1 is an invalid snake). With the macros expanded and some nice whitespace it looks more like the following:

```
char b[8][31];l,j,k;                           //Declares a buffer to work in, initialized all to 0; l j and k default to int and as globals are init to 0
main(i) {                                      //This is run no-args, so argc is 1 and the undeclared type defaults to int.
  for (; j++ < 5;) {                           //Iterating over each row, 1-indexed for convenience accessing the buffer
    gets(b);                                   //Reads into b[0] because of stack array decl layout
    for (i = l = 0; i < 30; i++) {             //j and l both init each time we begin this overall loop
      if (i[*b] > 47) {                        //Did we read a zero?
        if(b[7][i]++) exit(1);                 //If the snake already had a zero in this column, fail out
        memset(b[j+1] + i-1, l = 1, 3);        //Expect them on the next row in the columns left and right of this one (also set l)
      } else if (!b[7][i] & b[j][i]) exit(1);  //If we didn't read a zero, and we had reason to expect one this row, and there wasn't already a zero in this column, fail out
    }
    k+=!!l;                                    //Adds 1 to k iff l is nonzero
  } if (k < 5) exit(1);                        //If less than 5 rows had zeroes in them, fail out
  for(i = l = 0 ; i < 30; i++) {               //l isn't relevant in this loop but saves some bytes when sharing a macro with the other horizontal loop
    if(!b[7][i]) exit(1);                      //If any columns didn't have zeroes, fail out
  }                                            //Else, snake is valid. main default returns 0.
}

```

Lines of input are read into the first row of the buffer, the next five are for tracking what places are expected to (read: must) have zeroes in the row after each current one, and the last is for tracking whether a zero has already been read in a given column, in any row. The program processes each row in turn.

It's not at all robust (`gets()` is only the beginning) and the input must contain all the relevant spaces (no left-off trailing whitespace for instance), and gcc spews warnings and notes about stdlib functionality left implicitly declared and so on, but, C la vie.

It also assumes that the snake head need not be in the center row, and that a valid snake must have at least one zero in every row (i.e. no rows of all spaces in the 5 input rows). If the latter's not a requirement it can be made a bit shorter - everything to do with `k` and `l` in the program can be pared out or replaced with fewer bytes of code in that case.

Thanks to user202729 for approx. 26 bytes saved.

# Answer
> 2 votes
# Python 2, 71 bytes

```
f=lambda s:s[1]<' 'or'0'in s[::31]in' %s '%s[1::31]in'%6s'%0*2*f(s[1:])

```

Try it online!

Takes input as a multiline string. Tests case from Bubbler.

The first column is extracted as `s[::31]` and the second as `s[1::31]`, and they are checked for validity. We recurse on `s` removing the first character, causing successive pairs of columns to be checked.

The check for two columns uses Python's comparison chaining for `in` combine multiple checks:

* `'0'in s[::31]` checks that the first column has at least one `0`
* `s[::31]in' %s '%s[1::31]` checks that the first column is a substring of the second column sandwiches between two spaces, which ensures the position of the `0` has shifted at most one space
* `' %s '%s[1::31]in'%6s'%0*2` checks that the second column contains at most one `0`.

The ending `*f(s[1:])` also forces the recursive case to be true.

# Answer
> 1 votes
# Jelly, 19 bytes

```
Zn⁶T€L€=1$$;FIỊ$$$Ạ

```

Try it online!

-2 bytes thanks to Mr. Xcoder

# Explanation

```
Zn⁶T€L€=1$$;FIỊ$$$Ạ  Main Link
Z                    Transpose the matrix of characters
                         (string -> list of chars in Jelly)
 n⁶                  != " " (vectorizing)
   T€                For each column, get (row) indices of snake parts
     L€=1$$          For each index list, is its length 1? (that is, exactly one snake part per column)
           ;     $   Append (helper part)
            FIỊ$$    helper part:
            F        flatten index list
             I       get increments/forward differences
              Ị      are the values insignificant? (|z| <= 1)
                  Ạ  Are these all true?

```

Input is as a list of strings

# Answer
> 1 votes
# Python 2 and Python 3, 122 120 119 bytes

```
lambda s:s.count('0')<31and all(s[i-31*(i>30):31*(i<124)-~i:31].strip(' ')for i,x in enumerate(s,1)if' '<x)and' '<s[62]

```

Try it online!

Input format is one string of length 154 (5 x 30 chars, 4 newlines):

```
'''
            0 0
  0        0 0 000
00 0     00       000 0      0
    000 0            0 0   00
       0                000   '''[1:] # to exclude starting newline

```

---

# If the head doesn't have to be the center row

The center-row-head requirement was in the original challenge, but I found that it's not the case here (at least it's not explicitly mentioned).

# Python 2 and Python 3, 124 123 bytes

```
lambda s:s.count('0')<31and all(s[i-31*(i>30):31*(i<124)-~i:31].strip(' ')for i,x in enumerate(s,1)if' '<x)and'0'in s[::31]

```

Try it online!

---

**Edit:**

* Reduced 2 bytes by changing equals(`==`) into inequalities for each code.
* Found mistakes in the less limiting version, and revised it. (Fortunately it's not too terrible, so I could keep all versions similar in length.) You can see additional test cases in the latter two TIO links.
* Found a dangling byte in Py2 solutions, making the `all()` trick meaningless in Py3, so merged both versions.

# Answer
> 1 votes
# MATL, ~~18~~ 17 bytes

```
32>&fun30=wd|2<vA

```

Input is a 2D char array. Any non-space character can be used for the snake.

Try it online!

### Explanation

```
32>      % Implicit input. Transform non-space into 1, space into 0
&f       % Push vector of row indices and vector of column indices of nonzeros
u        % Unique: vector of deduplicated entries
n        % Length
30=      % Does it equal 30? (*)
w        % Swap. Moves vector of row indices to top
d|       % Absolute consecutive differences
2<       % Is each value less than 2? (**)
v        % Concatenate results (*) and (**) vertically
A        % All: true if all entries are nonzero. Implicit display

```

# Answer
> 1 votes
# Jelly, (14?\*) 13 bytes

```
Zn⁶T€z-IỊ0-¦Ȧ

```

A monadic link taking a list of five strings\*, each of length 30 consisting of spaces and any other characters (e.g. `0`s), and returning an integer (1 if a snake as defined, 0 otherwise)

* If input must be a single string (list of characters) then prepend a  to split the string at line feeds.

**Try it online!**

### How?

```
Zn⁶T€z-IỊ0-¦Ȧ - Link: list of lists of characters, Lines
Z             - transpose the lines -> columns
  ⁶           - literal space character
 n            - not equal? -> 0 where there were spaces and 1 where there were "0"s
   T€         - truthy indices for each -> e.g. [0,0,1,0,0] -> [3] or [0,1,1,0,0] -> [2,3]
              -                           note: [0,0,0,0,0] -> []
      -       - literal minus one
     z        - transpose with filler (-1) -> {valid: a single list of heights {top:1,...,bottom:5}
              -                              invalid: list of >1 lists, some of which contain -1
              -                                       ...OR an empty list (no 0s in the input at all)}
       I      - differences -> {up:-1; down:1; flat:0; invalid:-6,-5,...,-2,2,...4}
        Ị     - insignificant (abs(z)<=1) -? {up/down/flat:1; invalid:0}
           ¦  - sparse application///
         0    - ...action: literal zero
          -   - ...to indices: [-1] -> make penultimate list into a zero (when one exists)
            Ȧ - any & all -> when flattened:{empty or contains a 0:0; otherwise:1}

```

# Answer
> 1 votes
# Stax, 20 bytesCP437

```
Å┴m▐◘5)ît╢V¼≥+╝╜►º½ê

```

24 bytes when unpacked,

```
LM{'0|Ic%vChm:-{Jh!f%29=

```

Run and debug online!

May not be the best golfed one but I think the method is novel and interesting.

## Explanation

```
LM                          Load the input string as a 2d array of characters, and transpose it

  {         m               Map array with block
   '0|I                     Get all indices of substring "0"
       c%vC                 Map to nothing if the indices are not unique
           h                Otherwise map to the unique index

             :-             Take pairwise difference

               {   f        Filter array with block
                Jh!         Only keep 0, 1 and -1

                    %29=    Check whether the final array has exactly 29 elements

```

# Answer
> 1 votes
## Grime, ~~30~~ ~~26~~ 23 bytes

*Thanks to Zgarb for saving 7 bytes and pointing out a bug.*

```
e`" 0/0 "oO|#29ddv&d#1+

```

Try it online!

# Answer
> 1 votes
## Slip, 28 bytes

```
((\|/)?0(<(?| *$^)<){2}){30}

```

Test it here.

# Answer
> 1 votes
# , 38, 37 30 bytes

-8 bytes thanks to FrownyFrog

```
[:($e.~[:(-:*)2-/\])@:I.'0'=|:

```

Try it online!

# Answer
> 1 votes
# Pip `-r`, ~~26~~ 24 bytes

```
$&ZgM{0Na<2>yAD#y*Ya@?0}

```

Takes the snake from stdin and outputs 0 for invalid or 1 for valid. Attempt This Online!

### Explanation

This was fun. I went through several different versions, finally ending up with a solution that abuses the `y` variable delightfully and also shows off Pip's chaining comparison operators.

```
$&ZgM{0Na<2>yAD#y*Ya@?0}
                          g is list of lines of stdin (-r flag); y is "" (implicit)
  Zg                      Zip g, transposing rows and columns
    M{                 }  To each sublist (column of the original input), map this function:
      0Na                  The number of 0s in this column
         <2                 is less than 2
           >                and 2 is greater than the following quantity:
            y                The index of the 0 in the previous column, or "" if this is
                              the first column
             AD              Absolute difference with
               #y*            len(y) times
                   a@?0       the index of 0 in this column
                  Y           which we also store in y
$&                        Fold the resulting list on logical AND

```

The expression `yAD#y*Ya@?0` warrants further explanation. We want to calculate the difference between the indices of 0s in consecutive columns. We calculate the index of 0 in the current column (`a@?0`) and store it in `y` by using the `Y`ank operator (`Ya@?0`).

But then how can we access the previous column's index, which was stored in `y`? We'll have to access it *before* overwriting `y` with the new value. Since Pip expressions are always evaluated left-to-right, we can use the old value of `y` on the left side of the expression and update to the new value on the right.

The first column presents another wrinkle. Here, when we access the old value of `y`, we haven't had a chance to set it to anything yet, and it still has its initial value of `""`. We want the first column to succeed no matter what its 0 index is, which means we need the difference to be between -1 and 1. So we multiply the new value by the length of the old value (`#y`). If `y` hasn't been set yet, this multiplies the new value by 0, making the difference 0. If `y` has been set, it will be a single-digit number (since there are only 5 rows in the input), and so multiplying by its length will leave the new value unchanged.

# Answer
> 1 votes
# Vyxal, 14 bytes

```
∩ȧvT:v₃$¯ȧ2<JA

```

Try it Online!

Takes input as a list of char lists.

```
∩              # Transpose the input
 ȧ             # Remove whitespace (since this is a char list list, spaces become empty)
  vT           # Truthy indices (indices of 0) of each
            JA # Are both...
    :v₃        # All elements are length 3
       $¯ȧ     # And all elements have absolute differences
          2<   # Less than 2.

```

# Answer
> 0 votes
# Python 2, 141 bytes

```
lambda g:(lambda a:all(map(len,a)+[-2<x-y<2 for b in[sum(a,[])]for x,y in zip(b,b[1:])]))([[i for i in range(5)if"0"==r[i]]for r in zip(*g)])

```

Try it online!

Input is a grid of characters.

# Answer
> 0 votes
# JavaScript (Node.js), ~~128~~ 126 bytes

Edited after input clarification stating that the input is "a string".

```
F=(a,l=29,r=0,t=/^( *)0 *$/.exec(a.split`
`.map(p=>p[l]).join``),q=t&&~t[1].length)=>q&&(s=q-(r=r||q))>-2&s<2?l?F(a,l-1,q):1:0

```

Try it online!

# Answer
> 0 votes
# Excel (VBA), 68 bytes

Using Immediate Window, `Cell[A6]` as output.

```
[A1:AD5]="=CHOOSE(ROUND(RAND()+1,),0,"""")":[A6]="=COUNT(A1:AD5)=30"

```

# Answer
> 0 votes
## Snails, 18 bytes

```
\0!(ud.,\0)raa7)30

```

Try it online!

# Answer
> 0 votes
# Ruby, 93 bytes

```
->x{x.transpose.map{|x|x.count(?0)<2&&x.index(?0)}.each_cons(2).all?{|x,y|x&&y&&(x-y).abs<2}}

```

Try it online!

# Answer
> 0 votes
# Python 3, ~~197~~ 185 bytes

In command prompt do `verify.py<snake.txt` or in bash do `cat snake.txt | python verify.py`. Where `snake.txt` is a file containing a snake to verify.

If the snake is correct nothing will be output. If it isn't correct Python will raise an index error.

```
import sys
s=sys.stdin.read().split("\n")
x=0
exec('t,y="",0\nwhile y<5:t+=s[y][x];y+=1\ns+=[t];x+=1;'*30)
s=list(map(lambda l:len(l.rstrip()),s))
while y<35:"ee"[abs(s[y]-s[y+1])];y+=2

```

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


title: Build me a room

text:
# Question
Title: Build me a room
Related

A room, in the context of this challenge, is a multidimensional array where the elements on the "outside" are `1`, to represent the walls, and all the other elements are `0` (empty space inside the room)

Here's a 1D room with size 5:

```
[1,0,0,0,1]

```

And here's a 2D room with size 6x4:

```
[[1,1,1,1],
 [1,0,0,1],
 [1,0,0,1],
 [1,0,0,1],
 [1,0,0,1],
 [1,1,1,1]]

```

It's 6x4 and not 4x6 because the list has length 6 at depth 1, and length 4 at depth 2.

Or a 4x4x4 room (imagine each 4x4 sub-array as a 2D slice of the 3D room):

```
[[[1,1,1,1],
  [1,1,1,1],
  [1,1,1,1],
  [1,1,1,1]],
 [[1,1,1,1],
  [1,0,0,1],
  [1,0,0,1],
  [1,1,1,1]],
 [[1,1,1,1],
  [1,0,0,1],
  [1,0,0,1],
  [1,1,1,1]],
 [[1,1,1,1],
  [1,1,1,1],
  [1,1,1,1],
  [1,1,1,1]]]

```

A room can be recursively defined by starting with `0` and replacing each `0` with `[1,0,0,...,0,1]` and each 1 with `[1,1,...,1,1]`, each to the appropriate length and depth.

Your challenge is to take a list of integers and output a room with those dimensions. Dimensions will always be \\$ \>1 \\$. A dimension value of 2 means no space inside, so if there's a 2 the whole thing will be `1`s.

You may use any two consistent values instead of `0` and `1` to represent space and wall.

Output may be as a flattened string, e.g. \[3,4\] =\> `111110011111`.

You may take the coordinate list reversed (inside out).

# Scoring

This is , so the shortest code in bytes wins!

# Testcases

```
[3] => [1,0,1]
[2,2,2,2,2] => [ [ [ [ [1,1], [1,1] ], [ [1,1], [1,1] ] ], [ [ [1,1], [1,1] ], [ [1,1], [1,1] ] ] ], [ [ [ [1,1], [1,1] ], [ [1,1], [1,1] ] ], [ [ [1,1], [1,1] ], [ [1,1], [1,1] ] ] ] ]
[4,4,4] => [ [ [1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1] ], [ [1,1,1,1], [1,0,0,1], [1,0,0,1], [1,1,1,1] ], [ [1,1,1,1], [1,0,0,1], [1,0,0,1], [1,1,1,1] ], [ [1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1] ] ]
[5,6] => [ [1,1,1,1,1,1], [1,0,0,0,0,1], [1,0,0,0,0,1], [1,0,0,0,0,1], [1,1,1,1,1,1] ]
[3,19] => [ [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] ]
[12] => [1,0,0,0,0,0,0,0,0,0,0,1]

```

Thanks to golden\_bat and pxeger for clarifying and fixing this challenge.

# Answer
# Jelly, 7 bytes

```
R%)Ịoþ/

```

A monadic Link that accepts the dimensions as a list of positive integers ordered by depth descending (like the examples in the question) and yields the room as a multi-dimensional list of `1`s and `0`s.

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

### How?

```
R%)Ịoþ/ - Link: list of positive integers, Sizes
  )     - for each (size in Sizes):
R       -   range (size)  -> [1,2,3,...,size]
 %      -   modulo (size) -> [1,2,3,...,0]
   Ị    - insignificant?  -> [...,[1,0,0,...,1],...]
      / - reduce by:
     þ  -   make a table using:
    o   -     logical OR (vectorises)

```
> 8 votes

# Answer
# APL(Dyalog Unicode), 11 bytes SBCS

```
⊢↑1∘-↑-∘2⍴≡

```

Try it on APLgolf!

Sometimes the most straightforward method wins. Space is 1, wall is 0.

### How it works

```
⊢↑1∘-↑-∘2⍴≡    Monadic train; ⍵←dimension vector
      -∘2⍴≡    Create the core of ones of dimensions of ⍵-2
  1∘-↑         Prepend a layer of zeroes by overtaking ⍵-1 in reverse
⊢↑             Append a layer of zeroes by overtaking ⍵

```
> 7 votes

# Answer
# APL (Dyalog Unicode), 12 bytes

Anonymous tacit prefix function.

```
⊂(∨/=,1∊⊢)¨⍳

```

Try it online!

`⊂(``)¨⍳` apply the following tacit infix function between the entire argument and each index in an array of those dimensions:

`1∊⊢` is there a `1` in the index?

`=,` prepend a Boolean list indicating which coordinate are equal to the corresponding element of the original argument

`∨/` are any true? (lit. OR reduction)
> 6 votes

# Answer
# K (ngn/k), ~~14~~ 11 bytes

```
|/~&/|:'\!:

```

Try it online!

@ngn suggested a 13-byter `{|/~x&|'x:!x}` in chat, which

* overwrites `x` with the odometer (`x:!x`),
* takes element-wise minimum `&` with its row-wise reverse `|'x`,
* and then does `|/~` as below.

The 11-byter above is the result of `x f g x` trainifying tip. 1 in `1|:'\` can be omitted because odometer's reverse is always different from itself (assuming all dimensions are at least 2).

---

# K (ngn/k), 14 bytes

```
{|/~(x-1)!'!x}

```

Try it online!

Same bytecount as Traws's but different approach. Returns a flattened list of ones on the wall and zeros inside. The helper function `g` reshapes the flattened list into the desired shape.

### How it works

```
{|/~(x-1)!'!x}    monadic function; x: a list
           !x     odometer: column-wise list of coordinates in x-shaped array
    (x-1)!'       use modulo x-1 to convert occurrence of x-1 in each row to zeros
   ~              boolean NOT
 |/               reduce by boolean OR over each column

```
> 6 votes

# Answer
# JavaScript (ES6), 65 bytes

Expects the input list in reverse order.

Very similar to the 66-byte version, but returns a flattened string.

```
f=([n,...a],b='0')=>n?b.replace(/./g,v=>f(a,1+v.repeat(n-2)+1)):b

```

Try it online!

---

# JavaScript (ES6), 66 bytes

Expects the input list in reverse order.

```
f=([n,...a],b=[0])=>n?b.map(v=>f(a,[1,...Array(n-2).fill(v),1])):b

```

Try it online!

### Commented

```
f = (                   // f is a recursive function taking:
  [ n,                  //   n = next value from the input list
       ...a ],          //   a[] = all remaining values
  b = [ 0 ]             //   b[] = output, initialized to [ 0 ]
) =>                    //
n ?                     // if n is defined:
  b.map(v =>            //   for each value v in b[]:
    f(                  //     do a recursive call:
      a,                //       pass the remaining values
      [                 //       build an array consisting of:
        1,              //         a leading '1'
        ...Array(n - 2) //         followed by n - 2 values
        .fill(v),       //         set to v
        1               //         followed by a trailing '1'
      ]                 //       end of array
    )                   //     end of recursive call
  )                     //   end of map()
:                       // else:
  b                     //   we're done: return b[]

```
> 5 votes

# Answer
# Octave with Image Package, 25 bytes

```
@(d)padarray(e(d-2),+~~d)

```

Anonymous function that inputs a vector with the coordinates and outputs an *n*-dimensional array. Wall and space are respectively `0` and `e` (equal to `2.71828...`)

Note that, when displaying, the first dimension corresponds to the vertical direction.

**Try it online!**

### Explanation

```
@(d)padarray(e(d-2),+~~d)

@(d)                      % Define anonymous function
             e(d-2)       % N-dim array containing e, with side lengths given by d-2
                    +~~d  % Negate d twice, cast to double: gives vector of N ones (**)
    padarray(      ,    ) % Add a frame of zeros to (*) with thickness (**) in each dim

```
> 5 votes

# Answer
# Haskell, 57 bytes

```
s[]="0"
s(a:b)|k<-[1..product b]>>"1"=k++([3..a]>>s b)++k

```

Try it online!

Builds a flat list since Haskell is strongly typed. Also takes the coordinates in reverse.
> 4 votes

# Answer
# Python 3.6, 63 bytes

```
f=lambda d,w=0:d and[f(d[1:],x)for x in[1,*[w]*(d[0]-2),1]]or w

```

Try it online!

Got the and/or mechanism from aeh5040's post. Originally I was just using a ternary operator.
> 4 votes

# Answer
# Python 3.8 (pre-release), 65 bytes

```
f=lambda d,o=0:d and[f(t:=d[1:],1),*[f(t,o)]*(d[0]-2),f(t,1)]or o

```

Try it online!
> 3 votes

# Answer
# , 14 bytes

```
{.-@<:{.-&2$1:

```

Try it online!

*This is a translation of Bubbler's nice answer into J.*

I tried a few other approaches, including stumbling on the same one Adam used, but in J Bubbler's approach was easily the shortest.
> 3 votes

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

```
|/:/{~x#!x-1}'

```

Try it online!

```
    {       }'            for each dimension apply the function in lambda
      x#!x-1              overtake n from the range of n-1,        e.g. 0 1 2 3 4 0 for n=6
     ~                    "not" the array to get ones at the edges e.g. 1 0 0 0 0 1
|/:/                      max table along all dimensions

```
> 3 votes

# Answer
# Coconut, 68 bytes

Uses the recursive method described in the challenge. Takes input in reversed order.

```
g=(x,k)->x*0==0and[1,*[x]*(k-2),1]or[*map(g$(?,k),x)]
reduce$(g,?,0)

```

Try it online!
> 2 votes

# Answer
# Jelly, 10 bytes

```
Œp’ỊƇƇo⁸ŒṬ

```

Try it online!

A monadic link taking a list of integers and returning a list of the appropriate depth of 0s and 1s. Works by generating a list of all of the coordinates, keeping only those that are the walls and using the multidimensional untruthy link to generate the final list.
> 2 votes

# Answer
# Haskell, 32 bytes

```
map(elem 0).mapM(\i->0:[2-i..0])

```

Try it online!

Outputs a flat list of Booleans
> 2 votes

# Answer
# Julia 0.7, ~~39~~ 37 bytes

```
x->(a=ones(x);a[(:).(2,x.-1)...]=0;a)

```

Try it online!

Takes input as a tuple of dimensions, outputs a multidimensional array with `1`s and `0`s formatted as floats.
> 2 votes

# Answer
# Charcoal, 28 bytes

```
≔0ζ≔1ηＦ⮌θ«≔Ｅι⎇﹪κ⊖ιζηζ≔Ｅιηη»ζ

```

Try it online! Link is to verbose version of code. Outputs vertically with ever larger number of newlines as delimiters between different dimensions. Explanation:

```
≔0ζ≔1η

```

Start with `0` as the hollow room and `1` as a solid room.

```
Ｆ⮌θ«

```

Loop through the dimensions in reverse order so that the innermost dimension is processed first.

```
≔Ｅι⎇﹪κ⊖ιζηζ

```

For the next level of hollow room, take the number of rooms and make the first and last solid.

```
≔Ｅιηη

```

The next level of solid rooms is just an array of the appropriate number of solid rooms of the previous level.

```
»ζ

```

Output the final hollow room.
> 1 votes

# Answer
# APL (Dyalog Unicode), 10 bytes

```
∨∘⌽⍨∘,0∊¨⍳

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 13 bytes

```
ÎvTyo<y<o>‚b‡

```

Straight-forward approach. Can definitely be golfed a bit with a smarter approach.
Output is a flattened string.

Try it online or verify all test cases.

**Explanation:**

```
Î           # Push 0 and the input-list
 v          # Loop over the integers `y` of this list:
  T         #  Push 10
   yo<      #  Push 2^y-1 (oeis sequence A000225)
   y<o>     #  Push 2^(y-1)+1 (oeis sequence A000051)
       ‚    #  Pair them together
        b   #  Convert both to a binary string
         ‡  #  Transliterate the [1,0] to ["111...111","100...001"] respectively
            # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 26 bytes

```
Array[!1{##}a&,a=#]&

```

Try it online!

The private-use character is `\[VectorLess]`.
> 1 votes

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


title: Knights Jam | Chess

text:
# Question
Title: Knights Jam | Chess
The knight is a chess piece that, when placed on the `o`-marked square, can move to any of the `x`-marked squares (as long as they are inside the board):

```
.x.x.
x...x
..o..
x...x
.x.x.

```

Eight knights, numbered from 1 to 8, have been placed on a 3×3 board, leaving one single square empty `.`.

They can neither attack each other, nor share the same square, nor leave the board: the only valid moves are jumps to the empty square.

Compute the minimum number of valid moves required to reach the following ordered configuration by any sequence of valid moves:

```
123
456
78.

```

Output `-1` if it is not reachable.

Example detailed: Possible in 3 moves

```
128       12.       123       123
356  -->  356  -->  .56  -->  456
7.4       784       784       78.

```

## Input & Output

* You are given three lines of three characters (containing each of the characters 1-8 and `.` exactly once)
* You are to output a single integer corresponding to the smallest number of moves needed to reach the ordered configuration, or `-1` if it is not reachable.
* You are allowed to take in the input as a matrix or array/list
* You are allowed to use `0` or  in the input instead of `.`

## Test cases

```
128
356
7.4
->
3

674
.25
831
->
-1

.67
835
214
->
-1

417
.53
826
->
23

```

## Scoring

This is code-golf, so shortest code wins!

Credits to this puzzle

# Answer
# 05AB1E, ~~40~~ ~~39~~ 38 bytes

-1 byte porting *@Neil*'s 54 bytes Charcoal approach:

```
•4Gв©Tв•8×I•55˜u•SèDðkUþJk8*X+D56α‚ß®M

```

Try it online or verify all test cases.

***Original answer:***

```
•þÜε•SDIðkk._Tиü2vÐ{QiND56α‚ßq}DyèyRǝ}®

```

Try it online or verify all test cases.

Both programs take a flattened list of digits as input with `" "` as empty square.

**Explanation:**

```
•4Gв©Tв•        # Push compressed integer 4381672438167
 8×             # Repeat it 8 times as string
   I            # Push the input-list
    •55˜u•      # Push compressed integer 83270561
     S          # Convert it to a list of digits
      è         # Index each into the input
       D        # Duplicate it
        ðk      # Get the index of the space " "
          U     # Pop and store this index in variable `X`
        þ       # Remove the space by only keeping digits
         J      # Join it together to a string
          k     # Get the first 0-based index of this in the large string
           8*   # Multiply this by 8
             X+ # Add index `X`
D               # Duplicate it
 56α            # Get the absolute difference with 56
    ‚           # Pair both together
     ß          # Pop and push the minimum
      ®         # Push -1
       M        # Push the largest number on the stack
                # (after which it is output implicitly as result)

```

```
•þÜε•           # Push compressed integer 16507238
 S              # Convert it to a list of digits
  D             # Duplicate it
   I            # Push the input-list
    ðk          # Get the index of the space " "
      k         # Use that to index into the duplicated list of digits
       ._       # Rotate the list of digits that many times towards the left
         Tи     # Repeat it 10 times as list
ü2              # Get all overlapping pairs of this list
  v             # Loop over each pair `y`:
   Ð            #  Triplicate the current list
                #  (which will be the implicit input in the first iteration)
    {           #  Sort the top copy
                #  (where the space will go to the end of the sorted digits)
     Qi         #  If the two lists are still the same
       N        #   Push the loop index
        D56α‚ß  #   Same as above
              q #   Stop the program
                #   (after which the result is output implicitly)
       }        #  Close the if-statement
        DyèyRǝ  #  Swap the values at indices `y`:
        D       #   Duplicate the list once more
         yè     #   Get the values at the `y` indices
           yR   #   Push the reversed pair `y`
             ǝ  #   Insert the values back into the list at those indices
}               # Close the loop
 ®              # Push -1
                # (which is output implicitly if we haven't encountered the `q`)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•4Gв©Tв•` is `4381672438167`; `•55˜u•` is `83270561`; and `•þÜε•` is `16507238`.
> 2 votes

# Answer
# Charcoal, ~~54~~ 52 bytes

```
≔⭆³Ｓθ≔⭆83270561§θＩιθＩ⌈⟦±¹⁻²⁸↔⁻²⁸⁺×⁸⌕”)″“◨_'↷χ”⁻θ.⌕θ.

```

Try it online! Link is to verbose version of code. Save 4 bytes if printing any negative number is acceptable for an unreachable configuration. Explanation:

```
≔⭆³Ｓθ

```

Input the grid and join the lines together into a single string.

```
≔⭆83270561§θＩιθ

```

Reorder the digits from the string starting at the original bottom right corner and taking clockwise knight's moves.

```
Ｉ⌈⟦±¹⁻²⁸↔⁻²⁸

```

Output the difference from 28 of the absolute difference with 28 (or `-1` if that is negative) of...

```
⁺×⁸⌕”)″“◨_'↷χ”⁻θ.⌕θ.

```

... finding the position of that string excluding the `.` in the compressed string `4381672438167`, multiplying that by 8, and adding on the position of the `.`.
> 3 votes

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

```
(n,F=(i,I)=>(I%3-i%3)**2+((I/3|0)-(i/3|0))**2==5)=>Math.min(...(X=[...Array(9)].flatMap((e,i,a)=>F(i,n.search`0`)?[eval('for(k=0,N=n,S=[];!(t=S.filter(Z=>Z==N)[1])&&N!="123456780";(N=[...m=N],N[h=m.search`0`]=N[(H=k?a.findIndex((E,P)=>P!=M&F(P,h)):i,M=m.search`0`,H)],N[H]="0",S.push(N=N.join``),k++));t?-1:k')]:[])).length?X:[-1])

```

Try it online!

Takes a 9-character string where the dot is replaced by a zero.

## Explanation

As the trick is really fun to find, I've hidden it behind a spoiler.

> There are only two spaces that are a knight's move away from the zero. Let us consider one of the pieces. If we move it to the zero, then we can decide to move it back to where it was. However, that wastes moves. Since there are only two spaces that are a knight's move away from any given space, this means that only one other piece can be moved to the new position of the zero, other than the one we just moved. As a result, we must move that piece. Using the same reasoning as above, this means that there is only one "path" originating from a given move, because we only have one choice at each stage. Eventually, we will end up at the ideal arrangement. Now, to account for the impossible cases, notice that there are only so many possible moves. Eventually, we will reach an arrangement that we have already seen. If we do, that means the case is impossible and we can break out of the loop and return -1.

A problem I have is that this is way too long, so I'll try to keep golfing it.

Fixed a bug that would create outputs of `Infinity` for certain inputs.
> 3 votes

# Answer
# Python 3, 126 bytes

```
def f(a,s=[*range(1,9),0],m=0,n=8):
 for o in(3,2,7,0,5,6,1,8)*7:m+=a!=s or m-55;s[n],s[o],n=s[o],0,o
 return min(56-m or-1,m)

```

Try it online!

*-1 byte thanks to Jonathan Allan*

*-3 bytes thanks to Arnauld*

There are 56 possible permutations. From the starting position, we can walk a circular path 7 times, until we reach the starting position again. If the input is found, we return the number of steps `m` required. If the path is shorter the other way around, we return `56-m`.
> 2 votes

# Answer
# JavaScript (ES6),  ~~110 108~~  105 bytes

This is very similar to Jitse's answer.

Expects a comma-separated string.

```
a=>(b=[..."123456780"],g=k=>i=b!=a&&k--?g(k,b[(s="83270561")[k+1&7]]=b[p=s[k&7]],b[p]=0):k)(56)>28?56-i:i

```

Try it online!
> 1 votes

# Answer
# Excel, 158 bytes

```
=IFERROR(LET(a,MID(A1&A2&A3,{2;7;6;1;8;3;4;9},1)*1,b,CONCAT(FILTER(a,a)),d,"2761834",f,(FIND(2,b)*8+1-XMATCH(0,a))*(1-ISERROR(FIND(b,d&d)))-1,MIN(f,56-f)),-1)

```

Link to Spreadsheet
> 1 votes

# Answer
# Ruby, ~~101~~ 98 bytes

```
->n{a=[*1..8,0];z=j=-29
("I`;-XAf#"*7).bytes{|i|j+=1;a==n&&z=j;a[i/9%9],a[i%9]=a[i%9],0}
28-z.abs}

```

Try it online!

Fairly straightforward. Cycle generates all 56 possible positions and compares with the input.

Saved some bytes off the orignal version by counting from the solved position at `-28` through `0` to `+27`, and using `28-z.abs` to decode the output.
> 0 votes

---
Tags: code-golf, string, matrix, chess
---


title: Factorials of primes decomposition

text:
# Question
Title: Factorials of primes decomposition
You have to decompose a positive integer/fraction as a product of powers of factorials of prime numbers.

For example

> `22 = (11!)^1 × (7!)^(−1) × (5!)^(−1) × (3!)^(−1) × (2!)^1`

> `10/9 = (5!)^1 × (3!)^(−3) × (2!)^1`

Use this special notation: `prime number#power` to denote each term, e.g. `(11!)^4` is denoted as `11#4`.

Output the non-zero terms only, with space separation.

The above examples hence become:

> `22 = 11#1 7#-1 5#-1 3#-1 2#1`

> `10/9 = 5#1 3#-3 2#1`

## Input & Output

* You are given a positive number `N`, that can be either an integer or a fraction of the form `numerator/denominator`
* The ordered list of the non-zero terms of the decomposition of `N`, denoted using the special notation
* You are allowed to output the terms as a list/array (containing strings with the special notation `#`)
* You are allowed to output the terms in any order
* Duplicate prime numbers are allowed
* You are not allowed to use terms that have to the power of `0`

## Test cases

```
6 -> 3#1
5040 -> 7#1
22 -> 11#1 7#-1 5#-1 3#-1 2#1
1/24 -> 3#-1 2#-2
720/121 -> 11#-2 7#2 5#3 3#3

```

This is code-golf, shortest code wins!

Credits to this puzzle

# Answer
# 05AB1E, 30 bytes

```
þ>LD(«ZÅPâæ¦.Δε`!sm}PI.EQ}í'#ý

```

Outputs as a list of strings. Can output with duplicated prime numbers as allowed in the rules (e.g. `3/4` results in `["3#1","2#-1","2#-2"]` instead of `[3#1","2#-3"]`).
Brute-force approach, so very slow and times out for most test cases.

Try it online or verify some test cases using values below `3` by replacing the `þ>`.

**Explanation:**

```
þ         # Keep the digits of the (implicit) input, potentially removing the "/"
          # for fractions
 >        # Increase it by 1 (for edge case input=1 or 1/1)
  LD(«    # Convert it into a [value,-value]-ranged list without 0:
  L       #  Pop the copy and push a list in the range [1,value]
   D      #  Duplicate this list
    (     #  Negate each value
     «    #  Merge the two lists together
  Z       # Push the maximum (without popping), which is the value again
   ÅP     # Pop and push a list of primes <= this value
      â   # Cartesian power to create all possible pairs of the two lists
       æ  # Get the powerset of this list of pairs
        ¦ # Remove the leading empty list (for edge case input=1 or 1/1 again,
          # because the product of an empty list is 1)
.Δ        # Find the first result which is truthy for:
  ε       #  Map the list of pairs to:
   `      #   Pop and push the values in the pair separated to the stack
    !     #   Take the factorial on the second
     s    #   Swap so the other is at the top
      m   #   Exponent the two together
  }P      #  After the map: take the product of the values
    I     #  Push the input
     .E   #  Evaluate it as Elixir code, which calculates the value for factorial
          #  inputs and will keep integer inputs unchanged
       Q  #  Check if they're the same
 }í       # After we've found our result: reverse each inner pair
   '#ý   '# Join each inner pair with "#"-delimiter
          # (after which the list is output implicitly as result)

```
> 2 votes

# Answer
# Python 3, 133 130 bytes

```
import math
g=lambda i,k=1,n=1,j=2:i%j%i and g(i,k,n,j+1)or(i+k<3)*" "or"%s#%s "%(j,n)*(i>1)+g(k*math.factorial(j-1),i//j or 1,-n)

```

Try it online!

<sup>-3 bytes thanks to loopy walt</sup>

<sup>-5 more bytes if using python 3.8, as pointed out by ovs </sup>

Returns a whitespace separated string.

Uses a recursive algorithm: `i` is the numerator and `k` is the denominator. If `n` is -1, the roles are reversed. `j` is a potential divisor of `i`; `j` is incremented until it divides `i`. After this, we add `j#n` to the output and the function is called again with the roles reversed (`n` is negated). More precisely for inputs `i`, `k` we recurse with `i=k*fact(j-1),k=i//j`. This halts, because every step we are removing one "instance" of the prime number `j`, and only possibly adding smaller primes.

Just for fun, here are some shorter programs using looser IO rules:

106 bytes: Integer input only, returns flat list
> 2 votes

# Answer
# Excel (Insider Beta), 350 bytes

```
=LET(e,IFERROR(FIND("/",A1),0),n,ROW(1:99),m,COLUMN(A:CU),p,SORT(FILTER(n,MMULT(1*(MOD(n,m)=0),n^0)=2),,-1),f,LAMBDA(d,LET(c,MMULT((MOD(d,p^m)=0)*1,n^0),h,LAMBDA(x,y,SUM(INT(x/y^n))),z,TRANSPOSE(MINVERSE(MAKEARRAY(25,25,LAMBDA(x,y,h(INDEX(p,x),INDEX(p,y)))))),MMULT(z,c))),r,IF(e,f(LEFT(A1,e-1))-f(MID(A1,e+1,99)),f(A1)),CONCAT(IF(r,p&"#"&r&" ","")))

```

Uses `MAKEARRAY` and `LAMBDA` which are not widely available yet. Prime factors are not duplicated. Works for all numbers \\$ \<= 2^{20} \\$ whose prime factors are all \\$\<100\\$.

## Explanation

`=LET(e,IFERROR(FIND("/",A1),0),` Finds position of "/"; return 0 if not found

`n,ROW(1:99),` vertical array of 1..99

`m,COLUMN(A:CU),` horizontal array of 1..99

`p,SORT(FILTER(n,MMULT(1*(MOD(n,m)=0),n^0)=2),,-1),` reverse sort of all primes \\$\<100\\$.

`f,LAMBDA(d,` `f` is the function that returns the array of prime factorials for an integer \\$\>1\\$.

`LET(c,MMULT((MOD(d,p^m)=0)*1,n^0),` the vertical array of the number of times each prime divides \\$d\\$.

`h,LAMBDA(x,y,SUM(INT(x/y^n))),` function that returns the number of times \\$y\\$ divides \\$x!\\$.

`MAKEARRAY(25,25,LAMBDA(x,y,h(INDEX(p,x),INDEX(p,y))))` an array indicating how many times each prime divides the factorial of each prime

`z,TRANSPOSE(MINVERSE(~)),` the inverse of the prime matrix, note: I had to use `TRANSPOSE` instead of reversing x & y because of some weird precision errors.

`MMULT(z,c))),` matrix multiply z and c, this transforms the number of times each prime divides d to the powers of prime factorials

`r,IF(e,f(LEFT(A1,e-1))-f(MID(A1,e+1,99)),f(A1)),` if \\$e\>0\\$ then \\$r=f(num.)-f(denom.)\\$ else \\$r=f(n)\\$.

`CONCAT(IF(r,p&"#"&r&" ","")))` if an element in \\$r\>0\\$ then return \\$p\\$#\\$r\\$ and then concatenate.
> 2 votes

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

```
x=>([n,d=1]=x.split('/'),(f=r=>r<2?'':(((i=y=>y<2||r%y&&i(~-y))(~-r)?v=(q=s=>s%r?0n:-~q(s/r))(n,w=q(d)):v=w=0n)-w?' '+r+'#'+(v-w):'')+f(~-r,n*=(F=n=>n?n*F(~-n):1n)(r)**w,d*=F(r)**v))((n=(z=BigInt)(n))>(d=z(d))?n:d).trim())

```

Try it online!

`.trim()` could be removed (-7 bytes) if you were willing to tolerate an extraneous space at the start of the output.
> 2 votes

# Answer
# Charcoal, ~~94~~ 89 bytes

```
≔Ｉ…⪪⁺Ｓ/1¦/²θ≔Πθη≔²ζＷ⊖η¿﹪ηζ≦⊕ζ≧÷ζηＷ⊖ζ¿∨¬⬤…²ζ﹪ζκΠ﹪θζ≦⊖ζ¿¬Σ﹪θζ≧÷ζθ«Ｉζ#⌕﹪θζ⁰1→ＵＭθ⎇﹪κζ×κΠ…·¹ζκ

```

Try it online! Link is to verbose version of code. Outputs each prime factorial once per power. Explanation:

```
≔Ｉ…⪪⁺Ｓ/1¦/²θ

```

Append "/1" to the input in case it's a single integer, then split it on "/" and take the first two values.

```
≔Πθη≔²ζＷ⊖η¿﹪ηζ≦⊕ζ≧÷ζη

```

Find the largest prime number dividing either the numerator or denominator.

```
Ｗ⊖ζ¿∨¬⬤…²ζ﹪ζκΠ﹪θζ≦⊖ζ

```

Loop though the prime numbers down to `2`, decrementing if the current number is not prime or does not divide either the numerator or denominator.

```
¿¬Σ﹪θζ≧÷ζθ«

```

If the current prime number divides both numerator and denominator, start reducing the fraction to its lowest terms, otherwise:

```
Ｉζ#⌕﹪θζ⁰1→

```

Print the current prime number with "#-1" if it's a factor of the denominator or "#1" if it's a factor of the numerator, leaving a space between prime factorials.

```
ＵＭθ⎇﹪κζ×κΠ…·¹ζκ

```

Multiply whichever isn't a factor by the factorial of the prime.
> 2 votes

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

```
p=>q=>(o={},g=(v,t,i=2,h=j=>j?h(--j,g(j,-t)):i)=>{for(;v>1;)v%i?++i:delete o[i*!(o[h(i,v/=i)]=~~o[i]+t)]})(q,~g(p,1))||o

```

Try it online!
> 2 votes

# Answer
# Python3, 461 bytes:

```
from itertools import*
import math
def s(n=1):
 while(n:=n+1):
  if all(n%i for i in range(2,n)):yield n
r=lambda x:pow(*x[0][:-1])*(not x[1:]or r(x[1:]))
F=math.factorial
def f(n):
 q,Q=[[[],2,s()]],[]
 while q:
  p,I,v=q.pop(0)
  for i in product(*[range(-I,I)]*len(p)):
   if all(i)and p and round(r([[a,z,c]for(a,c),z in zip(p,i)]),4)==round(n,4):return' '.join(f'{b}#{j}'for(_,b),j in zip(p,i))
  q+=[[p+[[F(P:=next(v)),P]],I,s(P)],[p,I+1,s(P)],[p,I,s(P)]]

```

Try it online!

Basic brute force solution, but still runs quickly on the test cases.
> 0 votes

---
Tags: code-golf, number, primes, rational-numbers, factorial
---