# Question
Title: Does this Set Represent a Natural Number?
In set theory, the natural numbers \\$\mathbb{N} = \\{0, 1, 2, 3, ...\\}\\$ are usually encoded as pure sets, that is sets which only contain the empty set or other sets that are pure. However, not all pure sets represent natural numbers. This challenge is about deciding whether a given pure set represents an encoding of natural number or not.

The encoding of natural numbers works in the following way1:

* Zero is the empty set: \\$ \text{Set}(0) = \\{\\} \\$
* For a number \\$n \> 0\\$: \\$ \text{Set}(n) = \text{Set}(n-1) \cup \\{\text{Set}(n-1)\\}\\$

Thus, the encodings of the first few natural numbers are

* \\$ 0 \leadsto \\{\\}\\$
* \\$ 1 \leadsto \\{0\\} \leadsto \\{\\{\\}\\}\\$
* \\$ 2 \leadsto \\{0,1\\} \leadsto \\{\\{\\},\\{\\{\\}\\}\\}\\$
* \\$ 3 \leadsto \\{0,1,2\\} \leadsto \\{\\{\\},\\{\\{\\}\\},\\{\\{\\},\\{\\{\\}\\}\\}\\}\\$
* \\$ 4 \leadsto \\{0,1,2,3\\} \leadsto \\{\\{\\},\\{\\{\\}\\},\\{\\{\\},\\{\\{\\}\\}\\},\\{\\{\\},\\{\\{\\}\\},\\{\\{\\},\\{\\{\\}\\}\\}\\}\\}\\$

## The Task

* Given a string representing a pure set, determine whether this set encodes a natural number according to the above construction.
* Note, however, that the elements of a set are not ordered, so \\$\\{\\{\\},\\{\\{\\}\\},\\{\\{\\},\\{\\{\\}\\}\\}\\}\\$ is not the only valid representation of \\$3\\$ as e.g. \\$\\{\\{\\{\\}\\},\\{\\},\\{\\{\\{\\}\\},\\{\\}\\}\\}\\$ represents the same set.
* You may use `[]`, `()` or `<>` instead of `{}`.
* You may assume the sets are given without the `,` as separator.
* You can assume there won't be any duplicate elements in the input, e.g. `{{},{}}` is not a valid input, and that the input is well-formed, e.g. no `{{},`, `{,{}}` or similar.

## Test Cases

True:

```
{}
{{}}
{{},{{}}}
{{{}},{}}
{{},{{}},{{},{{}}}}
{{{},{{}}},{},{{}}}
{{{{}},{}},{{}},{}}
{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}}
{{{{{}},{}},{{}},{}},{{}},{},{{},{{}}}}
{{},{{}},{{},{{}},{{},{{}}},{{},{{}},{{},{{}}}}},{{{}},{}},{{},{{}},{{},{{}}}}}
{{{{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}}

```

False:

```
{{{}}}
{{{{}}}}
{{{{}},{}}}
{{},{{}},{{{}}}}
{{{},{{}}},{{}}}
{{{{{}}},{}},{{}},{}}
{{},{{}},{{},{{}}},{{},{{}},{{{}}}}}
{{{{{}},{}},{{{}}},{}},{{}},{},{{},{{}}}}
{{{{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}},{{{{{}},{}},{{}},{}},{{{}},{}},{{}}},{{{{}},{}},{{}},{}},{{{}},{}},{{}},{}}

```

---

Related: Natural Construction (Output the set encoding of a given natural number.)
1 See https://en.wikipedia.org/wiki/Set-theoretic\_definition\_of\_natural\_numbers

# Answer
# JavaScript (Node.js), ~~53~~ ~~48~~ 44 bytes

```
f=a=>(a=eval(a)).every(e=>a[e.length]&&f(e))

```

Try it online! Test cases mostly shamelessly stolen from @Arnauld's answer. Explanation: If a set represents a natural number, then the natural number it represents must be equal to the size of the set, and (given that the elements are guaranteed distinct) the elements must be the representations of the natural numbers less than it, and these must therefore have shorter lengths. This is trivially true of the empty set of course. Edit: Saved 5 bytes thanks to @Arnauld. Saved 4 bytes thanks to @Cowsquack.
> 13 votes

# Answer
# Python 3, ~~69~~ ~~58~~ 44 bytes

11 bytes thanks to Erik the Outgolfer.

14 bytes thanks to Mr. Xcoder.

```
f=lambda s:all(len(e)<len(s)*f(e)for e in s)

```

Try it online!
> 7 votes

# Answer
# Wolfram Language (Mathematica), ~~60~~ 59 bytes

```
E!=(If[Sort@#===Range[t=Tr[1^#]]-1,t,E]&//@ToExpression@#)&

```

Try it online!

The core of this solution is the function

```
If[Sort@#===Range[t=Tr[1^#]]-1,t,E]&

```

which converts a list of the form `{0,1,2,...,n-1}` in any order into the output `n` (in particular, it converts `{}` to `0`), and converts anything else into the real number `E`.

Call this function `f`. Given an input such as `"{{{}},{}}"`, we do the following:

1. Convert the string into a Mathematica expression.
2. Apply `f` at every level, getting `f[{f[{f[{}]}], f[{}]}]`.
3. Evaluating all the `f`'s will produce a natural number for an input representing it. For example, `f[{f[{f[{}]}], f[{}]}]` = `f[{f[{0}], 0}]` = `f[{1, 0}]` = `2`. Anything else will produce `E`.
4. We test if the result is a natural number by checking if it's not `E`.
> 6 votes

# Answer
# Brachylog (v2), 9 bytes

```
↰ᵐo.t~k|Ė

```

Try it online!

As usual for a , this is a full program. Input from standard input, using square brackets. Output to standard output as `true.` versus `false.`.

## Explanation

Although I said above that this is a full program, it's actually more interesting than that; it's *both* a full program and a function. When used as a full program, it prints `true.` if the set is a natural number, or `false.` if it isn't. When used as a function, it "normalizes" a natural number (i.e. normalizes all its elements and sorts them into order by value; this program uses lists internally, not sets), or "throws an exception" (actually a failure, as this is Prolog) if the input isn't a natural number.

The full program behaviour is easy enough to explain: it's purely implicit in Brachylog's treatment of full programs that don't contain I/O instructions. The behaviour in question is "run the function, taking its input from standard input, and asserting that its output matches the description given by the first command-line argument; if the assertion fails or the program throws an exception, print `false.`, otherwise print `true.`". In this case, the command-line argument is missing (i.e. "anything goes"), so the exception/no-exception behaviour of the function gives the output.

As for the function behaviour:

```
↰ᵐo.t~k|Ė
↰ᵐ          Map a recursive call to this function over the list
  o         Sort the list
   .   |    Assert that the following operation need not change the list:
    t         Take the last (i.e. greatest) element of the list
     ~k       Append an arbitrary element to the resulting list
   .   |    Output the unchanged list
       |    Exception handler: if the above threw an exception,
        Ė     Assert that the input is empty, and output an empty list

```

A natural number is defined as containing two parts: the elements of the natural number below, unioned with the number itself. Thus, all its elements are also natural numbers. We can recognise a natural number by a) verifying that all its elements are natural numbers, b) verifying that the set's largest element is identical to the set without its largest element.

When we're using lists rather than sets (thus the square brackets), we need to put them into a consistent order for equality comparisons to work (in this case, sorted by "value"). Brachylog's default sort order will sort a prefix of a list before the list itself, which conveniently means that it'll sort natural numbers by numerical value. So we can just recursively sort all our numbers to get them into a consistent order. In fact, via the function we're defining recursively, we can achieve both results at the same time: recursively sorting the number's elements, and verifying that it's a natural number.

The function thus has four main parts. `↰ᵐ` is the recursive call, ensuring that each element is a natural number, and converting it each element to a normalized form. `o` the normalizes the number itself (its elements are already normalized, so all we have to do is to sort it). Then `.t~k|` ensures we have the structure we want by checking that the largest element and other elements are the same. An empty list (i.e. 0) doesn't have a last element, so will get an assertion failure with `t`; the  handles this case, via giving an explicit fallback in the case where the input list is empty.
> 4 votes

# Answer
# Jelly, 8 bytes

```
ß€Ṣ
ÇṖƤƑ

```

Since the input has to be a string, this submission is only valid as a full program.

Try it online! or verify all test cases

### How it works

```
ß€Ṣ   Helper link. Argument: A (array)

ß€    Recursively map the helper link over A.
  Ṣ   Sort the result.

```

This yields a canonical representation of the input, consisting solely of sorted arrays.

```
ÇṖƤƑ  Main link. Argument: A (array)

Ç     Call the helper link to canonicalize the array.
   Ƒ  Fixed; call the link to the left and test if it returns its argument unchanged.
 ṖƤ       Pop prefix; for each non-empty prefix of the result, remove its last element.

```
> 3 votes

# Answer
# K (ngn/k), ~~26~~ ~~24~~ 27 bytes

```
{{o'!x}[#x]~{x@<x:o'x}x}`j?

```

Try it online!
> 2 votes

# Answer
# Jelly, 7 bytes

```
Ẉ<Laß€Ạ

```

This is a port of Leaky Nun's Python answer.

Since the input has to be a string, this submission is only valid as a full program.

Try it online! or verify all test cases

### How it works

```
Ẉ<Laß€Ạ  Main link. Argument: A (array)

Ẉ        Width; compute the length of A's elements.
  L      Yield the length of A.
 <       Compare them, yielding an array of Booleans.
    ß€   Recursively map the main link over A.
   a     Take the logical AND of the Booleans and the results of the map.
      Ạ  All; yield 1 if and only if all ANDs yielded 1.

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~36~~ 40 bytes

```
(Sort//@#//.{a__,{a__}}:>{a})!={}!={{}}&

```

Try it online!
> 2 votes

# Answer
# Jelly, 10 bytes

```
ẈṢ‘⁼Jȧ@ßƇƑ

```

Try it online!
> 1 votes

# Answer
# Japt, 9 bytes

Port of Neil's JS solution. Please upvote that if you're upvoting this.

```
e@Ê>XÊ©ßX

```

Try it or run all test cases

```
              :Implicit input of array U
e             :Does every element in U return true
 @            :When passed through the following function as X
  Ê           :Length of U
   >          :Greater than
    XÊ        :Length of X
      ©       :Logical AND with
       ßX     :A recursive call of the programme with X passed as the new value of U

```
> 1 votes

# Answer
# Red, 81 bytes

```
func[a][p: 1 foreach e to-block a[p: p *(pick[1 0](length? e)< length? a)* f e]p]

```

Try it online!

Similar to Leaky Nun's Python 3 answer
> 1 votes

