title: Neural Processing Lattice Checker

text:
# Question
Title: Neural Processing Lattice Checker
Consider the following 9 "row patterns", using 0s to represent empty cells and 1s to represent a full cell. Each pattern is associated with an integer \\$n\\$, such that \\$0 \le n \le 8\\$ (multiple `[1,1,1,1,1,1]`s exist as there's some difference that we don't care about):

| \\$n\\$ | Pattern |
| --- | --- |
| 0 | `[0,0,0,0,0,0]` |
| 1 | `[1,1,1,1,1,1]` |
| 2 | `[1,1,1,1,1,1]`\[1\] |
| 3 | `[1,1,1,1,1,1]`\[1\] |
| 4 | `[1,1,0,1,1,1]` |
| 5 | `[0,1,1,0,1,0]` |
| 6 | `[1,0,0,1,0,1]` |
| 7 | `[0,1,0,0,0,0]` |
| 8 | `[0,0,0,0,1,0]` |

Given 6 integers, each of which is between \\$0\\$ and \\$8\\$ inclusive, we can use these rows to build a 6x6 square matrix. For example, consider an input of `[1,4,6,6,0,0]`. We'll start with `1` being the bottom row and the `0`s being the top 2, giving:

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

```

For each column in this matrix, we can see that every non-zero element has a "support" down to the base, i.e. no `1` has a `0` below it. However, this isn't the case for `[2,3,4,5,0,0]`:

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

```

As the third column from the left has a `0` below the top `1`, meaning that it is "unsupported".

Given 6 integers between `0` and `8` inclusive, in any reasonable format, you should output a truthy value if, in the matrix represented by these numbers, all non-zero values are supported; and a falsey value if not.

This is , so the shortest code in bytes wins.

Test cases:

```
[1,4,6,6,0,0] => valid
[2,1,2,4,7,7] => valid
[5,8,8,0,0,0] => valid
[2,0,2,0,0,0] => invalid
[2,3,4,5,0,0] => invalid

```

# Answer
# Jelly, ~~20~~ 15 bytes

```
ị“???7ȷ%Ñ£¡‘&\Ƒ

```

Try it online!

-5 bytes thanks to Lynn!

## How it works

```
ị“???7ȷ%Ñ£¡‘&\Ƒ - Main link. Takes a list of integers on the left
 “???7ȷ%Ñ£¡‘    - Integer list; [63, 63, 63, 55, 26, 37, 16, 2, 0]
ị               - For each i in the input, get the ith element of the list
              Ƒ - Is the list of numbers unchanged when doing:
             \  -   Scan by:
            &   -     Bitwise AND

```

We can avoid having to convert to binary by using bitwise AND instead of logical AND. By scanning a column (treating the numbers as binary) with a zero bit "hole" with AND, it'll overwrite it as a `1`, thus changing the number represented. If there are no holes, none of the numbers will change.
> 6 votes

# Answer
# JavaScript (ES6),  ~~45~~  43 bytes

Returns `false` for valid or `true` for invalid.

```
a=>a.some(n=>a!=n&n<'900067999'[a]&(a=n)>0)

```

Try it online!

### How?

When trying to actually process the patterns, my best attempt was **49 bytes**. It turns out that looking for invalid consecutive indices is shorter (at least in JS).

For each index \\$0\le p\le 8\\$, we generate the list of indices \\$n\\$ that cannot appear right after \\$p\\$:

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

```

It follows that \\$n\\$ is invalid iff all the following conditions are met:

* \\$p\\$ is defined
* \\$n\neq p\\$
* \\$n\neq 0\\$
* \\$n\<A\_p\\$, with \\$A=\[9,0,0,0,6,7,9,9,9\]\\$

---

# JavaScript (ES6), 58 bytes

This is a straightforward implementation of the results described above as a regex.

Expects a string of digits. Returns `false` for valid or `true` for invalid.

```
s=>/0[^0]|4[1235]|5[1-46]|6[1-578]|7[1-68]|8[1-7]/.test(s)

```

Try it online!
> 4 votes

# Answer
# Python 3, ~~73~~ 64 bytes

*Thanks to ovs for pointing what I should have seen.*

```
lambda x:all(2**i&ord("ǿ.^¾ľ"[j])for i,j in zip(x,x[1:]))

```

Try it online!

First time goling in Python a while. We store a binary matrix as a string.

This represents

\\$ M= \left\[\begin{matrix} 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\ 0 & 1 & 1 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 1 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 1 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 1 & 1 & 1 & 0 & 0 & 0 & 0 \\ 0 & 1 & 1 & 1 & 0 & 1 & 0 & 0 & 0 \\ 0 & 1 & 1 & 1 & 1 & 0 & 1 & 0 & 0 \\ 0 & 1 & 1 & 1 & 1 & 1 & 0 & 1 & 0 \\ 0 & 1 & 1 & 1 & 1 & 1 & 0 & 0 & 1 \\ \end{matrix}\right\] \\$

Where \\$M\_{i,j}\\$ is whether \\$i\\$ can be placed on top of \\$j\\$. Basically its the adjacency matrix of the underlying lattice. Then with this matrix we check all the pairs of indices and see if anything is adjacent to something it can't be.
> 3 votes

# Answer
# MATL, 22 bytes

```
63tt55' :_o'd2Ovi)Bd1<

```

Outputs a matrix containing only ones (which is truthy) or containing at least a zero (which is falsy). The footer contains a truthy/falsy test.

Try it online! Or verify all test cases.

### Explanation

The code generates the binary matrix, without any leading column of zeros (which doesn't affect the result), and computes consecutive differences vertically. The differences can be 0, 1 or −1. The input is valid if no difference equals 1.

```
63       % Push this number
tt       % Duplicate twice
55       % Push this number
' :_o'   % Push this string
d        % Consecutive differences (of ASCII codes). Gives [26 37 16]
2        % Push this number
O        % Push 0
v        % Concatenate everything into a column vector. (*)
i        % Input: numeric vector
)        % Index into (*). Indexing is 1-based and modular, so index 0
         % corresponds to the last entry
B        % Convert to binary. Gives a matrix, each original number corresponding
         % to a row. The number of columns is determined by the longest binary
         % expansion
d        % Consecutive differences, vertically
1        % Push 1
<        % Less than? Element-wise. For a valid input this gives a matrix with
         % all entries equal to true, or equivalently to 1
         % Implicit display

```
> 1 votes

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

```
n=>/^[123]*(4*6*|(4*|5*)(7*|8*))0*$/.test(n)

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 20 bytes

```
3LÛ0ÜÔ•€Â¦ŠôY∞•59вså

```

Input as a string of digits.

Port of *@tsh*'s JavaScript regex answer, so make sure to upvote him as well!

Try it online or verify all test cases.

**Explanation:**

```
3L                   # Push list [1,2,3]
  Û                  # Remove all leading 1s, 2s, and/or 3s from the (implicit) input
   0Ü                # Also remove all trailing 0s
     Ô               # Connected uniquify the remaining digits
      •€Â¦ŠôY∞•      # Push compressed integer 35401368921902082
               59в   # Convert it to base-59 as list: [4,5,6,7,8,46,47,48,57,58]
                  så # Check if the earlier integer is in this list
                     # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•€Â¦ŠôY∞•` is `35401368921902082` and `•€Â¦ŠôY∞•59в` is `[4,5,6,7,8,46,47,48,57,58]`.
> 1 votes

# Answer
# C (gcc), ~~86~~ ~~83~~ 75 bytes

```
i;r;*m=L"???7%";f(int*l){for(r=i=0;i++<5;)r|=m[*l++]&m[*l]^m[*l];i=!r;}

```

Try it online!

*Saved 8 bytes thanks to ceilingcat!!!*

Inputs a list of \\$6\\$ integers in \\$\left\[ 0,8 \right\]\\$.
Returns \\$1\\$ if valid or \\$0\\$ for invalid.
> 0 votes

# Answer
# C (gcc), 93 bytes

Here it is, not extensively tested but I think it should work!

Input is a string of 6 digits, no spaces or separators. Exit code 1 means invalid, 0 means valid

Uses (lower|upper)\>lower to test for unsupported bits.

Thanks to ceilingcat for -8 bytes!

```
b=63;char*a,d[9];main(c){for(scanf("%s",a=d);*a;b=c)(b|(c="%7???"[56-*a++]))>b?exit(1):0;}

```

Try it online!
> 0 votes

# Answer
# Charcoal, 30 bytes

```
≔ＥＳ℅§O@@@ABMGKＩιθ⬤θ∨¬κ⁼ι｜ι§θ⊖κ

```

Try it online! Link is to verbose version of code. Takes input as a string of digits and outputs a Charcoal boolean, i.e. `-` for supported, nothing for unsupported. Explanation:

```
≔ＥＳ℅§O@@@ABMGKＩιθ

```

Translate each digit to a custom bitmask, given by the bottom 4 bits of the ASCII codes of each character (the upper bits are the same for each character so they don't affect the final result).

```
⬤θ∨¬κ⁼ι｜ι§θ⊖κ

```

Check that the bitmasks represent a supported matrix.

The custom bitmasks are as follows:

```
0   1111
1   0000
2   0000
3   0000
4   0001
5   0010
6   1101
7   0111
8   1011

```

Calculation of the adjacency matrix will result in the same matrix as the original bitmasks. Note that these masks are inverted so the code uses a bitwise OR check to compensate.
> 0 votes

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


# Question
Title: Draw a hollow square of # with given width
I got this challenge from Codingame and am curious about better solutions than mine:

Given a width via standard input draw a hollow square of '#' in given width and length.

Example:

5 results in

```
#####
#   #
#   #
#   #
#####

```

I used python to solve this so i am particulary interested in other python code. But please feel free to post your solution in any language you want.

# Answer
> 12 votes
# Charcoal, 6 bytes

Code:

```
ＮβＢββ#

```

Explanation:

```
Ｎβ        # Get input from the command line and store into β
   Ｂ      # Draw a hollow box with...
     β     #  Width β
      β    #  Height β
       #   #  Filled with the character '#'
           # Implicitly output the box

```

Try it online!

# Answer
> 8 votes
# MATL, 12 bytes

```
:G\1>&*~35*c

```

Try it online!

### Explanation

```
:     % Input n implicitly. Push range [1 2 ... n]
      % STACK: [1 2 3 4 5]
G     % Push n again
      % STACK: [1 2 3 4 5], 5
\     % Modulo
      % STACK: [1 2 3 4 0]
1>    % Does each entry exceed 1?
      % STACK: [0 1 1 1 0]
&*    % Matrix with all pair-wise products
      % STACK: [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]
~     % Negate
      % STACK: [1 1 1 1 1;
                1 0 0 0 1;
                1 0 0 0 1;
                1 0 0 0 1;
                1 1 1 1 1]
35*   % Multiply by 35
      % STACK: [35 35 35 35 35;
                35  0  0  0 35;
                35  0  0  0 35;
                35  0  0  0 35;
                35 35 35 35 35]
c     % Convert to char. 0 is interpreted as space. Display implicitly
      % STACK: ['#####';
                '#   #';
                '#   #';
                '#   #';
                '#####']

```

# Answer
> 6 votes
## Python 2, ~~62~~ 54 bytes

```
f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+'\n'+'#'*n

```

Returns `#\n#` when the input is `1`

55 Bytes version that prints

```
def f(n):a=n-2;print'#'*n,'\n#%s#'%(' '*a)*a,'\n'+'#'*n

```

62 Bytes version that works for any input:

```
f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+('\n'+'#'*n)*(n>1)

```

# Answer
> 6 votes
# Jolf, 8 bytes

```
,ajj"###
,ajj      draw a box with height (input) and width (input)
    "###  with a hash border

```

# Answer
> 5 votes
# Java 7, ~~113~~ ~~112~~ 110 bytes

```
String c(int n){String r="";for(int i=n,j;i-->0;r+="\n")for(j=0;j<n;r+=i*j<1|n-i<2|n-j++<2?"#":" ");return r;}

```

1 byte saved thanks to *@OlivierGrégoire*;
2 bytes saved thanks to *@cliffroot*.

Derived solution based on my *Creating a Crossed Square* answer.

Try it here.

# Answer
> 5 votes
# COW, ~~426~~ ~~405~~ ~~348~~ 330 bytes

```
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMMMmoOMMMMoOMoOMoOMoOMoOMoOMoOMoOMoO
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMMMmoOMMMMoOMoOMoOmoOoomMMM
moOMMMMOOmOomOoMoomoOmoOMOomoomOoMMMmoOMMMMOoMOoMOOmOomOomOomOoMoo
moOmoOMoomoOMMMmoOmoOMMMMOoMOoMOOmOomOomOomOoMoomoOmoOmoOmoOMOomoo
mOomOomOoMoomoOmoOMOomoomOomOomOomOoMoomoOmoOmoOMOOmOoMoomoOMOomoo

```

Try it online! Change the number in the second line to any number to change the output.

The COW interpreter that I'm using here was written in Perl (and is newer than this challenge), but you can still get the same result by inputting the code here.

### Explanation

```
; Note: [n] means "value stored in the nth block of memory".
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoO                                                  ;Stores 10 in [0].  10 is the code point for carriage return
MMMmoOMMMMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoO     ;Stores 32 in [1].  32 is the code point for whitespace
MMMmoOMMMMoOMoOMoO                                                              ;Stores 35 in [2].  35 is the code point for #
moOoom                                                                          ;Reads STDIN for an integer, and stores it in [3]
MMMmoOMMM                                                                       ;Copies [3] into [4]
MOO                                                                             ;Loop as long as [4] is non-zero
    mOomOoMoo                                                                   ;Navigate to [2] and print the character with that code point
    moOmoOMOo                                                                   ;Navigate to [4] and decrement
moo                                                                             ;End loop
mOoMMMmoOMMMMOoMOo                                                              ;Copy [3] into [4] and decrement [4] twice
MOO                                                                             ;Loop as long as [4] is non-zero
    mOomOomOomOoMoo                                                             ;Navigate to [0] and print the character with that code point
    moOmoOMoo                                                                   ;Navigate to [2] and print the character with that code point
    moOMMMmoOmoOMMMMOoMOo                                                       ;Navigate to [3] and copy it into [5], then decrement [5] twice
    MOO                                                                         ;Loop as long as [5] is non-zero
        mOomOomOomOoMoo                                                         ;Navigate to [1] and print the character with that code point
        moOmoOmoOmoOMOo                                                         ;Navigate to [5] and decrement
    moo                                                                         ;End loop
    mOomOomOoMoo                                                                ;Navigate to [2] and print the character with that code point
    moOmoOMOo                                                                   ;Navigate to [4] and decrement
moo                                                                             ;End loop
mOomOomOomOoMoo                                                                 ;Navigate to [0] and print the character with that code point
moOmoOmoO                                                                       ;Navigate to [3]
MOO                                                                             ;Loop as long as [3] is non-zero
    mOoMoo                                                                      ;Navigate to [2] and print the character with that code point
    moOMOo                                                                      ;Navigate to [3] and decrement
moo                                                                             ;End loop

```

# Answer
> 4 votes
## PowerShell v2+, ~~48~~ 47 bytes

```
param($n)($z='#'*$n--);,("#$(' '*--$n)#")*$n;$z

```

*-1 byte thanks to JohnLBevan*

Takes input `$n`, sets `$z` as `$n` hashmarks, with `$n` post-decremented. Encapsulates that in parens to place a copy on the pipeline. Then uses the comma operator to create an array of pre-decremented `$n` lines of `#`,spaces,`#`. Those are left on the pipeline. Then places `$z` again on the pipeline. Output via implicit `Write-Output` at the end introduces a newline between elements, so we get that for free.

Since the OP's code doesn't work for input `n <= 1`, I took that to mean we don't need to support input `1`, either.

### Examples

```
PS C:\Tools\Scripts\golfing> 2..6|%{"$_";.\draw-a-hollow-square.ps1 $_;""}
2
##
##

3
###
# #
###

4
####
#  #
#  #
####

5
#####
#   #
#   #
#   #
#####

6
######
#    #
#    #
#    #
#    #
######

```

# Answer
> 4 votes
# Python 2, ~~59~~ 58 bytes

```
n=i=input()
while i:print'#%s#'%((' #'[i%n<2])*(n-2));i-=1

```

**repl.it**

Note: An input of `1` produces an output of `##`, but a *hollow* square would never be produced for an input less than `3`, so I guess this is fine.

# Answer
> 3 votes
# C, 98 bytes

```
f(n,i){i=n*(n+1);while(i--){putchar(i%(n+1)==n?10:i<n||i>n*n-1||i%(n+1)==0||i%(n+1)==n-1?35:32);}}

```

Usage:

```
f(5)

```

# Answer
> 3 votes
# 05AB1E, 20 bytes

```
'#×D¹Íð×'#.ø¹Í×sJ¹ä»

```

Try it online!

Or **18 bytes** if we can ignore `1 <= n`:

```
F„ #N¹<%_è¹Í×'#.ø,

```

Try it online!

# Answer
> 3 votes
# JavaScript, ~~61~~ 58 bytes

Saved 3 bytes thanks to @lmis!

```
n=>(b='#'[r='repeat'](n))+`
#${' '[r](n-=2)}#`[r](n)+`
`+b

```

(Doesn't handle `0` or `1`)

For 13 extra bytes (at **71 bytes**), you can!

```
n=>n?n-1?(b='#'[r='repeat'](n))+`
#${' '[r](n-=2)}#`[r](n)+`
`+b:'#':''

```

These solutions are fairly simple: they do a lot of storage to not *repeat* themselves to save a few bytes. Unminified without the variablsm it would look like:

```
n => // Anonymous function definition (Param `n` is the size)
    '#'.repeat(n) +      // # `n` times to form the top
    `
#${' '.repeat(n - 2)}#`  // Followed by a newline followed by a hash and `n` - 2 spaces and
                         // another hash to make one of the middle lines
    .repeat(n - 2) +     // The above middle lines repeated `n` - 2 times
    '#'.repeat(n)        // Followed by the top line again

```

### Try it!

```
<script type="text/babel">var f=n=>n?n-1?(b='#'[r='repeat'](n))+`\n#${' '[r](n-=2)}#`[r](n)+`\n`+b:'#':'',b,r;function c(){document.getElementById('pre').textContent = f(+document.getElementById('input').value);}</script><input id="input" onkeydown="c();" onkeyup="c();" onchange="c();" onclick="c();" placeholder="Size"><pre id="pre"></pre>
```

# Answer
> 3 votes
# WinDbg, ~~206~~ ~~200~~ ~~182~~ 170 bytes

```
.if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}

```

*-6 bytes from removing parens from `.if` and using `j` instead of second `.if`*

*-18 bytes by using `f` instead of a `.for` to construct the strings.*

*-12 bytes by not NULL-terminating strings, instead passing length to `da`*

Input is passed in through the pseudo-register `$t0` (eg `r $t0 = 5; {above-code}`).

Explanation:

```
.if @$t0                                                *Verify width($t0) at least 1
{                                                       *(registers have unsigned values)
    r $t3 = 2000000;                                    *Set $t3 to address where the
                                                        *string will be constructed
    f @$t3 L@$t0 23;                                    *Put width($t0) '#' at 2000000($t3)
    f 2 * @$t3 L@$t0 20;                                *Put width($t0) ' ' at 4000000(2*$t3)
    eb 2 * @$t3 23;                                     *Put '#' on left of ' ' string
    eb 2 * @$t3 + @$t0 - 1 23;                          *Put '#' on right of ' ' string
    da @$t3 L@$t0;                                      *Print the top of the box
    j 1 < @$t0                                          *If width($t1) at least 2
    '
        .for (r $t1 = @$t0 - 2; @$t1; r $t1 = @$t1 - 1) *Loop width($t0)-2 times to...
        {
            da 2 * @$t3 L@$t0                           *...print the sides of the box
        };
        da @$t3 L@$t0                                   *Print the bottom of the box
    '
}

```

Sample output:

```
0:000> r$t0=0
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}