# Answer
# Wolfram Language (Mathematica), 52 bytes

```
If[Max[#0/@#]<(l=2Length@#),l]&@*ToExpression/*EvenQ

```

Try it online!
> 0 votes

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


title: Parse ascii art math!

text:
# Question
Title: Parse ascii art math!
# The task

Given a multiline string with ascii art operators and numbers, parse the expression!

# Possible symbols

Numbers: (3x4)

```
 /
/|
 |
---

___
 _|
|
---

___
 _|
  |
---

| |
|_|
  |
  |

___
|_
  |
---

___
|_
| |
---

___
  /
 /
|

___
|_|
| |
---

___
|_|
  |
---

___
| |
| |
---

```

Operators: (3x3)

```
 |
-+-
 |

---

\ /
 x
/ \

 .
---
 .

```

Braces: (1x4)

```
/
|
|
\

\
|
|
/

```

# Input

A multiline string with ascii art operators and numbers. Examples in the test cases.

# Output

The string of the parsed expression.

# Test cases

Input:

```

/ ___     ___ \     ___
|  _|  |    / |  .   _|
| |   -+-  /  | ---   |
\ ---  |  |   /  .  ---

```

Output: `(2+7)/3`

Input:

```
___      /      ___
|_|     /|  \ / |_
  | ---  |   x    |
---     --- / \ ---

```

Output: `9-1*5`

# Rules

1. Numbers will always be single-digit
2. Since operators are one symbol shorter than numbers, they are placed one symbol lower than numbers, leaving whitespace on top.
3. All symbols have a column of whitespace between them
4. This is a code-golf challenge, so lowest byte count wins!

# Answer
> 18 votes
# APL (Dyalog Unicode), ~~46~~ 44 bytes

```
'/(80-)63+92145*7'[16|43|25⊥¨(×⊆⊢)2⊥' .\'⍳⎕]

```

Try it online!

evaluated input, must be a character matrix

`' .\'⍳` replace spaces with 0, `.`s with 1, `\`s with 2, and everything else with 3

`2⊥` base-2 decode the columns

`(×⊆⊢)` split on zeroes

`25⊥¨` base-25 decode each group

`16|43|` mod 43, mod 16

`'/(80-)63+92145*7'[` `]` use as indices in the given string

# Answer
> 7 votes
# Python 2, ~~154~~ 139 bytes

```
s=zip(*input().split('\n'))
i=0
while s[i:]:d=3**(max((s+[' '])[i+1])>' ')+i;print'+/5(_41_7802*6__-9)3'[hash(tuple(s[i:d]))*3%67%21];i=1+d

```

Try it online!

# Answer
> 5 votes
# APL (Dyalog Unicode), ~~69~~ 61 bytes

Anonymous tacit prefix function. Requires `⎕IO←0`.

```
{('+-*/()',⎕D)['∆JV⍺TgucKmre3Ha'⍳⎕AV[94|2⊥¨,⌿⍵⊆⍨∨⌿32≠⍵]]}⎕UCS

```

Try it online!

`⎕UCS` convert characters to code points

`{``}` "dfn"; argument is

`('+-*/()',⎕D)` the involved symbols followed by the **D**igits

`[``]` index into that using the following indices:

`'∆JV⍺TgucKmre3Ha'⍳` indices in this string (missing elements get index=length) of

`⎕AV[``]` index into the **A**tomic **V**ector (the character set) using the following:

`94|` the division remainder when divided by 94 of

`2⊥¨` the base-2 evaluation of each of

`,⌿` the vertically joined and flattened

`⍵⊆⍨` segments of the argument, as indicated by trues in

`∨⌿` the vertical OR-reduction of

`32≠⍵` the Boolean mask indicating where the argument is different from 32 (space)

# Answer
> 3 votes
# JavaScript (Node.js), 152 bytes

```
f=(s,i=0,a=s.split`
`,c=a[n=0][i],x=1)=>c?"*3-425()6+9/7081"[c=='/'?6:c=='\\'?7:[x=3,4,5,6,9].map(c=>n+=Buffer(a[c/3|0])[i+c%3]*c)|n%47%16]+f(s,i-~x):''