0:000> r$t0=1
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x1 bytes
Filled 0x1 bytes
02000000  "#"

0:000> r$t0=2
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x2 bytes
Filled 0x2 bytes
02000000  "##"
02000000  "##"

0:000> r$t0=5
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x5 bytes
Filled 0x5 bytes
02000000  "#####"
04000000  "#   #"
04000000  "#   #"
04000000  "#   #"
02000000  "#####"

```

# Answer
> 3 votes
# Python 2, 47 bytes

Works for all `n` greater than 1.

```
lambda n:'#'*n+('#%*s'%(n,'#\n')*~-n)[n:]+'#'*n

```

Try it online!

# Answer
> 2 votes
# Python, 109 bytes

```
n=int(input())
for x in range(n):
 r=list(' '*n);r[0]=r[-1]='#'
 if x%(n-1)==0:r='#'*n
 print("".join(r))

```

# Answer
> 2 votes
# C, ~~83~~ ~~82~~ ~~80~~ ~~78~~ 77 Bytes

```
i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i*j&&i^n-1&&j^n-1?32:35));}

```

Sneak in a multiply and save a byte...

```
i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i&&j&&i^n-1&&j^n-1?32:35));}

```

Also count down j and save a few more...

```
i,j;f(n){for(i=n;i--;puts(""))for(j=0;j++<n;putchar(i&&j^1&&i^n-1&&j^n?32:35));}

```

Count down i from n to zero and save a few bytes...

```
i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i^1&&j^1&&i^n&&j^n?32:35));}

```

A bit easier to understand and 1 byte more

```
i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i==1|i==n|j==1|j==n?35:32));}

```

# Answer
> 2 votes
# Ruby, 39 bytes

```
->n{puts a=?#*n,[?#+' '*(n-=2)+?#]*n,a}

```

Turns out to be shorter this way than all the fancy stuff I was trying. Be advised that this doesn't handle 0 or 1 at all.

# Answer
> 2 votes
## Python 2, 50 bytes

```
m=input()-2
for c in'#'+' '*m+'#':print'#'+m*c+'#'

```

Works for `n>=2`. Prints each line with a pound sign, `n-2` of the appropriate symbol, then another pound sign.

Aliasing the pound symbol gives same length:

```
m=input()-2;p='#'
for c in p+' '*m+p:print p+m*c+p

```

Other attempts:

```
lambda n:'#'*n+('\n#'+' '*(n-2)+'#')*(n-2)+'\n'+'#'*n

lambda n:'#'*n+'\n#%s#'%((n-2)*' ')*(n-2)+'\n'+'#'*n

lambda n:'\n'.join(['#'*n]+['#'+' '*(n-2)+'#']*(n-2)+['#'*n])

n=input();s='#'+' '*(n-2)+'#'
for c in s:print[s,'#'*n][c>' ']

s='##'+' #'*(input()-2)+'##'
for c in s[::2]:print s[c>' '::2]

s='#'+' '*(input()-2)+'#'
for c in s:print s.replace(' ',c)

```

# Answer
> 2 votes
## Haskell, 49 bytes

```
n%b='#':(b<$[3..n])++"#\n"
f n=(n%)=<<init(n%' ')

```

Works for `n>=2`. Defines the operation of sandwiching a character between `#` for an `n`-character newline-terminated string, then applies it twice to make a 2D grid.

Call like:

```
*Main> putStrLn$ f 5
#####
#   #
#   #
#   #
#####

```

# Answer
> 2 votes
# K (ngn/k), 17 bytes

```
{"# "x*/:x#:!x-1}

```

Try it online!

Or tacit, 20 bytes:

```
" #"@|/(+|:)\^ :':=:
"# "@&/(+|:)\=':1|=:  / similar

```

Try it online!

# Answer
> 1 votes
# Groovy, ~~51~~ 50 bytes

```
{n->a="*"*n+"\n";n-=2;print(a+"*${' '*n}*\n"*n+a)}

```

# Answer
> 1 votes
# PHP, ~~81~~ 69 bytes

```
for($n=-1+$i=$argv[1];$i--;)echo str_pad("#",$n," #"[$i%$n<1]),"#\n";

```

Run with `-r`; provide input as argument.

Throws a `DivisionByZeroError` for input=`1`.

# Answer
> 1 votes
## Pyke, 11 bytes

```
ttDd*n+*.X#

```

Try it here!

```
ttDd*n+*    - a square of spaces n-2*n-2 big
        .X# - surround in `#`

```

# Answer
> 1 votes
# R, 68 ~~70~~ bytes

Works for n \> 1. Thanks to @Billywob for a couple of bytes swapping out the array for a matrix.

```
cat(rbind(b<-'#',cbind(b,matrix(' ',n<-scan()-2,n),b),b,'
'),sep='')

```

Uses rbind and cbind to put rows and columns of `#`'s around an n-2 square matrix of spaces. Newlines are bound to the rows as well. The newline in the source is significant. Input is from STDIN

# Answer
> 1 votes
# Common Lisp, ~~150~~ 130 bytes

*-20 thanks to @Cyoce and @AlexL.*

```
(defun s(v)(format t"~v,,,vA~%"v #\# #\#)(dotimes(h(- v 2))(format t"~v,,,vA~A~%"(- v 1)#\  #\# #\#))(format t"~v,,,vA"v #\# #\#))

```

Usage:

```
* (s 5)
#####
#   #
#   #
#   #
#####

```

Basically uses `format` twice for the top and bottom and a loop for the rows in between. The format call for the top and bottom outputs a line starting with `#` and padded to the appropriate width with `#`s. The format call for the rows in between works similarly, except the padding is spaces and a `#` gets printed at the end of the line.

Note: I'm rather new to Lisp and expect to have a lot of room for improvement on this.

# Answer
> 1 votes
# Dyalog APL, 20 bytes

```
{' #'[1+∘.∨⍨1⍵∊⍨⍳⍵]}

```

Try it online!

This is an improved version on my first attempt suggested by dzaima on the APL Orchard, so all credit goes to him.

Takes an integer n as input. Using 5 as an example:

```
                ⍳⍵   integers from 1 to n
                      1 2 3 4 5
            1⍵∊⍨     check whether each integer is 1 or n
                      1 0 0 0 1
        ∘.∨⍨         generate all possible pairs of the
                     0s and 1s in a matrix, or'ing each pair:
                      ∨ | 1 0 0 0 1
                      --+----------
                      1 | 1 1 1 1 1
                      0 | 1 0 0 0 1
                      0 | 1 0 0 0 1
                      0 | 1 0 0 0 1
                      1 | 1 1 1 1 1
      1+             add 1 to each number
                      2 2 2 2 2
                      2 1 1 1 2
                      2 1 1 1 2
                      2 1 1 1 2
                      2 2 2 2 2
 ' #'[            ]  turn 1 into space (the first character)
                     and 2 into # (the second character)

```

# Answer
> 0 votes
## Python 2, ~~60~~ ~~65~~ ~~69~~ ~~62~~ 61 bytes

```
x=input();h='#';print h*x+'\n'+(h+' '*(x-2)+h+'\n')*(x-2)+h*x

```

My first attempt at this problem, I will golf it down hopefully.

*+5 bytes* I forgot to put newlines between the lines :(
*+4 bytes* I forgot to add 2 to the last `x` :(
*-7 bytes* If I don't subtract 2 from the input at the beginning and subtract it where it would make sense to do so, I can actually save 7 bytes :)
*-1 byte* Thanks to @Cyoce for helping me save 1 byte by assigning `'#'` to a variable (which I called `h` because that's what he was thinking in the comments :P)

Still 1 byte longer than before... :(

# Answer
> 0 votes
## Haskell, 67 bytes

```
l#n=l<$[1..n]
f n=unlines$'#'#n:('#':' '#(n-2)++"#")#(n-2)++['#'#n]

```

Usage example:

```
Prelude> putStrLn $ f 4
####
#  #
#  #
####

```

How it works:

```
l#n=l<$[1..n]                      -- helper function that makes n copies of l

   '#'#n                           -- make a string of n copies of #, followed by
                        #(n-2)     -- n-2 copies of
     '#':' '#(n-2)++"#"            -- # followed by n-2 times spaces, followed by #
                           ['#'#n] -- and a final string with n copies of #
unlines                            -- join with newlines in-between

```

# Answer
> 0 votes
# Jelly, 13, bytes

```
,þ%µỊṀ€€ị⁾# Y

```

**TryItOnline!** or try 0 to 15

### How?

```
,þ%µỊṀ€€ị⁾# Y - Main link: n
 þ            - outer product with
,             -    pair:   [[[1,1],[2,1],...,[n,1]],[[1,2],[2,2],...,[n,2]], ... ,[[1,n],[2,n],...,[n,n]]]
  %           - mod n:     [[[1,1],[2,1],...,[0,1]],[[1,2],[2,2],...,[0,2]], ... ,[[1,0],[2,0],...,[0,0]]]
   µ          - monadic chain separation
    Ị         - abs(z)<=1: [[[1,1],[0,1],...,[1,1]],[[1,0],[0,0],...,[1,0]], ... ,[[1,1],[0,1],...,[1,1]]]
      €€      - for each for each
     Ṁ        - maximum:   [[1,    1,    ...,1],    [1,    0,    ..., 1],    ... ,[1,    1,    ..., 1]   ]
        ị     - index into (1 based)
         ⁾#   - "# ":      ["##...#","# ...#", ...,"##...#"]
           Y  - join with line feeds

```

# Answer
> 0 votes
## Racket 113 bytes

```
(let*((d display)(g(λ()(for((i n))(d"#")))))(g)(d"\n")(for((i(- n 2)))(d"#")(for((i(- n 2)))(d" "))(d"#\n"))(g))

```

Ungolfed:

```
(define (f n)
  (let* ((d display)
         (g (λ ()
              (for ((i n))
                (d "#"))
              (d "\n"))))
    (g)
    (for ((i (- n 2)))
      (d "#")
      (for ((i (- n 2)))
        (d " ") )
      (d "#\n"))
    (g)))

```

Testing:

```
(f 5)

```

Output:

```
#####
#   #
#   #
#   #
#####

```

# Answer
> 0 votes
## Pip, 16 bytes

15 bytes of code, +1 for `-n` flag.

```
(Y_Xa-2WR'#s)My

```

Works for input \>= 2. Try it online!

### Explanation of somewhat ungolfed version

First, we define a function `y` that takes a string argument, repeats it `a-2` times (where `a` is the first command-line input), and wraps the result in `#`.

```
Y _ X a-2 WR '#
  _              Identity function
    X a-2        String-repeated by a-2
          WR '#  Wrapped in #
Y                Yank the resulting function into y

```

Next, we apply this function twice--once normally, then again with map--to obtain the square as a list of strings:

```
y M (y s)
    (y s)  Call function y with s (preinitialized to " ") as argument
y M        Map y to each character of the resulting string

```

For input of `4`, `(y s)` results in `"# #"` and `y M (y s)` in `["####"; "# #"; "# #"; "####"]`. This latter value is then printed, with the `-n` flag causing it to be newline-separated.

### Golfing tricks

To get from the ungolfed to the golfed version:

* Remove spaces.
* `Y` is an operator, which means we can use it in an expression. Instead of `Y...` followed by `(ys)`, we can just do `(Y...s)`.
* The problem is, we have to yank the function before we reference it again as `y`; so `yM(Y_Xa-2WR'#s)` won't work. Solution: swap the operands of the `M`ap operator. As long as one of them is a function and the other is an iterable type, it doesn't matter what order they come in.

# Answer
> 0 votes
# C#, ~~154~~ 152 bytes

Golfed:

```
void F(int n){Console.Write($"{new string('#',n)}\n");for(int i=2;i<n;i++)Console.Write($"#{new string(' ',n-2)}#\n");Console.Write(new string('#',n));}

```

Ungolfed:

```
    void F(int n)
    {
        Console.Write($"{new string('#', n)}\n");

        for (int i = 2; i < n; i++)
            Console.Write($"#{new string(' ', n - 2)}#\n");

        Console.Write(new string('#', n));
    }

```

EDIT1: Loop range optimization.

# Answer
> 0 votes
# SpecBAS - 57 bytes

```
1 INPUT n: a$="#"*n,n-=2,b$="#"+" "*n+"#"#13: ?a$'b$*n;a$

```

`?` is shorthand for `PRINT`, `#13` is carriage return which can be tacked on to the end of a string without needing a `+` to join them.

The apostrophe moves print cursor down one line.

# Answer
> 0 votes
# Stuck, ~~29~~ 27 Bytes

Pretty darn long for a "golfing" language, but I have forgotten how a lot of it works :P

```
i_2-_u'#*N+_'#' u*'#N+++u*u

```

Explanation:

```
i_2-_u                           # take input and triplicate, subtracting 2 (5 -> [3,3,5])
      '#*N+_                     # create the top and bottom rows
            '#' u*'#N+++u*       # create input - 2 copies of middle rows
                          u      # rotate left 1 to get correct order, implicit output

```

# Answer
> 0 votes
## Lithp, 117 bytes

Line split in two for readability:

```
#N::((var X (repeat "#" N))(print X)(each (seq 3 N) (scope #X::((print (+ "#"
     (repeat " " (- N 2)) "#")))))(print X))

```

Sample usage:

```
% square.lithp
(
    (import "lists")
    (def s #N::((var X (repeat "#" N))(print X)(each (seq 3 N) (scope #X::((print (+ "#" (repeat " " (- N 2)) "#")))))(print X)))
    (s 10)
)

Output:
$ ./run square.lithp
##########
#        #
#        #
#        #
#        #
#        #
#        #
#        #
#        #
##########

```

# Answer
> 0 votes
## dc, 83 bytes

```
?sd0[1+[#]Pdld>k]sklkx0[1+[
]P0[#]P[1+[ ]Pdld2->x]sxlxxk[#]Pdld2->r]srld2<r[
]P0lkx

```

This is mostly straightforward. It's kinda late so I won't write up an explanation now, but I might edit one in later.

(Note: I'm new to `dc` so there are probably obvious improvements to be made here.)

# Answer
> 0 votes
## Python 2, 92 bytes

```
def f(j):r=range(j);print'\n'.join(''.join(' #'[x*y<1or max(x,y)==j-1]for y in r)for x in r)

```

# Answer
> 0 votes
# ForceLang, ~~316~~ 314 bytes

```
def s set
s n io.readnum()
s g goto
def w io.write "#"
s W io.writeln
if n=0
g 3
if n=1
g 4
label 0
if i=n
g 1
s i 1+i
w
g 0
label 1
s i 0
s m n+-2
W()
label a
if i=m
g b
s i 1+i
s j 0
w
label c
if j=m
g d
s j 1+j
io.write " "
g c
label d
W "#"
g a
label b
s i 0
label 2
if i=n
g 3
s i 1+i
w
g 2
label 4
w
label 3

```

# Answer
> 0 votes
## T-SQL 351 bytes

This is so wrong... but anyway:

```
DECLARE @ INT=1,@n INT=10,@a VARCHAR(MAX),@b VARCHAR(MAX),@c CHAR='#',@s VARCHAR(MAX)=''WHILE @<=@n BEGIN SET @a=concat(@a,@c)SET @b=concat(@b,(SELECT CASE WHEN @=1THEN @c WHEN @=@n THEN @c ELSE' 'END))SET @=@+1 END SET @=1 WHILE @<=@n BEGIN SET @s=@s+(SELECT CASE WHEN @=1THEN @a WHEN @=@n THEN CHAR(13)+@a ELSE CHAR(13)+@b END)SET @=@+1 END PRINT @s

```

Ungolfed:

```
DECLARE     @ INT=1,
            @n INT=10,
            @a VARCHAR(MAX),
            @b VARCHAR(MAX),
            @c CHAR='#',
            @s VARCHAR(MAX)=''
WHILE @<=@n
BEGIN
    SET @a=concat(@a,@c)
    SET @b=concat(@b,(SELECT CASE WHEN @=1THEN @c WHEN @=@n THEN @c ELSE' 'END))
    SET @=@+1;
END
SET @=1
WHILE @<=@n
BEGIN
    SET @s=@s+
    (SELECT
        CASE
            WHEN @=1THEN @a
            WHEN @=@n THEN CHAR(13)+@a
            ELSE CHAR(13)+@b
        END
    )
    SET @=@+1
END
PRINT @s

```

# Answer
> 0 votes
# BrainF\***, 152 bytes

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

```

Hopefully this can be golfed a bit more.

Explanation:

```
+++++[>++>+++++++<<-]           Initializes to [0, 10, 35]. 10 is the charcode for a newline, 35 is the charcode for '#'
,                               Gets the input (as an ASCII char, which is converted to an integer)
[>>>+>+>+>+<<<<<<-]             Copies the input to 4 different spaces
>>>>[-<<.>>]                    Prints the appropriate number of '#'
++++[>>>++++++++<<<-]           Puts 32 in the next available space (32 is the charcode of a space)
>--<<--                         Subtracts 2 from one of the input values and the value on which to loop
[
  <<.>.>>>                      Print a newline and a '#'
  [>>.<<-]                      Print n - 2 spaces
  <<<.>->>>                     Print another '#'
  [<+<+>>-]<<[>>+<<-]>--<<      Copy n to two other spaces, then copy it back
]
<<.>>>>>                        Print a newline
[<<<<.>>>>-]                    Print the appropriate number of '#'

```

Try it here (visualizer) or here (repl)

# Answer
> 0 votes
# Ruby, 66 bytes

```
n=gets.to_i
puts ?#*n
if n>1
puts [?#+' '*(n-2)+?#]*(n-2),?#*n end

```

# Answer
> 0 votes
# Common Lisp, SBCL, ~~64~~ 63 bytes

```
(format t"#~v@{#~}#
~@*~v@{~@*#~v@t#
~}~@*#~v{#~}#"(-(read)2)1)

```

For n=1 will give:

```
##
##

```

but I guess it's ok, since author's solution doesn't seem to work for n=1 (tested here but maybe it's because it's other Python version?)

Other than that it should work fine.

### Explanation

```
format  ;printing function
~v@{#~} ;loop n times, where n equals current argument
        ;printing "#" - gives n "#"s
~@*     ;go back to first argument - reuse (-(read)2)
~v@t    ;add n spaces where n is current argument

```

# Answer
> 0 votes
# Charcoal, 3 bytes

```
ＢＮ#

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 6 bytes

```
'#Ž9¦Λ

```

Try it online!

```
'#Ž9¦Λ  # full program
     Λ  # draw lines of length...
        # implicit input...
     Λ  # made from...
'#      # literal...
     Λ  # s with directions in [N, NE, E, SE, S, SW, W, NW] with indices in each character in...
  Ž9¦   # 2460
        # implicit output

```

# Answer
> 0 votes
# Dyalog APL, ~~31~~ ~~29~~ ~~24~~ 23 bytes

Tacit Function that takes number of lines as argument, returns hollow square

`(' #'⌷⍨1∘+)¨(∘.∨⍨⍳∊1∘,)`

## Output (for argument 10)

```
    (' #'⌷⍨1∘+)¨(∘.∨⍨⍳∊1∘,) 10
##########
#        #
#        #
#        #
#        #
#        #
#        #
#        #
#        #
##########

```

# Answer
> 0 votes
# Vyxal `Rj`, 15 bytes

```
₌Ẋ‹%ƛ1c\#*ð∨;∑²

```

Try it Online!

I'm actually proud of this answer, because it took a bit of thinking and effort to obtain.

## Explained

```
₌Ẋ‹%ƛ1c\#*ð∨;∑²
₌Ẋ‹             # Push cartesian_product(range(1, input + 1), range(1, input + 1)), input - 1
   %            # modulo those
    ƛ       ;   # over each item X:
     1c         #    does X contain 1?
       \#*      #    repeat "#" that many times
          ð∨    #    and logical or with space
            ∑²  # join into a single string and format as a grid

```

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


title: Find the sliced sheet of paper

text:
# Question
Title: Find the sliced sheet of paper
# Context :

Suppose you have a sheet of paper measuring `8 x 10`. You want to cut it exactly in half while maintaining its rectangular shape. You can do this in two ways.

* You can cut it in half preserving its long dimension of 10 (for our purpose we will refer to this as long cut from now on).

Example : $$ \[8, 10\] \rightarrow {long cut} \rightarrow \[4, 10\] $$ Or you can cut it in half preserving its short dimension (we will refer to it as short cut).

Example :

$$ \[8,10\]→short cut→\[5,8\] $$

For a square, the short and long cut are same. i.e : $$ \[12,12\]→long cut→\[6,12\] $$ $$ \[12,12\]→short cut→\[6,12\] $$

# Task :

For this challenge you are given two arguments.

* The first is a string containing the cuts to be made to a sheet of paper in sequence from first to last. A long cut is designated by "L" and a short cut by "S".
* The second is dimension of paper after said cuts were made (an array)

Given that devise a function that will find the all the possible original dimensions of the sheet of paper before any cuts were made.

The dimensions of a sheet are given as an array `[x,y]` (\\$y\geq x\\$)

Return all possible orignial paper measures : `[x, y]` for (\\$y\geq x\\$)

If input make it so that an output is not possible return a falsey value (be it empty array , false, 0, empty string, nil/null/Null). You may not give an error though

# Examples :

```
cuttingPaper("S", [3, 7])      --> [[3, 14]]
cuttingPaper("L", [5, 7])      --> []
cuttingPaper("", [3, 7])       --> [[3, 7]]
cuttingPaper("S", [5, 7])      --> [[5, 14], [7, 10]]
cuttingPaper("LSSSSS", [1, 2]) --> [[2, 64], [4, 32], [8, 16]]

```

# Explanation :

### For example 2 :

`L` for `[5, 7]` gives empty array since if it started `[5, 14]` then the long cut would result in `[2.5, 14]` and if it started with `[10, 7]` then the long cut would result in `[10, 3.5]`. so in this case the cut is simply not possible

### For example 4 :

`[5, 7]` for `S` cut gives 2 solutions since it could start as `[5, 14]` and then short cut would yield `[5, 7]` which is possible solution 1.

Alternately you can start with `[7, 10]` and then cut and you would end up with `[5, 7]` which is possible solution 2. B

ecause of that you get 2 possible solutions. (you output both)

**In such a case you will return an array of array / list of list / etc...**

# I/O :

You take 2 inputs :

* A String containing the cuts made.
* The array after said cuts were made

You can take it as the following :

* an array/set (or equivalents) containing 3 inputs (in following order `[cuts, x, y]` or `[x, y, cut]`
* Three inputs `cut, x, y` or `x, y, cut`
* 2 input `cut, [x, y]` or `[x, y], cut`
* A string consisting of all 3 `cuts x y` (space seperated, you may choose your separator)

# Notes :

* The string will either be empty or contain some combination of S and/or L.
* The array will always contain two Positive integers.
* This is code-golf so shortest answer in bytes will win (note : I won't be selecting any answer as accepted).
* Standard loopholes apply.

For those that solve it kindly if you can give a small explanation so others (mainly me) can learn/understand your code (if you have the time and patience)

# Answer
# Python 3.8, ~~115~~ 110 bytes

```
f=lambda s,d:{k for a,b in[d,d[::-1]]if(x:=(2*a,b)[::s[-1]<'S'or-1])[0]<=x[1]for k in f(s[:-1],x)}if s else{d}

```

Try it online!

---

# Python 3.8, 104 bytes

Takes some inspiration from Arnauld's answer.

```
f=lambda s,d:s==''!=print(d)or[f(s[:-1],x)for a,b in{d,d[::-1]}if(x:=(2*a,b)[::s[-1]<'S'or-1])[0]<=x[1]]

```

Try it online!
> 6 votes

# Answer
# JavaScript (V8),  ~~94~~  91 bytes

Expects `(list, width, height)`, where `list` is either a string or an array of characters. Prints the solutions.

```
f=([...c],w,h)=>c+c?c.pop(W=w*2)>"L"?f(c,w,h*2,W<h|w==h||f(c,h,W)):W>h||f(c,W,h):print(w,h)

```

Try it online!

### How?

Given an operation and the resulting dimensions \\$(w,h)\\$ (with \\$w\le h\\$), we look for the possible solutions for the original dimensions.

If the operation was a long cut:

* If \\$2w\le h\\$, the only possible solution is \\$(2w,h)\\$. Otherwise, this is invalid.

If the operation was a short cut:

* \\$(w,2h)\\$ is always a solution.
* If \\$2w\ge h\\$, \\$(h,2w)\\$ is another solution.
* If \\$w=h\\$, both solutions are identical so we make sure to try only one of them to avoid duplicate results.

We attempt to apply these rules, starting with the last operation and going backwards. Whenever we successfully process the entire chain, we print the final result.
> 6 votes

# Answer
# 05AB1E, 19 bytes

Takes `[x, y]` on the first and the (unquoted) cut sequence on the second line.

```
¸sRv€ÂÙ€ƶyCÉií}ʒD{Q

```

Try it online!

```
¸                    # wrap the pair into a list [[x,y]]
 sR                  # swap to the string and reverse it
   v                 # for each character y in the reversed string:
    €Â               #   extend the list by all pairs reversed
      Ù              #   remove duplicate pairs
       €ƶ            #   "Lift" each pair; multiply first element by 1, second by 2
         yCÉ         #   is y equal to 'L'?
            ií}      #   if so, reverse each pair
               ʒ     #   only keep resulting pairs, that are ...
                D{Q  #     equal when sorted

```
> 4 votes

# Answer
# Charcoal, ~~73~~ 43 bytes

```
⊞υＥ²ＮＦ⮌Ｓ≔ΦＥ⁺υＥυ⮌κＥκ×μ⊕⁼ν⁼ιS¬›⁰↨κ±¹υＩΦυ⁼κ⌕υι

```

Try it online! Link is to verbose version of code. Takes `x`, `y`, `cuts` on separate lines and outputs pairs of `x`, `y` on separate lines with double-spacing between each pair. Explanation: Now inspired by @ovs's answer.

```
⊞υＥ²Ｎ

```

Push the target pair to the predefined empty list.

```
Ｆ⮌Ｓ

```

Loop over the cuts in reverse order.

```
≔ΦＥ⁺υＥυ⮌κＥκ×μ⊕⁼ν⁼ιS¬›⁰↨κ±¹υ

```

Take the list of sizes and reverse each size. Take both lists and double either the width or length depending on the cut. Filter out those sizes where the width is larger than the length.

```
ＩΦυ⁼κ⌕υι

```

Deduplicate and output the final sizes.
> 0 votes

---
Tags: code-golf, geometry
---


title: Parentheses Clusters

text:
# Question
Title: Parentheses Clusters
Write a program that groups a string into parentheses cluster. Each cluster should be balanced.

### Examples :

```
split("((())d)") ➞ ["((()))"]

split("(h(e(l)l)o)(w(o)r)l(d)(w)h(a(t)(s)u)p") ➞ ["((()))", "(())", "()", "()", "(()())"]

split("((())())(()(()()))") ➞ ["((())())", "(()(()()))"]

```

Input may contain letters other than parentheses but you are not sorting them. (The possible characters in the input are uppercase and lowercase letters, numbers, and `()`)

Given parentheses will always be complete (i.e : `(` will be matched with `)` )

Cluster is when outermost `(` ends with `)`. In short when your parentheses are all balanced at that moment so :

```
(((    ---> this will be balanced when 3 ) are added
)))    ---> now its balanced this is cluster 1
()     ---> this is cluster 2
(((((((((((((((((((((((((((((( ---> this is start of cluster 3. will need equal amount of ) to balance

```

This is code-golf, shortest code wins

(Link to challenge on Code Wars : link for those that wish to check it)

# Answer
# Vim, 20 bytes

```
:s/\w//g
qq%a
<Esc>@qq@q

```

Try it online!

Programmer's text editor builtins ftw! \o/

Explanation:

```
:s/\w//g    # Remove all letters and numbers
qq          # Start macro 'q'
  %a        #  Jump to matching parenthesis and insert newline
<Esc>
     @q     #  Call macro 'q'
       q    #  End macro 'q'
        @q  # Call macro 'q'

```
> 10 votes

# Answer
# , 35 bytes

```
(](]<;.2~0=[:+/\_1+2*i.)[-.-.)&'()'

```

Try it online!

* Remove all parens from the input.
* Turn `(` into -1 and `)` into 1, and take the scan sum, then convert that into a mask which is 1 wherever the sum is 0.
* Finally, use that mask to cut the cleaned input into chunks.
> 6 votes

# Answer
# Jelly, 11 bytes

```
fØ(µO-*Ä¬Ṗk

```

Try it online!

The Footer just runs all the test cases, joins each cluster by a single newline and each test case by 2.

## How it works

```
fØ(µO-*Ä¬Ṗk - Main link. Takes a string S on the left
fØ(         - Remove all non-"()" characters
   µ        - Use this string of parentheses P as the argument from here:
    O       - Convert to ords ("(" -> 40, ")" -> 41)
     -*     - Raise -1 to that power, yielding "(" -> 1, ")" -> -1
       Ä    - Cumulative sum
        ¬   - Logical NOT, converting 0 -> 1, everything else -> 0
         Ṗ  - Remove the trailing 1
          k - Split P at the indices of the 1s

```
> 6 votes

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

```
{⍵⊂⍨¯1⌽0=+\¯1*')'=⍵}∩∘'()'

```

Try it on APLgolf! or Try it with step by step output

`∩∘'()'` intersect right argument with `()`. This removes all other characters.
`{ ... }` call the dfn with the cleaned string as its right argument .

`')'=⍵` for each character in the string, is it equal to `)`?
`¯1*` this maps `(` to 1 and `)` to ¯1.
`+\` cumulative sums. This is the nesting level for each character.
`0=` equal to 0?
`¯1⌽` rotate the trailing 1 to the front.
`⍵⊂⍨` partition the string at characters with nesting level 0.
> 4 votes

# Answer
# Python 3, 75 bytes

```
def f(s,x=1):
 for i in s:y=(i==")")-(i=="(");x+=y;y and print(i,end=" "*x)

```

Try it online!

prints the clusters separated by spaces

# Python 3, 88 bytes

```
def f(s,x=1,w=""):
 for i in s:y=(i==")")-(i=="(");x+=y;w+=y*y*i+" "*x
 return w.split()

```

Try it online!

returns a list of clusters
> 4 votes

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

```
A=>[...A.replace(/[^()]/g,(o=0,t=''))].map(l=>(t+=l,!(o+=l<")"||-1)&&t+(t="")||""))

```

Try it online!

If it accepts array having `,` in between parentheses otherwise :

# JavaScript (Node.js), ~~101~~ ~~100~~ 95 bytes

```
A=>[...A.replace(/[^()]/g,(o=0,a=[],t=''))].map(l=>(o+=l<")"||-1,t+=l,!o&&a.push(t+(t=''))))&&a

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~18~~ ~~17~~ 14 bytes

```
žuÃDÇÈ·<.¥_Å¡¦

```

-1 byte because of the rule change from all printable ASCII to just parenthesis and alphanumeric characters in the input
-3 bytes and improved performance thanks to *@cairdCoinheringaahing*

Output as a list of list of characters.

Try it online or verify all test cases.

**Explanation:**

```
žu              # Push constant string "()<>[]{}"
  Ã             # Only keep those characters from the (implicit) input-string
   D            # Duplicate this string
    Ç           # Convert each character in the copy to its unicode integer:
                #  "("→0; ")"→1
     É          #  Check for each whether it's odd: "("→0; ")"→1
      ·         #  Double each: "("→0; ")"→2
       <        #  Decrease each by 1: "("→-1; ")"→1
        .¥      #  Undelta this list
          _     #  Check for each whether it's equal to 0 (1 if 0; 0 otherwise)
           Å¡   # Split the string we've duplicated at the truthy indices,
                # which implicitly converts the parts to character-lists
             ¦  # And remove the leading empty list
                # (after which the result is output implicitly)

```
> 3 votes

# Answer
# JavaScript (ES6),  ~~61 60~~  59 bytes

*Saved 1 byte thanks to @tsh*

Outputs a string with one cluster per line.

```
s=>s.replace(/./g,c=>c=='('?(s=-~s,c):c==')'?--s?c:`)
`:'')

```

Try it online!
> 3 votes

# Answer
# Japt v2.0a0, ~~15~~ ~~13~~ 12 bytes

```
r\w ó@T±JpXc

```

Try it

```
r\w ó@T±JpXc     :Implicit input of string U
r                :Replace
 \w              :  RegEx /[a-z0-9]/gi
    ó            :Partition after each character X
     @           :That returns falsey (0) when passed through the following function
      T±         :  Increment T (initially 0) by
        J        :  -1
         p       :  Raised to the power of
          Xc     :  Charcode of X

```
> 3 votes

# Answer
# Java 8, ~~89~~ ~~82~~ 81 bytes

```
s->{int t=0;for(var c:s)System.out.print(c==40?++t>0?c:c:c==41?--t<1?") ":c:"");}

```

-7 bytes thanks to *@ZaelinGoodman*

Input as character-array; output as a space-delimited string.

Try it online.

**Explanation:**

```
s->{                   // Method with character-array as parameter and no return
  int t=0;             //  Create a temp integer, starting at 0
  for(var c:s)         //  Loop over the characters of the input-array:
    System.out.print(  //   Print:
      c==40?           //    If the current character is '(':
        ++t            //     Increase `t` by 1
        >0?c:c         //     And print the '('
      :c==41?          //    Else-if the current character is ')':
        --t            //     Decrease `t` by 1
           <1?         //     If it is now 0:
              ") "     //      Print the ')', plus a space
             :         //     Else (it's not 0):
              c        //      Print just the ')'
      :                //    Else (it's a different character):
       "");}           //     Print nothing

```
> 3 votes

# Answer
# Pip, ~~28~~ ~~25~~ ~~24~~ 23 bytes

```
Fca@X^pI$==_NyPBcMpY/Py

```

Try it here! Or, with a variable definition in the header, you can also Try it online!

### Explanation

Pushes one parenthesis at a time onto `y`, checks whether `y` is balanced, and if so, outputs and resets it.

```
Fca@X^pI$==_NyPBcMpY/Py
                         a is cmdline arg; p is "()"; y is "" (implicit)
Fc                       For each character c in
  a@                     each regex match in a of
    X                    a regex matching
     ^                   either of the characters in
      p                  "()":
       I                  If
             yPBc         we push c onto the end of y
           _N             and then the number of occurrences in y of
                 Mp       each character in "()"
        $==               is equal:
                     Py    Print y
                    /      and invert (resulting in nil because y isn't a number)
                   Y       and yank that as the new value of y

```

This works because pushing a string onto a variable that is nil sets the variable to the pushed string, the same as if the variable's value had been `""`.
> 3 votes

# Answer
# Java (JDK), ~~86~~ ~~80~~ 79 bytes

```
n->{int o=0;for(var c:n)if(o!=(o+=c>41?0:81-2*c))System.out.print(o<1?") ":c);}

```

Try it online!

-7 thanks to Kevin Kruijssn and Zaelin Goodman!
> 3 votes

# Answer
# Ruby, 37 bytes

```
->s{s.tr('^()','').scan /\(\g<0>*\)/}

```

Try it online!

Returns an array of clusters. The numbered subpattern `\g<0>` nests the balanced-parentheses-matching regex within itself.
> 3 votes

# Answer
# PowerShell Core, 89 80 bytes

-9 bytes thanks to @mazzy!!!

```
$args-replace"\w"|sls "(\((?=\(*(?<S>\)))|\k<S>(?<-S>))+?(?(S)(?!))"-a|% M*|% V*

```

Try it online!
> 2 votes

# Answer
# C (gcc), 70 bytes

I think at this point I have to admit I'm on a ternary operator abuse spree.

Big thanks to ErikF for -14 bytes.

And thanks the ceilingcat for -4 more!

```
c;f(d){for(d=0;read(0,&c,1);c>47||(d+=2*putchar(c)-81)||putchar(32));}

```

Try it online!
> 2 votes

# Answer
# , ~~99~~ 92 bytes

Or **\>=4.1, 85 bytes** by replacing the word `function` with `\`.

*-7 bytes thanks to @Dominic van Essen.*

```
function(s,x=utf8ToInt(s))Map(intToUtf8,split(a<-x[x<42],head(diffinv(!cumsum(a*2-81)),-1)))

```

Try it online!

As always,  is terrible in string challenges...
> 2 votes

# Answer
# JavaScript, ~~55~~ 53 bytes

Outputs a space delimited string with a trailing space.

```
s=>s.replace(/./g,x=>x>{}?``:(n+=x>s||-1)?x:`) `,n=0)

```

Try it online!
> 2 votes

# Answer
# Perl 5, 26 bytes

```
y/()//cd;s/\((?R)*\)/$&
/g

```

Try it online!

```
y/()//cd;           #delete all chars from input line except ( and )
s/\((?R)*\)/$&      #print clusters separated by newline
/g                  #found by recursive regexp with (?R)

```
> 2 votes

# Answer
# PowerShell, 62 bytes

```
switch($args){'('{$r+=$_;++$l}')'{$r+=$_;if(!--$l){$r;$r=''}}}

```

Try it online!
> 2 votes

# Answer
# Lua, 46 bytes

```
print(arg[1]:gsub("%w",""):gsub("%b()","%1;"))

```

Try it online!

Looks like it happened working. Though I don't know much about Lua.
> 1 votes

# Answer
# Retina 0.8.2, 25 bytes

```
\w

!`\(((\()|(?<-2>.))*.

```

Try it online! Link includes test cases. Explanation: The first two lines simply delete letters and digits. The final line matches groups of (assumed) parentheses. .NET balancing groups keep track of the number of unmatched `(`s and don't allow more `)`s than `(`s. This means that the inner loop stops when it reaches the matching `)` for the outer `(`. The `!` causes the groups themselves to be output on separate lines.
> 1 votes

# Answer
# Charcoal, 19 bytes

```
ＦＳ≡ι(«ι⊞υυ»)«ι¿¬⊟υ⸿

```

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

```
ＦＳ≡ι

```

Switch over each character of the input string.

```
(«ι⊞υυ»

```

If it's a `(` then print it and push the predefined empty list to itself. The list therefore contains itself as many times as there are unbalanced `(`s.

```
)«ι

```

If it's a `)` then print it, and...

```
¿¬⊟υ⸿

```

... if popping the list leaves it empty again then move to the next line.
> 1 votes

---
Tags: code-golf, string, parsing, balanced-string
---