```

Try it online!

# Answer
> 2 votes
# Charcoal, 67 bytes

```
⭆⪪⭆θ§αＩ⭆⟦θηζε⟧÷⊖℅§λκ³²A℅⁺⁴⁰÷⌕”$⌈O⁴εΦa↙M∕³↧ＦωＧ↙σ⎇C(｜？⊞¦﹪ω←2Ｉ0C⁻sⅉ”ι³

```

Try it online! Link is to verbose version of code. Assumes 4 input strings of equal length (space padded if necessary). Explanation:

```
   θ                                First input
  ⭆                                 Map over characters and join
        ⟦θηζε⟧                      All four inputs as a list
       ⭆                            Map over strings
                  λ                 Inner string
                 §                  Indexed by
                   κ                Outer index
                ℅                   Take the ASCII code
               ⊖                    Decrement
              ÷     ³²              Integer divide by literal `32`
      Ｉ                             Cast to integer
    §α                              Index into uppercase alphabet
 ⪪                    A             Split on literal `A`
⭆                                   Map over substrings
                            ⌕...ι   Find their indices in compressed data
                           ÷     ³  Integer divide by 3
                        ⁺⁴⁰         Plus literal `40`
                       ℅            Convert to ASCII
                                    Implicitly print

```

The compressed data represents the literal string `GAARAATEYKBKAAAKKKAAAKHKRZRXFBDRNZRRYSFNRDRRDBIURRRNRR` which contains the pattens that result from the calculation, padded with `A`s to place them at the appropriate offset to generate the desired ASCII character.

# Answer
> 2 votes
# Jelly, 36 bytes

```
ỴZ⁶=ẠƊ€œp$“¢Ọ/’,“642-*+)9(8/17035”ḥⱮ

```

A monadic Link accepting a list of characters which yields a list of characters.

**Try it online!**

### How?

```
ỴZ⁶=ẠƊ€œp$“¢Ọ/’,“642-*+)9(8/17035”ḥⱮ - Link: list of characters, I
Ỵ                                    - split at newline characters
 Z                                   - transpose
         $                           - last two links as a monad - i.e. f(X):
     Ɗ€                              -   for each, last three links as a monad:
  ⁶                                  -     the space character
   =                                 -     equals? (vectorises)
    Ạ                                -     all?
       œp                            -   split (X) at truthy indices of (that)
                                     -     (...call the result A)
          “¢Ọ/’                      - base 250 int = 170548 (salt)
                “642-*+)9(8/17035”   - list of characters "642-*+)9(8/17035" (domain)
               ,                     - pair -> [salt, domain]
                                   Ɱ - map across A with:
                                  ḥ  -   Jelly's hash function with salt and domain

```

# Answer
> 1 votes
# 05AB1E, ~~54~~ ~~40~~ 39 bytes

```
"2(-1 0/ 9 6*)+"Ž´Š«|€SøJð4×¡JÇ2δβŽ4w%è

```

~~Can definitely be golfed some more with smarter magical integers (including changing the `ā‡` to for example `Åβ` or changing the order of the charcters in the strings), but I'm pretty bad at those kind of challenges personally, so this will do for now.~~
-14 bytes thanks to *@ovs*, because he is skilled in these kind of magic integer challenges. ^\_^

Try it online or verify all test cases.

**Explanation:**

```
"2(-1 0/ 9 6*)+"      # Push this string
                Ž´Š   # Push compressed integer 45783
                   «  # Append it to the string: "2(-1 0/ 9 6*)+45783"
|                     # Push all input-lines as list
 €S                   # Convert each line to a list of characters
   ø                  # Zip/transpose; swapping rows/columns
    J                 # Join each inner list (column) together to a string
     ð4×              # Push a string of 4 space characters: "    "
        ¡             # Split the list on that
         J            # Join each inner list of strings to a single string
          Ç           # Convert each string to a list of codepoint integers
            δ         # For each list of integers:
           2 β        #  Convert from a base-2 list to a base-10 integer
              Ž4w%    # Modulo-1078 on each value
è                     # And then (modulair 0-based) index them into the string
                      # (after which the result is output implicitly)

```

See this 05AB1E tips of mine (section *How to compress large integers?*) to understand why `Ž´Š` is `45783` and `Ž4w` is `1078`.

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


title: Polygonal numbers

text:
# Question
Title: Polygonal numbers
A polygonal number is the number of dots in a `k`-gon of size `n`.

You will be given `n` and `k`, and your task is to write a program/function that outputs/prints the corresponding number.

# Scoring

This is . Shortest solution in bytes wins.

# Example

The `3`rd hexagon number (`k=6, n=3`) is `28` because there are `28` dots above.

# Testcases

Can be generated from this Pyth test suite.

Usage: two lines per testcase, `n` above, `k` below.

```
n    k  output
10   3  55
10   5  145
100  3  5050
1000 24 10990000

```

# Further information

# Answer
> 9 votes
# Jelly, 7 bytes

```
’;’;PH+

```

This uses the formula

to compute the **n**th **s**-gonal number.

Try it online!

### How it works

```
’;’;PH+  Main link. Arguments: s, n

’        Decrement; yield s - 1.
 ;       Concatenate; yield [s - 1, n].
  ’      Decrement; yield [s - 2, n - 1].
   ;     Concatenate; yield [s - 2, n - 1, n].
    P    Product; yield (s - 2)(n - 1)n.
     H   Halve; yield (s - 2)(n - 1)n ÷ 2.
      +  Add; yield (s - 2)(n - 1)n ÷ 2 + n.

```

# Answer
> 4 votes
## Hexagony, 25 bytes

```
?(({"+!@/"*'+{/?('*})/2':

```

Unfolded:

```
   ? ( ( {
  " + ! @ /
 " * ' + { /
? ( ' * } ) /
 2 ' : . . .
  . . . . .
   . . . .

```

Reads `k` first and `n` second (using any separator).

Try it online!

### Explanation

The program is completely linear, but as usual in Hexagony, the order of execution is all over the place:

The paths are executed in the order *grey*, *dark blue*, *red*, *light blue*, *dark green*, *pink*. As you can see, the three `/` only act to redirect the flow. Also, the `.` are no-ops. Stripping all hexagonal fanciness, the resulting linear program is:

```
?(({?('*})"*'+{2':"+!@

```

This computes the standard formula

like most of the other answers. It does so using the following five memory edges, with the memory pointer (MP) starting as shown in red:

Here's how this is done:

```
?    Read integer input s into edge A.
((   Decrement twice to get (s-2).
{    Move the MP forwards onto edge B.
?    Read integer input n into edge B.
(    Decrement to get (n-1).
'    Move the MP backwards onto edge C.
*    Multiply edges A and B to store the result (s-2)(n-1) in edge C.
}    Move the MP forwards onto edge B.
)    Increment to restore the value n.
"    Move the MP backwards onto edge A.
*    Multiply edge B and C to store the result (s-2)(n-1)n in edge A.
'    Move the MP backwards onto edge D.
+    Add edges E (initially 0) and A to copy (s-2)(n-1)n into edge D.
{    Move the MP forwards onto edge E.
2    Set the memory edge to value 2.
'    Move the MP backwards onto edge A.
:    Divide edge D by edge E to store (s-2)(n-1)n/2 in edge A.
"    Move the MP backwards onto edge C.
+    Add edges A and B to store (s-2)(n-1)n/2+n in edge C.
!    Print as integer.
@    Terminate the program.

```

# Answer
> 3 votes
# 05AB1E, 8 bytes

Code:

```
D<LOIÍ*+

```

Explanation:

```
D         # Duplicate the input
 <LO      # Compute n × (n - 1) / 2
    IÍ    # Compute k - 2
      *   # Multiply, resulting into (k - 2)(n - 1)(n) / 2
       +  # Add, resulting into n + (k - 2)(n - 1)(n) / 2

```

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

# Answer
> 3 votes
## Labyrinth, 13 bytes

```
?::(*?((*#/+!

```

Try it online!

### Explanation

Due to its single-character commands (which are merely a necessity of the 2D-ness of the language), Labyrinth can be surprisingly golfy for linear programs.

This uses the same formula as several other answers:

```
Op  Explanation                 Stack
?   Read n.                     [n]
::  Make two copies.            [n n n]
(   Decrement.                  [n n (n-1)]
*   Multiply.                   [n (n*(n-1))]
?   Read s.                     [n (n*(n-1)) s]
((  Decrement twice.            [n (n*(n-1)) (s-2)]
*   Multiply.                   [n (n*(n-1)*(s-2))]
#   Push stack depth, 2.        [n (n*(n-1)*(s-2)) 2]
/   Divide.                     [n (n*(n-1)*(s-2))/2]
+   Add.                        [(n+(n*(n-1)*(s-2))/2)]
!   Print.                      []

```

At this point, the instruction pointer hits a dead end and turns around. Now `+` is executed again, which is a no-op (since the bottom of the stack is implicitly filled with an infinite amount of zeros), and then `/` attempts a division-by-zero which terminates the program with an error.

# Answer
> 2 votes
## JavaScript (ES6), ~~24~~ 22 bytes

```
(k,n)=>n+n*--n*(k-2)/2

```

Explanation: Each n-gon can be considered to be n points along one side plus k-2 triangles of size n-1, i.e. n+n(n-1)(k-2)/2.

# Answer
> 2 votes
# CJam, 13 bytes

```
q~__(*2/@2-*+

```

Try it online

# Answer
> 2 votes
# APL (Dyalog Extended), 11 bytesSBCS

Thanks to Adám for his help for suggesting this alternate version.

```
⊢+-∘2⍤⊣×2!⊢

```

Try it online!

**Explanation**

```
⊢+-∘2⍤⊣×2!⊢  Right argument (⊢) is n. Left argument (⊣) is s.

        2!⊢  Binomial(n, 2) == n*(n-1)/2.
  -∘2⍤⊣×     Multiply (×) with by getLeftArgument (⊢) with (⍤) minus 2 (-∘2) called on it.
             In short, multiply binomial(n,2) with (s-2).
⊢+           Add n.

```

---

# APL (Dyalog Unicode), ~~12~~ 11 bytesSBCS

Thanks to Adám for his help in golfing this.

Edit: -1 byte from ngn.

```
⊢+{⍺-2}×2!⊢

```

Try it online!

**Ungolfing**

```
⊢+{⍺-2}×2!⊢  Right argument (⊢) is n. Left argument (⊣) is s.

        2!⊢  Binomial(n, 2) == n*(n-1)/2.
  {⍺-2}×     Multiply it by s-2.
⊢+           Add n.

```

# Answer
> 1 votes
## Actually, 12 bytes

```
3@n(¬@D3╟π½+

```

Try it online!

Explanation:

```
3@n(¬@D3╟π½+
3@n           push 3 copies of n (stack: [n, n, n, k])
   (¬         bring k to front and subtract 2 ([k-2, n, n, n])
     @D       bring an n to front and subtract 1 ([n-1, k-2, n, n])
       3╟π    product of top 3 elements ([n*(n-1)*(k-2), n])
          ½   divide by 2 ([n*(n-1)*(k-2)/2, n])
           +  add ([n*(n-1)*(k-2)/2 + n])

```

# Answer
> 1 votes
# dc, 14 bytes

```
?dd1-*2/?2-*+p

```

Try it online!

### Explanation

This makes use of the following formula (note that **T**n = `n*(n-1)/2`):

```
                # inputs              | N S                  | 10 5
?dd             # push N three times  | N, N, N              | 10, 10, 10
   1-           # subtract 1          | (N-1), N, N          | 9, 10, 10
     *          # multiply            | (N-1)*N, N           | 90, 10
      2/        # divide by two       | (N-1)*N/2, N         | 45, 10
        ?       # push S              | S, (N-1)*N/2, N      | 5, 45, 10
         2-     # subtract 2          | (S-2), (N-1)*N/2, N  | 3, 45, 10
           *    # multiply            | (S-2)*(N-1)*N/2, N   | 135, 10
            +   # add                 | (S-2)*(N-1)*N/2 + N  | 145
             p  # print to stdout

```

# Answer
> 1 votes
# Aceto, ~~18~~ 15 bytes

Port of the Bruce Forte's dc answer:

```
riddD*2/ri2-*+p

```

Saved 3 bytes by realizing that any "pure" (no combined commands) Aceto program can be written linearly.

# Answer
> 1 votes
# MathGolf, 8 bytes

```
_┐*½?⌡*+

```

Try it online!

## Explanation (with \\$n = 10, k = 5\\$

```
_          duplicate first implicit input, stack is [10, 10]
 ┐         push TOS-1 without popping, stack is [10, 10, 9]
  *        multiply, stack is [10, 90]
   ½       halve TOS, stack is [10, 45]
    ?      rotate top 3 stack elements, popping k to the top: [10, 45, 5]
     ⌡     decrement TOS twice: [10, 45, 3]
      *    multiply: [10, 135]
       +   add: [145]

```

An alternative 8-byter is `┼┐*½\⌡*+`, which takes the input in reversed order.

# Answer
> 1 votes
# \>\<\>, 13 bytes

```
::1-*2,{2-*+n

```

Try it online!

# Answer
> 0 votes
# Mathematica, 17 bytes

```
(#2-2)#(#-1)/2+#&

```

Straight-forward application of the formula.

## Usage

```
  f = (#2-2)#(#-1)/2+#&
  f[10, 3]
55
  f[10, 5]
145
  f[100, 3]
5050
  f[1000, 24]
10990000

```

# Answer
> 0 votes
# J, 14 bytes

```
]++/@i.@]*[-2:

```

Based on the formula.

```
P(k, n) = (k - 2) * T(n - 1) + n where T(n) = n * (n + 1) / 2
        = (k - 2) * n * (n - 1) / 2 + n

```

## Usage

```
   f =: ]++/@i.@]*[-2:
   3 f 10
55
   5 f 10
145
   3 f 100
5050
   24 f 1000
10990000

```

## Explanation

```
]++/@i.@]*[-2:
            2:  The constant function 2
          [     Get k
           -    Subtract to get k-2
        ]       Get n
     i.@        Make a range from 0 to n-1
  +/@           Sum the range to get the (n-1) Triangle number = n*(n-1)/2
                The nth Triangle number is also the sum of the first n numbers
         *      Multiply n*(n-1)/2 with (k-2)
]               Get n
 +              Add n to (k-2)*n*(n-1)/2

```

# Answer
> 0 votes
# TI-Basic, 20 bytes

```
Prompt K,N:(K-2)N(N-1)/2+N

```

# Answer
> 0 votes
# GameMaker Language, 44 bytes

```
n=argument1;return (argument0-2)*n*(n-1)/2+n

```

# Answer
> 0 votes
# Python 3, ~~31~~ ~~30~~ 28 bytes

The straight up equation from this wiki article

```
lambda s,n:(s-2)*(n-1)*n/2+n

```

*Thanks to @Mego for saving a byte!*

# Answer
> 0 votes
# Japt, ~~14~~ ~~12~~ 10 bytes

```
-[U½UÉVÍ]×

```

Try it

# Answer
> 0 votes
# Fourier, 18 bytes

```
I-2~SI~Nv*N/2*S+No

```

**Try it on FourIDE!**

Takes k as first input and n as second input. Uses the formula:

***Explanation Pseudocode:***

```
S = Input - 2
N = Input
Print (N - 1) * N / 2 *S + N

```

# Answer
> 0 votes
# Excel, 22 bytes

Calculates the `A1`th `B1`-gonal number.

```
=(B1-2)*A1*(A1-1)/2+A1

```

# Answer
> 0 votes
# Java 8, 21 bytes

All individual answers of equal byte-length:

```
k->n->n+n*~-n*(k-2)/2
k->n->n+n*--n*(k-2)/2
k->n->n+n*~-n*~-~-k/2
k->n->n+n*--n*~-~-k/2

```

**Explanation:**

Try it here.

```
k->n->            // Method with two integer parameters and integer return-type
  n+              //  Return `n` plus
    n*            //   `n` multiplied by
      ~-n         //   `n-1`
         *(k-2)   //   Multiplied by `k-2`
               /2 //   Divided by 2
                  // End of method (implicit / single-line return-statement)

```

# Answer
> 0 votes
# Husk, 9 bytes

```
S+~*-2(Σ←

```

Try it online!

### Explanation

Using the same formula as in my `dc` answer:

```
            -- implicit inputs S, N                     | 5, 10
S+          -- compute N + the result of the following  | 10 +
  ~*        --   multiply these two together            |      (   ) *
    -2      --     S-2                                  |       S-2
      (Σ←)  --     triangle number of (N-1)             |              tri(N-1)

```

# Answer
> 0 votes
# APL(NARS), 16 char, 32 bytes

```
{⍵+(⍺-2)×+/⍳⍵-1}

```

It is based from the fact that seems n×(n-1)/2=sum(1..n-1) test:

```
  f←{⍵+(⍺-2)×+/⍳⍵-1}
  10 f 3
27
  3 f 10
55
  5 f 19
532
  3 f 10
55
  5 f 10
145
  3 f 100
5050
  24 f 1000
10990000

```

# Answer
> 0 votes
# Rockstar, 67 bytes

```
listen to N
listen to K
cast N
let K be-2
let K be*N-1
say K*.5*N+N

```

Try it here (Code will need to be pasted in, with each input integer on an individual line)

# Answer
> 0 votes
# x86-16 machine code, 14 bytes

```
00000000: 4949 8bc3 48f7 e3f7 e1d1 e803 c3c3       II..H.........

```

Listing:

```
49          DEC  CX         ; k = k - 2
49          DEC  CX
8B C3       MOV  AX, BX     ; AX = n
48          DEC  AX         ; AX = n - 1
F7 E3       MUL  BX         ; AX = n * n - 1
F7 E1       MUL  CX         ; AX = ( k - 2 ) * n * ( n - 1 )
D1 E8       SHR  AX, 1      ; AX = ( k - 2 ) * n * ( n - 1 ) / 2
03 C3       ADD  AX, BX     ; AX = ( ( k - 2 ) * n * ( n - 1 ) / 2 ) + n
C3          RET             ; return to caller

```

Callable function, input `n` in `BX`, `k` in `CX`, result in `AX`.

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


title: Create pixel art!

text:
# Question
Title: Create pixel art!
# The task

Given an image as input, your task is to do the following:

1. Resize the image so it is **At least** 2 times smaller, but still has the same width/height ratio by taking every second (if resized to 2x) pixel in both horizontal and vertical directions and using those in the pixel art image. Example:

```
a 4x4 image

[abcd
,efgh
,ijkl
,mnop]

When resized to 2x will become one of the following:

[ac  [bd  [eg  [fh
,ik] ,jl] ,mo] ,np]

```
2. Each RGB pixel in the newly resized image must be converted to a 3-bit color, so there are 8 different possible colors:

```
Red        (255,0,0)
Green      (0,255,0)
Blue       (0,0,255)
Light Blue (0,255,255)
Magenta    (255,0,255)
Yellow     (255,255,0)
White      (255,255,255)
Black      (0,0,0)

```

An image of the colors:

3. And output the resulting image.

# Input

Your input may be:

1. An image
2. A path to the inputting image

# Output

Can be:

1. An image
2. A path to the outputting image

# Rules

* The inputting image will not be larger than 2048x2048 and will always be at least 256x256
* The outputting image must be at least 64x64
* When changing pixels, the original pixel **must** be converted to the closest (euclidean) pixel in the 3-bit scheme, no randomization
* You may hardcode how much you resize the image if you want to
* When submitting your answer, please include the following:
    1. Your byte-count in the title
    2. Your code
    3. An pair of images, one original of your choice and the other being the "pixel-art" from that image
* This is code-golf, so lowest byte count for each language wins.

# Test cases

(2x resize)

(2x resize)

# Answer
> 10 votes
# Sledgehammer, ~~22~~ 17 bytes

I noticed I'm no longer winning for some reason and made a minor IO golf

```
⢟⢡⡂⠴⠒⢂⢜⠧⣘⡨⡏⣻⢈⠯⣧⠼⡫

```

Corresponding Mathematica code: `Export[".bmp",ImageAdjust[Import[#]~Downsample~2, 9!]]&` . Takes input from the file with name specified in the program's arguments (for some reason these are put in a file, too), outputs to the file `.bmp`. There are literally built-ins for everything!

* built-in for reading arbitrary image format
* built-in for downsampling
* built-in for adjusting the contrast by \\$9!\\$
* built-in for writing all that into a file

At least it's not `PixelArtify[Input[]]`.

# Mathematica, ~~61~~ 31 bytes

```
ImageAdjust[#~Downsample~2,9!]&

```

Adjusts the contrast of the downsampled image by the factorial of nine.

# Answer
> 9 votes
# MATL, 18 bytes

```
Yi2Lt3:K$)127>o2YG

```

The input is a string with the file name. The output is an image displayed in a window.

Input image:

Output image:

### Explanation

```
Yi    % Implicit input: filename. Read image. Gives an N×M×3 uint8 array
2L    % Push [2 2 j] (predefined literal). When interpreted as an index,
      % this means 2:2:end
t     % Duplicate
3:    % Push [1 2 3]
K$)   % 4-input indexing. Downsamples the image by a factor of 2 in each
      % dimension of the first two dimensions (vertical and horizontal),
      % while keeping the three colour components
127>  % Greater than 127? Gives true (1) or false (0)
o     % Convert to double
2YG   % Display image. For double data type this assumes range from 0 to 1

```

# Answer
> 7 votes
# Python 3 \+ imageio, ~~68~~ 67 bytes

Takes the filename as input, overwrites the original file.

```
from imageio import*
lambda f:imwrite(f,(~imread(f)[::2,::2]>>7)-1)

```

`imageio.imread` returns a numpy 3d array of unsigned 8-bit integers corresponding to the RGB value of each pixel. `array[::2, ::2]` takes every other row and every other column of the array.

Because of the 8-bit data type `(~array>>7)-1` is equivalent to `((255-array)//128-1)%256`.

image source

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

```
Image[#&@@Nearest[{0,1}~Tuples~3,#]&/@#&/@ImageData@Downsample[#,2]]&

```

# Answer
> 4 votes
# Java 10, ~~255~~ ~~254~~ ~~252~~ ~~251~~ 248 bytes

```
import java.awt.image.*;I->{int w=I.getWidth()/2,h=I.getHeight()/2,c[]={0,255,65535,65280,255<<16,16711935,16776960,-1>>>8};var r=new BufferedImage(w,h,13,new IndexColorModel(3,8,c,0,0>1,1,0));r.createGraphics().drawImage(I,0,0,w,h,null);return r;}

```

-2 bytes thanks to *@mypronounismonicareinstate*
-4 bytes thanks to *@OlivierGrégoire*.

**Some example I/O:**

I/O as a `java.awt.image.BufferedImage`.

**Explanation:**

```
import java.awt.image.*;      // Import for BufferedImage and IndexColorModel
I->{                          // Method with BufferedImage as both parameter & return
  int w=I.getWidth()/2,       //  Get the width/2 of the input-image
      h=I.getHeight()/2,      //  Get the height/2 of the input-image
      c[]={                   //  Integer-arry for the colors:
       0,                     //   0x000000 (black)
       255,                   //   0x0000ff (blue)
       65535,                 //   0x00ff00 (green)
       65280,                 //   0x00ffff (aqua)
       255<<16,               //   0xff0000 (red)
       16711935,              //   0xff00ff (magenta)
       16776960,              //   0xffff00 (yellow)
       -1>>>8};               //   0xffffff (white)
  var r=new BufferedImage(w,h,//  Create the return-BufferdImage with this size, and:
         13,                  //   An indexed byte image (BufferedImage.TYPE_BYTE_INDEXED)
         new IndexColorModel( //   Using the following ColorModel:
          3,                  //    3-bits
          8,c,                //    with the 8 colors of the earlier created array
          0,                  //    without an offset index
          0>1,                //    without alpha layers (false)
          1,                  //    without transparent colors (Transparency.OPAQUE)
          0));                //    using unsigned bytes as data (DataBuffer.TYPE_BYTE)
  r.createGraphics()          //  Convert this image to a Graphics2D object
   .drawImage(I,              //  So we can use the input-image for it
              0,0,            //   with 0,0 as starting x,y coordinates
              w,h,            //   the same halved width & height
              null);          //   and no ImageObserver
  return r;}                  //  Return this created BufferedImage as result

```

# Answer
> 3 votes
# Red, ~~150~~ 148 bytes

```
func[s][r: func[a][round/to a 255]i: load s forall i[i/1: as-rgba r i/1/1
r i/1/2 r i/1/3 0]view compose[base(i/size / 2)draw[scale .5 .5 image i]]]

```

The output is an image displayed in a window.

Original

Scale 0.5

Original

Scale x 0.5

# Answer
> 3 votes
# Python 3 + PIL, ~~211~~ 208 bytes

```
from PIL import Image as I
i=I.open(input(),'r')
p=i.load()
q,g=i.size;a=q//4;c=g//4
u=I.new('RGB',(a,c))
o=u.load()
for w in range(a):
 for h in range(c):o[w,h]=tuple(e//128*255 for e in p[w*4,h*4])
u.show()

```

Golfed the testing script I used to create the test cases for this challenge

# Answer
> 3 votes
## bash + ImageMagick, ~~123~~ 50 bytes

```
convert "$1" -sample 50% +dither -posterize 2 "$2"

```

Untested, as I haven't actually installed it; I've just cribbed stuff from Stack Overflow. Edit: Saved 73 bytes thanks to @someone.

# Answer
> 3 votes
# bash + netpbm, 30 bytes

```
pnmdepth 1|pnmscale -nomix 0.5

```

Takes input on stdin as a PNM file, and outputs on stdout as a PNM file.

`pnmdepth 1` reduces the depth of the image on its stdin to 1, and `pnmscale 0.5` reduces the size by a half in each direction. The `-nomix` option is required for `pnmscale` to choose a pixel from the starting image for each output pixel, instead of mixing adjacent input pixels into one output pixel.

# Answer
> 1 votes
# MATLAB, 32 bytes

```
@(x)(x(1:2:end,1:2:end,:)>127)*1

```

Both input and output are images. Output is an array storing image data, it's not specified in challenge that output image must be displayed. (to display result add 8 bytes for `imshow(`...`)` command)
The actual result and original:

Art credit to Janna Sophia.

# Answer
> 0 votes
# Processing, 463 bytes

```
size(500,500);String u="";PImage p=loadImage(u);p.resize(p.width/2,p.height/2);noStroke();color[]c={#ff0000,#00ff00,#0000ff,#00ffff,#ff00ff,#ffff00,#ffffff,0};p.loadPixels();for(int i=0;i<p.width;i++){for(int j=0;j<p.height;j++){float[]d=new float[8];color x=p.get(i,j);for(int k=0;k<8;k++)d[k]=sqrt(sq(red(x)-red(c[k]))+sq(blue(x)-blue(c[k]))+sq(green(x)-green(c[k])));int b=0;for(int l=0;l<8;l++){if(d[l]<=d[b]){b=l;}}fill(c[b]);rect(i,j,1,1);}}save(u+"1.png");

```

Takes image location, saves pixel art as image1.png.  Image from beeple.

---
Tags: code-golf, graphical-output
---


title: Polynomial Long Division

text:
# Question
Title: Polynomial Long Division
Implement polynomial long division, an algorithm that divides two polynomials and gets the quotient and remainder:

(12x^3 - 5x^2 + 3x - 1) / (x^2 - 5) = 12x - 5 R 63x - 26

In your programs, you will represent polynomials as an array, with the constant term on the tail. for example, x^5 - 3x^4 + 2x^2 - x + 1 will become \[1, -3, 0, 2, -1, 1\].

The long division function you are going to write will return two values: the quotient and the remainder. You do not need to handle numerical imprecisions and arithmetic errors. Do not use math library to do your job, however, you may make your function able to deal with symbolic values. Shortest code wins.

EXAMPLE: `div([12, -5, 3, -1], [1, 0, -5]) == ([12, -5], [63, -26])`

# Answer
> 5 votes
## J, 94

```
f=:>@(0&{)
d=:0{[%~0{[:f]
D=:4 :'x((1}.([:f])-((#@]{.[)f)*d);([:>1{]),d)^:(>:((#f y)-(#x)))y'

```

eg.

```
(1 0 _5) D (12 _5 3 _1;'')
63 _26 | 12  _5

```

Explanation of some snippets, given that a: (12 -5 3 -1) and b: (1 0 -5)

length of a:

```
#a
4

```

make a and b same order by appending zeroes to b:

```
(#a) {. b
1 0 -5 0

```

divide higher powers (first elements) of a, b:

```
(0{a) % (0{b)
12

```

multiply b by that and subtract it from a:

```
a - 12*b
12 0 _60

```

repeat n times b = f(a,b):

```
a f^:n b

```

# Answer
> 5 votes
# Python 2, ~~260~~ ~~258~~ ~~257~~ 255 bytes

```
exec'''def d(p,q):
 R=range;D=len(p);F=len(q)-1;d=q[0];q=[q[i]/-d@R(1,F+1)];r=[0@R(D)];a=[[0@R(F)]@R(D)]
@R(D):
  p[i]/=d;r[i]=sum(a[i])+p[i]
  for j in R(F):
   if i<D-F:a[i+j+1][F-j-1]=r[i]*q[j]
 return r[:D-F],[d*i@r[D-F:]]'''.replace('@',' for i in ')

```

This executes:

```
def d(p,q):
 R=range;D=len(p);F=len(q)-1;d=q[0];q=[q[i]/-d for i in R(1,F+1)];r=[0 for i in R(D)];a=[[0 for i in R(F)] for i in R(D)]
 for i in R(D):
  p[i]/=d;r[i]=sum(a[i])+p[i]
  for j in R(F):
   if i<D-F:a[i+j+1][F-j-1]=r[i]*q[j]
 return r[:D-F],[d*i for i in r[D-F:]]

```

Use like so:

```
>>>d([12., -5., 3., -1.],[1.,0.,-5.])
([12.0, -5.0], [63.0, -26.0])

```

# Answer
> 4 votes
## Haskell, 126

For a start:

```
l s _ 0=s
l(x:s)(y:t)n=x/y:l(zipWith(-)s$map(*(x/y))t++repeat 0)(y:t)(n-1)
d s t=splitAt n$l s t n where n=length s-length t+1

```

Sample use:

```
*Main> d [12, -5, 3, -1] [1, 0, -5]
([12.0,-5.0],[63.0,-26.0])

```

# Answer
> 3 votes
## Javascript with lambdas, 108

```
f=(a,b)=>{for(n=b.length;a.length>=n;a.shift())for(b.push(k=a[q=0]/b[0]);q<n;++q)a[q]-=k*b[q];b.splice(0,n)}

```

It replaces first argument by reminder and second by result.

Example of usage in Firefox:

```
f(x=[12,-5,3,-1], y=[1,0,-5]), console.log(x, y)
// Array [ 63, -26 ] Array [ 12, -5 ]

```

Sorry for the bug. Already fixed.

# Answer
> 3 votes
# APL (Dyalog Unicode) 18.0, 63 bytes

```
{0≥d←1+⍺-⍥≢⍵:⍬⍺⋄q(r↓⍨⊥⍨0=⌽r←⍺-m+.×q←(d↑⍺)⌹d↑m←⍉{⍵,⍨⍺⍴0}∘⍵⍤0⍳d)}

```

Try it online!

The TIO link (which uses 17.1) has a polyfill for .

Well, it uses  to solve a system of equations, but technically it's not a library, so...

### How it works

Illustration for the inputs `x←12 ¯5 3 ¯1` and `y←1 0 ¯5`:

* We know that, from the lengths of `x` and `y`, the quotient will have two terms.
* Construct a matrix which, when matrix-multiplied with the quotient, will give the polynomial product of quotient with `y`:

```
 1  0
 0  1
¯5  0
 0 ¯5

```
* Calculate the quotient `q` so that first two terms of `x` agree with those of `y×q`, using matrix division .
* Calculate the remainder `r` using `x - y×q`, then remove leading zeros of `r`. (`q` is guaranteed to have no leading zeros.)

```
{ ⍝ x←dividend, y←divisor
  d←1+⍺-⍥≢⍵  ⍝ Degree of the quotient; 1 + length of x - length of y
  0≥d: ⍬⍺    ⍝ If degree is zero or lower: quotient is zero, remainder is x

  m←⍉{⍵,⍨⍺⍴0}∘⍵⍤0⍳d  ⍝ Construct the matrix
                 ⍳d  ⍝ 0..d-1
     {      }∘⍵⍤0    ⍝ For each number i, yielding a matrix row
      ⍵,⍨⍺⍴0         ⍝ Make i copies of 0, and append y
                     ⍝ (Implicitly right-pad with zeros for short rows)
    ⍉                ⍝ Transpose

  q←(d↑⍺)⌹d↑m  ⍝ Get the quotient
          d↑m  ⍝ Take first d rows of the matrix
    (d↑⍺)      ⍝ Take first d numbers of x
         ⌹     ⍝ Matrix divide aka. solve linear system of equations

  r←⍺-m+.×q  ⍝ Get the remainder

  q(r↓⍨⊥⍨0=⌽r)  ⍝ Remove leading zeros from r, and join with q
       ⊥⍨0=⌽    ⍝ Reverse r, test equal to zero, and count trailing ones (⊥⍨)
    r↓⍨         ⍝ Drop that many numbers from start of r
  q(         )  ⍝ Join with q
}

```

---
Tags: code-golf, math, abstract-algebra, polynomials
---


title: In The Jailhouse Now

text:
# Question
Title: In The Jailhouse Now
# Challenge

Given an integer `n` (where `4<=n<=10**6`) as input create an ASCII art "prison door"\* measuring `n-1` characters wide and `n` characters high, using the symbols from the example below.

---

## Example

```
╔╦╗
╠╬╣
╠╬╣
╚╩╝

```

The characters used are as follows:

```
┌───────────────┬─────────┬───────┐
│ Position      │ Symbol  │ Char  │
├───────────────┼─────────┼───────┤
│ Top Left      │    ╔    │ 9556  │
├───────────────┼─────────┼───────┤
│ Top           │    ╦    │ 9574  │
├───────────────┼─────────┼───────┤
│ Top Right     │    ╗    │ 9559  │
├───────────────┼─────────┼───────┤
│ Right         │    ╣    │ 9571  │
├───────────────┼─────────┼───────┤
│ Bottom Right  │    ╝    │ 9565  │
├───────────────┼─────────┼───────┤
│ Bottom        │    ╩    │ 9577  │
├───────────────┼─────────┼───────┤
│ Bottom Left   │    ╚    │ 9562  │
├───────────────┼─────────┼───────┤
│ Left          │    ╠    │ 9568  │
├───────────────┼─────────┼───────┤
│ Inner         │    ╬    │ 9580  │
└───────────────┴─────────┴───────┘

```

---

## Rules

* You may take input by any reasonable, convenient means as long as it's permitted by standard I/O rules.
* For the purposes of this challenge, in languages where the symbols used to build the "door" are multi-byte characters, they may be counted towards your score as a single byte each.
* All other characters (single- or multi-byte) should be counted as normal.
* Output may not contain any trailing spaces but a trailing newline is permitted if absolutely necessary.
* This is so lowest byte count wins.

---

## Test Cases

```
Input: 4
Output:
╔╦╗
╠╬╣
╠╬╣
╚╩╝

Input: 8
Output:
╔╦╦╦╦╦╗
╠╬╬╬╬╬╣
╠╬╬╬╬╬╣
╠╬╬╬╬╬╣
╠╬╬╬╬╬╣
╠╬╬╬╬╬╣
╠╬╬╬╬╬╣
╚╩╩╩╩╩╝

Input: 20
Output:
╔╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╦╗
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╣
╚╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╩╝

```

* Yes, I'm aware that the bigger it gets the less it looks like a prison door! :D

# Answer
> 10 votes
# Java 11, ~~156~~ ~~151~~ ~~148~~ ~~118~~ 89 bytes

```
n->"╔"+"╦".repeat(n-=3)+"╗\n"+("╠"+"╬".repeat(n)+"╣\n").repeat(n+1)+"╚"+"╩".repeat(n)+"╝"

```

Try it online.

**Old 118 bytes answer in Java 8:**

```
n->{String a="╔",b="╠",c="╚";for(int i=n;i-->3;a+="╦",b+="╬")c+="╩";a+="╗\n";for(b+="╣\n";n-->2;)a+=b;return a+c+"╝";}

```

-30 bytes by creating a port of *@raznagul* C# (.NET Core) answer, after I golfed 5 bytes.

Try it here.

**Explanation:**

```
n->                    // Method with integer parameter and String return-type
  "╔"                  //  The top-left corner
  +"╦"                 //  Appended with the top edge
      .repeat(n-=3)    //  Repeated input-3 times (-2 for the corners, -1 for width)
  +"╗\n"               //  Appended with the top-right corner and a newline
  +("╠"                //   The left edge
    +"╬"               //   Appended with the middle part
        .repeat(n)     //   Repeated input-3 times (-2 for edges, -1 for width)
    +"╣\n"             //   Appended with the right edge and a newline
          ).repeat(n+1)//  And repeat this entire line n-2 times (-2 for first/last rows)
  +"╚"                 //  Appended with the bottom-left corner
  +"╩"                 //  Appended with the bottom edge
      .repeat(n)       //  Repeated input-3 times
  +"╝"                 //  Appended with the bottom-right corners

```

# Answer
> 8 votes
# Charcoal, 34 - 5 = 29 bytes

```
Ａ⁻Ｎ³γＵＢ╬↓×╠γ╠¶╚×╩γ‖ＢＯγ‖ＢＯ↑⁺γ

```

Try it online! Link is to verbose version of code. 5 byte reduction is for box drawing characters.

`ReflectOverlapOverlap(0)` should be equivalent to `ReflectMirror()` but instead Charcoal just does a `ReflectTransform()` instead, otherwise this solution would also work for `n=3`. Here's a workaround which shows what would happen for `n=3` for 38 - 5 = 33 bytes:

```
Ａ⁻Ｎ³γＵＢ╬↓×╠γ╠¶╚×╩γ¿γ‖ＢＯγ‖Ｍ‖ＢＯ↑⁺γ¹

```

Better still, if `ReflectOverlapOverlap(0)` worked, but I didn't bother supporting `n=3`, then I could do this for 31 - 4 = 27 bytes:

```
Ａ⁻Ｎ³γＵＢ╬↓×╠γ╚×╩γ‖ＢＯγ‖ＢＯ↑⁻γ¹

```

# Answer
> 6 votes
# Charcoal, ~~44~~ 42 bytes

Crossed out 44 is still regular 44

```
Ａ⁺±³ＮαＡ⁺¹αω╔×α╦¦╗Ｊ⁰¦¹×ω╠
¦╚×α╩¦╝Ｍ↖↑×ω╣Ｍ↙¤╬

```

Try it online!

# Answer
> 6 votes
## Haskell, 75 bytes

```
w i(a:b:c)=a:(b<$[4..i])++c
f n=concat$w(n+1)$w n<$>["╔╦╗\n","╠╬╣\n","╚╩╝"]

```

Try it online!

Function `w` takes an integer `i` and a list where `a` is the first, `b` the second element and `c` the rest of the list and makes a new list `a`, followed by `i-3` copies of `b`, followed by `c`. Apply `w` first on each each element of the list `["╔╦╗\n","╠╬╣\n","╚╩╝"]` and then again (with `i` increased by `1`) on the resulting list. Concatenate into a single list.

# Answer
> 5 votes
# GNU sed, 74 + 1 = 75 bytes

+1 byte for `-r` flag. Takes input as a unary number.

```
s/1111(1*)/╔╦\1╗\n;\1╠╬\1╣\n╚╩\1╝/
:
s/(.)1/\1\1/
t
s/;([^;\n]+)/\1\n\1/
t

```

Try it online!

# Explanation

This is pretty simple. Suppose the input is 6 (unary 111111). The first line drops four `1`s and transforms the remaining input into this:

```
╔╦11╗
;11╠╬11╣
╚╩11╝

```

The third line, in a loop, replaces every `1` with the character preceding it. This creates our columns:

```
╔╦╦1╗
;11╠╬11╣
╚╩11╝

╔╦╦╦╗
;11╠╬11╣
╚╩11╝

...

╔╦╦╦╗
;;;╠╬╬╬╣
╚╩╩╩╝

```

Notice that this has also duplicated the `;` character. Finally, the fifth line, in a loop, replaces every `;` character with a copy of the line that follows:

```
╔╦╦╦╗
;;╠╬╬╬╣
╠╬╬╬╣
╚╩╩╩╝

╔╦╦╦╗
;╠╬╬╬╣
╠╬╬╬╣
╠╬╬╬╣
╚╩╩╩╝

╔╦╦╦╗
╠╬╬╬╣
╠╬╬╬╣
╠╬╬╬╣
╠╬╬╬╣
╚╩╩╩╝

```

# Answer
> 5 votes
# Vim, 29 bytes

```
3<C-x>C╔╦╗
╠╬╣
╚╩╝<Esc>h<C-v>kkx@-Pjyy@-p

```

Since there are control characters, here's an xxd dump:

```
00000000: 3318 43e2 9594 e295 a6e2 9597 0de2 95a0  3.C.............
00000010: e295 ace2 95a3 0de2 959a e295 a9e2 959d  ................
00000020: 1b68 166b 6b78 402d 506a 7979 402d 70    .h.kkx@-Pjyy@-p

```

Try it online! (The V interpreter seems to have issues with exotic characters, so that link uses more mundane ones.)

## Explanation

```
3<C-x>     " Decrement the number by 3
C╔╦╗
╠╬╣
╚╩╝<Esc>   " Cut the number (goes in @- register) and enter the "template"
h<C-v>kkx  " Move to the middle column, highlight and cut it
@-P        " Paste @- copies of the cut column
jyy        " Move to the middle line and copy it
@-p        " Paste @- copies of the copied line

```

# Answer
> 4 votes
# Jelly, 33 bytes

*...is it 33? - it costs 5 to convert from one byte string literals (code page indexes) to the Unicode characters.*

```
_2µ“€ðÐ‘ẋ“¡Ø¤“©ßµ‘js3x€2¦€’+⁽"7ỌY

```

A full program printing the result.

**Try it online!**

### How?

```
_2µ“€ðÐ‘ẋ“¡Ø¤“©ßµ‘js3x€2¦€’+⁽"7ỌY - Main link: n
_2                                - subtract 2
  µ                               - start a new monadic chain with n-2 on the left
   “€ðÐ‘                          - code page indexes [12, 24, 15] (middle row characters)
        ẋ                         - repeat n-2 times (make unexpanded middle rows)
         “¡Ø¤“©ßµ‘                - code page indexes [[0,18,3],[6,21,9]] (top & bottom)
                  j               - join (one list: top + middles + bottom)
                   s3             - split into threes (separate into the unexpanded rows)
                          ’       - decrement n-2 = n-3
                        ¦€        - sparsely apply to €ach:
                       2          -   at index 2
                     x€           -   repeat €ach (expand centre of every row to n-3 chars)
                            ⁽"7   - literal 9556
                           +      - addition (0->9556; 12->9568; etc...)
                               Ọ  - cast to characters (╠; ╔; etc...)
                                Y - join with newlines
                                  - implicit print

```

# Answer
> 4 votes
# Rockstar, ~~150~~ 104 bytes

```
Listen to B
let B be-3
X's-1
say "╔"+"╦"*B+"╗"
While B-X
say "╠"+"╬"*B+"╣"
let X be+1

say "╚"+"╩"*B+"╝"

```

Copy Paste it here!

-46 bytes from Shaggy.

I was inspired by Shaggy from this comment.

Here's the *real* rock song (sort of).

```
Listen to the bars
Knock the bars down, down, down
Let the end be the bars
Build the end up
Shout "╔"+"╦"*the bars+"╗"
While the end ain't nothing
say "╠"+"╬"*the bars+"╣"
Knock the end down

Shout "╚"+"╩"*the bars+"╝"
Let the prison be gone

```

# Answer
> 3 votes
# Python 3, 75 bytes

```
n=int(input())-3
print("╔"+"╦"*n+"╗\n"+("╠"+"╬"*n+"╣\n")*-~n+"╚"+"╩"*n+"╝")

```

Try it online!

# Answer
> 3 votes
# Japt, ~~60 52 49 48~~ 36 bytes

```
"╔{Uµ3 ç'╦}╗{UÄ ç"
╠{ç'╬}╣"}
╚{ç'╩}╝

```

Try it online!

# Another version (47 bytes + `-R` flag)

```
"8{Uµ3 ç'J};{UÄ ç"D{ç'P}G"}>{ç'M}A"c_+9500ÃòU+2

```

Needs the `-R` flag (added to the input field). Try it online!

## How does it work?

Because I originally assumed the 'door-characters' cost more than one byte, I figured I could save quite a few bytes by encoding them. Then, I subtracted 9500 from the character codes, which left me with the characters `8J; DPG >MA`, which only cost one byte each. Then, I could just add 9500 to each character code, and all would be well.

```
 "8{   Uµ 3 ç'J}  ;{   UÄ  ç"D{   ç'P}  G"}  >{   ç'M}  A"c_+9500Ã òU+2
 "8"+((U-=3 ç'J)+";"+((U+1 ç"D"+(Uç'P)+"G")+">"+(Uç'M)+"A"c_+9500} òU+2
 "8"+           +";"+                      +">"+      +"A"              # Take this string of characters
     ((U-=3 ç'J)                                                        # Repeat "J" input - 3 times
                     ((    ç              )                             # Repeat the string
                            "D"+(Uç'P)+"G"                              # "D" + input-3 times "P" + "G"
                       U+1                                              # Input - 2 times
                                                (Uç'M)                  # Repeat "M" input - 3 times
                                                          c_     }      # Take the character code of every character
                                                            +9500       # Add 9500 to it
                                                          c_     }      # And convert it back to a character
                                                                   òU+2 # Split this string on every (input)th character
                                                                        # Print the resulting array, joined with newlines.

```

# Answer
> 3 votes
# Dyalog APL, 71 bytes

```
{('╔',('╠'⍴⍨⍵-2),'╚'),((⍵-3)\⍪('╦',('╬'⍴⍨⍵-2),'╩')),'╗',('╣'⍴⍨⍵-2),'╝'}

```

Try it online!

# Answer
> 3 votes
# Ruby, ~~54~~ 52 bytes

-2 bytes thanks to ymbirtt.

```
->n{?╔+?╦*(n-=3)+"╗
"+(?╠+?╬*n+"╣
")*-~n+?╚+?╩*n+?╝}

```

Try it online!

## Ungolfed

This is super boring:

```
->n{
   ?╔ + ?╦ * (n-=3) + "╗\n" +
  (?╠ + ?╬ * n      + "╣\n") * -~n +
   ?╚ + ?╩ * n      + ?╝
}

```

# Answer
> 3 votes
# C# (.NET Core), ~~Score 123 (141 bytes)~~ Score 118 (136 bytes)

```
n=>{string a="╔",b="╠",c="╚";for(int i=3;i++<n;a+="╦",b+="╬")c+="╩";a+="╗\n";for(b+="╣\n";n-->2;)a+=b;return a+c+"╝";}

```

Try it online!

-5 bytes thanks to @KevinCruijssen

### Explanation:

```
n =>
{
    string a = "╔", b = "╠", c = "╚"; //Initialize the first, last and the middle lines with the starting character.
    for (int i = 3; i++ < n;          //Loop n-3 times
        a += "╦", b += "╬")           //Add the middle character to the first and middle line.
        c += "╩";                     //Add the middle character to the last line.
    a += "╗\n";                       //Add the end character to the first line.
    for (b += "╣\n";                  //Add the end character to the first line.
        n-- > 2;)                     //Loop n-2 times.
        a += b;                       //Add the middle line to the first line.
    return a + c + "╝";               //Add the last line and the final character and return.
}

```

# Answer
> 3 votes
# Java 8, 102 + 101 bytes

```
java.util.function.BiFunction<String,Integer,String>r=(c,n)->"".valueOf(new char[n]).replace("\0",c);

n->{n-=3;return "╔"+r.apply("╦",n)+"╗\n"+r.apply('╠'+r.apply("╬",n)+"╣\n",-~n)+"╚"+r.apply("╩",n)+"╝";}

```

This is another string repeater of the same length:

```
java.util.function.BiFunction<String,Integer,String>r=(c,n)->{String p=c;for(;--n>0;p+=c);return p;}

```

Try it online!

# Answer
> 3 votes
# Stax, 23 bytes

```
÷ÅoB↔╒╢Fm|╦a⌐á5µ┐»♫÷d╕Ñ

```

Run and debug it

Here's the ungolfed version. Amusingly, it's actually smaller for stax *not* to use the literal characters because including them as a literal would prevent source packing.

```
"2Pfj_EQGG]T"!  packed representation of the 9 characters
3/              split into groups of 3
GG              call into trailing program twice
m               print each row
}               trailing program begins here
1|xv\           [1, --x - 1]; x starts as original input
:B              repeat each element corresponding number of times
                effectively, this repeats the internal row of the matrix
M               transpose door; this way it expands the two dimensions

```

Run this one

# Answer
> 2 votes
# JavaScript (ES6), ~~80~~ 74 bytes

```
n=>`╔${"╦"[a="repeat"](n-=3)}╗${`
╠${"╬"[a](n)}╣`[a](n+1)}
╚${"╩"[a](n)}╝`

```

# Answer
> 2 votes
# 05AB1E, 29 bytes

```
3-…╩╬╦S×`…╔ÿ╗Š…╠ÿ╣IÍ×s…╚ÿ╝Jä»

```

Try it online!

# Answer
> 2 votes
# QBIC, 78 bytes

```
[:-3|X=X+@╦`]?@╔`+X+@╗`[b-2|Y=Z[b-3|Y=Y+@╬`]?@╠`+Y+@╣`}[b-3|W=W+@╩`]?@╚`+W+@╝`

```

Fortunately, all of the symbols used in out cell door are on the QBasic codepage.

## Explanation

```
            The TOP
[:-3|       FOR a = 1 to n-3 (-1 for the width, -2 for beginning and end)
X=X+@╦`]    Build out X$ with the parts of the middle-top
?@╔`+X+@╗`  Then print that preceded and followed by the corners
┘           Syntactic linebreak

            The MIDDLE
[b-2|       FOR c = 1 to n-2 (all the middle rows)
Y=Z         Reset Y$ to ""
            Build up the middle rows in the same way as the top,
            just with different symbols and once for each middle row
[b-3|Y=Y+@╬`]?@╠`+Y+@╣`
}           Close the FOR loop
            The BOTTOM
            The same as the top, just with different symbols
[b-3|W=W+@╩`]?@╚`+W+@╝`

```

## Sample Output

```
Command line: 7

╔╦╦╦╦╗
╠╬╬╬╬╣
╠╬╬╬╬╣
╠╬╬╬╬╣
╠╬╬╬╬╣
╠╬╬╬╬╣
╚╩╩╩╩╝

```

# Answer
> 2 votes
# Swift, 161 bytes

```
let f:(String,Int)->String={String(repeating:$0,count:$1)};var p={i in print("╔\(f("╦",i-3))╗\n\(f("╠\(f("╬",i-3))╣\n",i-2))╚\(f("╩",i-3))╝")}

```

Un-golfed:

```
let f:(String,Int)->String = {
    String(repeating:$0,count:$1)
}
var p={ i in
    print("╔\(f("╦",i-3))╗\n\(f("╠\(f("╬",i-3))╣\n",i-2))╚\(f("╩",i-3))╝")
}

```

You can try this answer out here

# Answer
> 2 votes
# PHP, 131 bytes, 113 chars

```
for($z=str_split("╔╠╚╦╬╩╗╣╝",3);$i<$a=$argn;)echo str_pad($z[$b=$i++?$i<$a?1:2:0],3*$a-3,$z[$b+3]),$z[$b+6],"\n";

```

Try it online!

# PHP, 133 bytes, 115 chars

```
for(;$i<$a=$argn;)echo str_pad(["╔","╠","╚"][$b=$i++?$i<$a?1:2:0],3*$a-3,["╦","╬","╩"][$b]),["╗","╣","╝"][$b],"\n";

```

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), 86 bytes

This is significantly longer than the other JS answer, but I wanted to give it a try with an alternate method.

```
n=>(g=i=>--i?`╬╣╠╩╝╚╦╗╔
`[(j=i%n)?!--j+2*!(n-j-2)+3*(i<n)+6*(i>n*n-n):9]+g(i):'')(n*n)

```

### How?

We assign a weight to each edge of the grid: 1 for right, 2 for left, 3 for bottom and 6 for top. The sum of the weights gives the index of the character to use.

```
8666667    0 1 2 3 4 5 6 7 8
2000001    ╬ ╣ ╠ ╩ ╝ ╚ ╦ ╗ ╔
2000001
2000001
2000001
2000001
2000001
5333334

```

### Demo

```
let f =

n=>(g=i=>--i?`╬╣╠╩╝╚╦╗╔
`[(j=i%n)?!--j+2*!(n-j-2)+3*(i<n)+6*(i>n*n-n):9]+g(i):'')(n*n)

console.log(f(8))
```

# Answer
> 2 votes
# Retina, ~~56~~ 50 bytes

```
.+
$*╬╣
^╬╬╬
╠
.?
$_¶
T`╠╬╣`╔╦╗`^.*
T`╠╬╣`╚╩╝`.*¶$

```

Try it online! Works by building up a square of ╬s and then fixing up the edges (in particular three colums are deleted when the sides are added).

# Answer
> 2 votes
## Batch, 126 bytes

```
@set s=
@for /l %%i in (4,1,%1)do @call set s=%%s%%Î
@echo É%s:Î=Ë%»
@for /l %%i in (3,1,%1)do @echo Ì%s%¹
@echo È%s:Î=Ê%¼

```

Works in CP437 or CP850. Looks like this in those code pages:

```
@set s=
@for /l %%i in (4,1,%1)do @call set s=%%s%%╬
@echo ╔%s:╬=╦%╗
@for /l %%i in (3,1,%1)do @echo ╠%s%╣
@echo ╚%s:╬=╩%╝

```

# Answer
> 2 votes
# PowerShell, 67 bytes

```
'╔'+'╦'*($x=$args[0]-3)+'╗';,('╠'+'╬'*$x+'╣')*($x+1);'╚'+'╩'*$x+'╝'

```

Takes input `$args[0]`, subtracts `3`, saves that into `$x`, uses that in the construction of the top of the door to output the appropriate number of middle sections. Then we're outputting the middle rows, of which we have `$x+1` of. Finally, the bottom row is similar to the top row. All of those are left on the pipeline, and the implicit `Write-Output` inserts a newline between elements for free.

Try it online!

# Answer
> 2 votes
# Perl 5, 61

60 characters of code (90 including the multibyte door characters) + 1 for `-p`

```
$_='╔'.'╦'x($n=$_-3)."╗\n";$_.=y/╔╦╗/╠╬╣/r x++$n.y/╔╦╗/╚╩╝/r

```

Try it online!

# Answer
> 2 votes
# C# (.NET Core), 130 bytes

```
n=>"╔"+R("╦",n-=3)+"╗\n"+R("╠"+R("╬",n)+"╣\n",-~n)+"╚"+R("╩",n)+"╝";string R(string c,int n){string r=c;for(;n-->1;r+=c);return r;}

```

Port of *@RobertoGraham*'s Java 8 answer, after I golfed about 70 bytes.

Try it online.

# Answer
> 2 votes
# MAWP, 73 bytes

```
@=MM"╔":!3-["╦":1-]`"╗
":2-["╠":M3-["╬":1-]`"╣
":1-]`"╚":M3-["╩":1-]`"╝":

```

Try it!

Note the strings with newlines

# Answer
> 1 votes
# Mathematica, 106 bytes

```
(T[a_,b_,c_]:=a<>Table[b,#-3]<>c;w=Column;w[{T["╔","╦","╗"],w@Table[T["╠","╬","╣"],#-2],T["╚","╩","╝"]}])&

```

# Answer
> 1 votes
# oK, 38 chars

```
`0:"╔╠╚╦╬╩╗╣╝"{+x+/:3*0,2_x}@&1,|1,-2+

```

Try it online.

k does not seem to want to handle unicode well, so I went with oK.

# Answer
> 1 votes
# , ~~41~~ 37 bytes

```
ucp@'╬╠╣╦╔╗╩╚╝'{~1 1|.{.&6 3+/<:{.2,*

```

Try it online!

Default box drawing takes 13 bytes, unfortunately the best way of replacing the characters I could find costs 28.

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


title: 8-bit Chess Pixel Counting

text:
# Question
Title: 8-bit Chess Pixel Counting
# Goal

You're playing a computerised chess game. The display is in black and white only and the pixels are chunky. White pixels use a lot power compared to black pixels and you're concerned about your carbon footprint.

Given a square and a piece in chess notation, return the number of white pixels displayed in the square.

The solution may be in the form of a function or a complete program.

# Input

A 4-character string defining:

1. One of `wb` for a white or black piece. (Not part of normal Chess notation, but required for this puzzle.)
2. One of `KQBNRP` for a King, Queen, Bishop, kNight, Rook or Pawn.
3. One of `abcdefgh` for the piece's file (column).
4. One of `12345678` for the piece's rank (row).

# Output

The number of white pixels used to draw the chess piece and the underlying square.

# Requirements

* Chess squares are 8x8 pixels and are either all white or all black.
* `a1` is a black square.
* White chess pieces are drawn as white with a black outline. Black pieces are black with a white outline. All pieces have transparent pixels which show the underlying square.
* Input is case-sensitive.
* Assume the input is valid.

The chess pieces have sprites as follows.
`.` is the piece's colour.
`#` is the inverse of the piece's colour.
`/` is the underlying square's colour.

```
King        Queen       Bishop
////////    ////////    ////////
///#.#//    /#.#.#.#    ///#.#//
//#...#/    //#...#/    //##..#/
///#.#//    ///###//    //#.#.#/
///###//    //#...#/    ///###//
//#...#/    //#...#/    //#...#/
//#...#/    //#...#/    //#...#/
//#.#.#/    //#.#.#/    //#.#.#/

kNight      Rook        Pawn
////////    ////////    ////////
////////    /#.#.#.#    ////////
//#..#//    /#.....#    ////////
/#....#/    /##...##    ///#.#//
///#..#/    //#...#/    //#...#/
//#..#//    //#...#/    ///#.#//
//#...#/    //#...#/    //#...#/
//#...#/    //#...#/    //#...#/

```

The number of pixels in the piece's colour, piece's outline and underlying square for each piece is:

```
Piece    Fill  Outline  Square
==============================
King     13    16       35
Queen    17    18       29
Bishop   13    18       33
Knight   16    12       36
Rook     23    18       23
Pawn     11    10       43

```

# Test Cases

```
Input  Output
wRa1   23
bRa1   18
wPc2   54
bKg8   51

```

# Scoring

The shortest code in bytes by Christmas Day gets a little something extra in their stocking.

# Answer
> 2 votes
# Pyth, ~~54~~ 53 bytes

The code contains unprintable characters, so here is a reversible `xxd` hexdump:

```
0000000: 732a 562b 5f57 2543 687a 322c 3031 2573  s*V+_W%Chz2,01%s
0000010: 434d 7474 7a32 4063 434d 2e22 0a2b 011e  CMttz2@cCM.".+..
0000020: d699 71d0 c6dc 3db8 eeae 2233 252a 4368  ..q...=..."3%*Ch
0000030: 747a 5433 31                             tzT31

```

Alternatively, here's a copy-paste friendly version, which you can also try online or use the test suite:

```
s*V+_W%Chz2,01%sCMttz2@cCM."\n+\x01\x1e\xd6\x99q\xd0\xc6\xdc=\xb8\xee\xae"3%*ChtzT31

```

# Answer
> 6 votes
# C#6, 107 bytes

Here's my own answer. I don't expect any points being the one who posed the challenge.

I have taken some inspiration from user81655's answer.

```
long P(string a)=>(a[0]>99?12201284685:11042628752)+(a[2]+a[3])%2*46566348643>>"KQBNRP".IndexOf(a[1])*6&63;

```

The pixel counts are encoded in 6-bit blocks. The outline or fill is added to the square (if it's white). Finally, the 6-bit block for the appropriate piece is extracted.

Thankfully, operation precedence worked heavily in my favor.

# Answer
> 5 votes
# JavaScript (ES6), 106

As an anonymous function.

```
x=>(o=+'137999'[p='PNKBQR'.search(x[1])],f=+'262149'[p]+p,(parseInt(x[2]+x[3],19)%2?9:55-f-o)+(x>'w'?f:o))

```

By now, I'm following the simplest way of find the answer with a calculation - this could be not the best way.

Over a black square, the answer is the size of fill for white pieces and the size of outline for black pieces. Over a white square, you need to add the free space. See the table below (inside the snippet)

I keep the size of fill and outline for each piece, the free space inside the square can be found subtracting from 64. To save space, the outline in stored as a single digit afer subtracing 9. The fill is trickier as the range is wider, check the code (that's way the pieces are sorted by occupied space)

Test snippet:

```
F=x=>(
  o=+'137999'[p='PNKBQR'.search(x[1])], // get outline - 9
  f=+'262149'[p]+p, // get fill -9
  (
    parseInt(x[2]+x[3],19) // parse with an odd base the differentiate between odd and even rows
    %2?9:55-f-o // black square if odd,, white if even so calc free space
  ) +(x>'w'?f:o) // add fill or outline based on piece color
)

// Test suite

console.log=x=>O.innerHTML+=x+'\n'

for(i=0; z='PNKBQR'[i]; i++)
{
  o = '';
  t = 'w'+z+'c2'; // white piece, white square
  o += t+' '+F(t)+', '
  t = 'b'+z+'c2'; // black piece, white square
  o += t+' '+F(t)+', '
  t = 'w'+z+'a1'; // white piece, black square
  o += t+' '+F(t)+', '
  t = 'b'+z+'a1'; // black piece, black square
  o += t+' '+F(t)
  console.log(o);
}
```

```
<pre>
Piece    Fill  Outline  Free  w/w b/w w/b b/b
=============================================
Pawn     11    10       43     54  53  11  10
Knight   16    12       36     52  48  16  12
King     13    16       35     48  51  13  16
Bishop   13    18       33     46  51  13  18
Queen    17    18       29     46  47  17  18
Rook     23    18       23     46  41  23  18
</pre>
<pre id=O></pre>
```

# Answer
> 3 votes
# JavaScript (ES6), ~~135~~ 112 bytes

```
s=>(c={K:`\u000a\u0010\u0023`,Q:`\u0011\u0012\u001d`,B:`\u000a\u0012\u0021`,N:`\u0010\u000c\u0024`,R:`\u0017\u0012\u0017`,P:`\u000b\u000a\u002b`}[s[1]])[f="charCodeAt"](s<"w")+((s[f](2)-s[3])%2&&c[f](2))

```

Every `\u00xx` should be a single one-byte character. They are represented here as codes because Stack Exchange automatically removes unreadable characters from posts.

## Explanation

```
s=>

  // c = string of three (mostly unreadable) characters, the ASCII code of each character
  //     represents the number of pixels in the fill, outline and square respectively
  (c={
    K:`\u000a\u0010\u0023`,
    Q:`\u0011\u0012\u001d`,
    B:`\u000a\u0012\u0021`,
    N:`\u0010\u000c\u0024`,
    R:`\u0017\u0012\u0017`,
    P:`\u000b\u000a\u002b`
  }[s[1]])

  [f="charCodeAt"](s<"w") // if piece is black add outline pixels, else add fill pixels
  +((s[f](2)-s[3])%2      // this returns 1 if the square is white or 0 if black
    &&c[f](2))            // if the square is white add the square's pixels

```

## Test

```
var solution = s=>(c={K:`\u000a\u0010\u0023`,Q:`\u0011\u0012\u001d`,B:`\u000a\u0012\u0021`,N:`\u0010\u000c\u0024`,R:`\u0017\u0012\u0017`,P:`\u000b\u000a\u002b`}[s[1]])[f="charCodeAt"](s<"w")+((s[f](2)-s[3])%2&&c[f](2))
```

```
<input type="text" id="input" value="bKg8" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 2 votes
# JavaScript (Node.js), 84 bytes

```
s=>[a=~"0628"[[C,P,F,R]=Buffer(s),i=P%11%7],b=-"63682"[i]||4][C&1]+(F+R&1?45-a-b:19)

```

Try it online!

### How?

The color, the piece, the file and the rank characters are turned into ASCII codes which are saved into \\$C\\$, \\$P\\$, \\$F\\$ and \\$R\\$ respectively.

We compute the piece index \\$i=(P \bmod 11)\bmod 7\\$:

```
 char. | code | mod 11 | mod 7
-------+------+--------+-------
  'B'  |  66  |    0   |   0        Reordered by index:
  'K'  |  75  |    9   |   2
  'N'  |  78  |    1   |   1         0 | 1 | 2 | 3 | 4 | 5
  'P'  |  80  |    3   |   3        ---+---+---+---+---+---
  'Q'  |  81  |    4   |   4         B | N | K | P | Q | R
  'R'  |  82  |    5   |   5

```

We compute \\$a\\$, which is the number of outline squares for the piece, minus \\$19\\$:

```
a = ~"0628"[i]

```

We compute \\$b\\$, which is the number of filled squares for the piece, minus \\$19\\$:

```
b = -"63682"[i] || 4

```

We use `C & 1` to figure out the color of the piece and `F + R & 1` to figure out the color of the square.

The final result is:

```
[a, b][C & 1]    // use outline squares if the piece is black
+                // or filled squares if the piece is white
(                //
  F + R & 1 ?    // if the square is white:
    45 - a - b   //   add 19 + (64 - ((a + 19) + (b + 19)))
                 //   = 45 - a - b
  :              // else:
    19           //   just add 19
)                //

```

# Answer
> 1 votes
# Lua, 158 155 Bytes

```
c,p,l,n=(...):byte(1,4)m="KQBNRP"d={}d[1]={13,17,13,16,23,11}d[0]={16,18,18,12,18,10}p=m:find(string.char(p))print(d[c%2][p]+(l+n)%2*(64-d[0][p]-d[1][p]))

```

Could probably reduce the byte count by encoding the data, but I kinda like the current table method.

Bases color of the square on the ASCII value of 'w' or 'b' taking advantage of the fact that one is even and one is odd. Assigns integer value of the piece based on the position of the piece's symbol in the `m` string variable. Whether a square is dark or light is handled by `(l+n)%2` taking advantage of ASCII value again.

**Ungolfed**

```
c,p,l,n=(...):byte(1,4)   --stores input of all characters into variables
m="KQBNRP"                --piece encoded string
d={}                      --data table
d[1]={13,17,13,16,23,11}  --fill
d[0]={16,18,18,12,18,10}  --outline
p=m:find(string.char(p))  --position in string for position in tables
print(d[c%2][p] +         --takes data element from corresponding table according to color of piece and type of piece
     (l+n)%2  *           --is square black or white? 0 if back, 1 if white
     (64-d[0][p]-d[1][p]) --if white, pixels not used by piece would be area (64) minus pixels used by piece, or corresponding data in the tables
     )

```

-3 Bytes by removing `c=c%2` before the `print` and using `d[c%2][p]` instead of `d[c][p]`.

# Answer
> 1 votes
# 05AB1E, 41 bytes

```
Ç`+É•wH˜OÝ•44в*s11%©è•2ĀpakΩÕðβ•₂в2ä+sè®è

```

Try it online or verify all test cases.

**Explanation:**

```
Ç                          # Convert the (implicit) input to a list of codepoint integers
 `                         # Pop and push the four integers separated to the stack
  +                        # Add the top two together (column+row)
   É                       # Check if this is odd (1 if odd/white; 0 if even/black)
    •wH˜OÝ•                # Push compressed integer 245530244740
     44в                   # Convert it to base-44 as list: [33,36,35,43,29,23,0]
        *                  # Multiply each value by the odd-check
         s                 # Swap so the piece is at the top of the stack
          11%              # Modulo-11 on that integer
             ©             # Store it in variable `®` (without popping)
              è            # Index (0-based modulair) it into the list
               •2ĀpakΩÕðβ• # Push compressed integer 45866137874521319810
                ₂в         # Convert it to base-26 as list:
                           #  [18,12,16,10,18,18,0,13,16,13,11,17,23,0]
                  2ä       # Split it into two equal-sized parts:
                           #  [[18,12,16,10,18,18,0],[13,16,13,11,17,23,0]]
                    +      # Add the earlier indexed value to each
                     s     # Swap to get the final integer at the top (square-color)
                      è    # Index (0-based modulair) it into this pair of lists
                       ®è  # And then index `®` (piece%11) into 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 `•wH˜OÝ•` is `245530244740`; `•wH˜OÝ•44в` is `[33,36,35,43,29,23,0]`; `•2ĀpakΩÕðβ•` is `45866137874521319810`; and `•2ĀpakΩÕðβ•₂в` is `[18,12,16,10,18,18,0,13,16,13,11,17,23,0]`.

The modulo-11 trick on the piece codepoint was inspired by *@Arnauld*'s JavaScript answer. The trailing `0`s in the lists are just fillers, since 05AB1E indexes modulair, so we don't need the modulo-7 that *Arnauld* uses.

Try it online for a step-by-step output.

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