title: Chessboard pattern

text:
# Question
Title: Chessboard pattern
**Input:** a positive number \\$n\\$, smaller than \\$80\\$, from stdin or as a command-line argument.

**Output:** A square chessboard pattern, the size of the input number. The dark fields are represented by the letter `X`, the white fields by a space. The top-left field should be `X`.

A complete program is required. This is so the shortest code in bytes wins

---

**Examples:**

**Input**: 1

**Output**:

```
X

```

**Input**: 8

**Output**:

```
X X X X
 X X X X
X X X X
 X X X X
X X X X
 X X X X
X X X X
 X X X X

```

# Answer
# Pyth, 13 chars

Note: Pyth is much too new to be eligible to win. However, it was a fun golf and I thought I'd share it.

```
VQ<*QX*d2N\XQ

```

Try it here.

How it works:

```
                       Q = eval(input())
VQ                     for N in range(Q):
  <         Q                                                        [:Q]
   *Q                                    (Q*                        )
     X*d2N\X                                assign_at(" "*2, N, "X")

```

Basically, this uses `X` to generate `"X "` or `" X"` alternately, then repeats that string `Q` times, and takes its first `Q` characters. This is repeated `Q` times.

How does the `X` (assign at) function work? It takes the original string, `" "` in this case, an assignment location, `N` in this case, and a replacement character, `"X"` in this case. Since Pyth's assignments are modular, this replaces the space at location `N%2` with an `X`, and returns the resultant string, which is therefore `"X "` on the first, third, etc. lines, and `" X"` on the others.
> 7 votes

# Answer
## Golfscript - 17 chars

```
~:N,{"X "N*>N<n}%

```

Analysis

`~` convert input to an int
`:N` store in the variable N
`,{...}` for each value of \[0...N-1\]
`"X "N*` repeat "X " to give a string of N\*2 characters
`>` take the substring starting from the loop index...
`N<` ...ending N characters later
`n` put a newline a the end of each string
> 12 votes

# Answer
## Perl, ~~41~~ 40

```
for$i(1..$_){say substr" X"x$_,$i%2,$_}

```

Perl 5.10 or later, run with `perl -nE 'code'` (`n` counted in code size)

Sample output:

```
$ perl -nE'for$i(1..$_){say substr" X"x 40,$i%2,$_}' <<<5
X X X
 X X
X X X
 X X
X X X
$ perl -nE'for$i(1..$_){say substr" X"x 40,$i%2,$_}' <<<8
X X X X
 X X X X
X X X X
 X X X X
X X X X
 X X X X
X X X X
 X X X X

```
> 6 votes

# Answer
### Python, 48 Characters

```
x,i=input(),0
exec'print(x*"X ")[i:i+x];i^=1;'*x

```
> 4 votes

# Answer
## Python, 76 characters

```
n=input()
p='X '*n
print n/2*(p[:n]+'\n'+p[1:n+1]+'\n'),
if n&1:print p[:n]

```
> 3 votes

# Answer
## Scala - 141 95 characters

```
var a=args(0).toInt
for(y<-1 to a;x<-1 to a)print((if((x+y)%2<1)"X"else" ")+("\n"*(x/a)take 1))

```

Usage: `scala filename N` where n is your input to the program.
> 3 votes

# Answer
## APL (16)

Assuming `⎕IO=0` (i.e. zero-indexed arrays, it is a setting)

```
' X'[=/¨2⊤¨⍳2⍴⎕]

```

Explanation:

* `⍳2⍴⎕`: read a number N, and create a N×N matrix containing (0,0) to (N-1,N-1).
* `2⊤¨`: get the least significant bit of each number in the matrix. (So now we have (0,0), (0,1), (0,0)... (1,0), (1,1), (1,0)...)
* `=/¨`: for each pair, see if the two numbers are equal. (Now we have 1 0 1 0 1 0 ...)
* `' X'[`...`]`: put a space for each 0 and an X for each 1.
> 3 votes

# Answer
## Ruby ~~45~~ 42

```
(x=gets.to_i).times{|i|puts ("X "*x)[i,x]}

```

Demo: http://ideone.com/Mw25e
> 3 votes

# Answer
# Brainfuck, 140 bytes

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

```
> 3 votes

# Answer
## C++ - 253 obfuscated characters

```
#include <iostream.h>
int main(int i,char*c[]=0)
{
  char a=i,b=i>>8;i&32512?((i>>16&255)<a)?(cout<<b)?main((i^30720)+65536):0:(cout<<endl)?(((b=(i>>24)+1)<a)?main((i&2130706559)+((b&1)?16785408:16799744)):0):0:main((i>=2?atoi(1[c]):8)|22528);
}

```
> 2 votes

# Answer
# JavaScript, 169

```
function b(w){var i=w,j=w,r='';while(i--){while(j--){if((i+j)%2)r+=' ';else r+='X'}j=w;r+="\n"}return r}do{n=parseInt(prompt('Number'))}while(isNaN(n)||n<1);alert(b(n));

```
> 2 votes

# Answer
# k (26 chars)

26 For bare function:

```
{-1',/x#',x#'("X ";" X");}

```

Or a further 7 to take input from stdin

```
{-1',/x#',x#'("X ";" X");}"I"$0:0

```
> 2 votes

# Answer
# Bash: 60 characters

```
yes X|fmt -w80|paste -d '' <(yes '
 ') -|head -$1|cut -c1-$1

```

The table size is passed as command-line parameter, for example `bash chesstable.sh 8`.
> 2 votes

# Answer
# APL (Dyalog Extended), 12 bytesSBCS

Anonymous tacit prefix function. Requires `⎕IO←0` (zero-based indexing).

```
'X '⊇⍨2|⍳+⍀⍳

```

Try it online!

**ɩ**ndices 0…n–1

`+⍀` plus table with that horizontally and vertically:

**ɩ**ndices 0…n–1

`2|` division remainder when divided by two

`'X '⊇⍨` use that matrix to index into the string
> 2 votes

# Answer
# Java 10, lambda function, ~~92~~ ~~87~~ 84 bytes

```
n->{for(int i=0;i<n*n;)System.out.print(((i%n+i/n)%2<1?"X":" ")+(++i%n<1?"\n":""));}

```

Try it online here.

Thanks to ceilingcat for golfing 4 bytes and to Kevin Cruijssen for golfing 3 more.

Ungolfed version:

```
n -> { // void lambda taking an int as argument
    for(int i = 0; i < n*n; ) // loop over the entire square
            System.out.print(((i%n + i/n) % 2 < 1 ? "X" : " ") // print an 'X' or a space depending on which line&column we're on
               + (++i % n < 1 ? "\n" : "")); // print a newline at the end of a line
}

```

# Java 8, full program, ~~155~~ 139 bytes

```
interface M{static void main(String[]a){int i=0,n=new Byte(a[0]);for(;i<n*n;)System.out.print(((i%n+i/n)%2<1?"X":" ")+(++i%n<1?"\n":""));}}

```

Try it online here.

Ungolfed version:

```
interface M {
    static void main(String[] a) {
        int i = 0, // iterator variable for the loop
            n = new Byte(a[0]); // take the argument and convert it to an int
        for(; i < n*n; ) // loop over the entire square
            System.out.print( ((i%n + i/n) % 2 < 1 ? "X" : " ") // print an 'X' or a space depending on which line&column we're on
                             +(++i % n < 1 ? "\n" : "") ); // print a newline at the end of a line
        }
    }
}

```
> 2 votes

# Answer
# Japt, ~~8~~ 7 bytes

```
ÆîSi'XY

```

Run it online

**~~7~~ 6 bytes** if we can replace `X` with `x`:

```
ÆîSixY

```

Run it online

---

Alternative **8 byte** solution:

```
Æî"X "éY

```

Run it online
> 2 votes

# Answer
# Python 2, 47 bytes

```
n=input()
s='X '*n
exec"print s[:n];s=s[1:];"*n

```

Try it online!

---

**Python 2, 47 bytes**

```
n=input()
i=0
exec"i^=1;print'X'*i+n/2*' X';"*n

```

Try it online!

Trims trailing space.
> 2 votes

# Answer
# Scala, 68 bytes

```
  def^(n:Int)=for(a<-1 to n)println(("x_"*n).substring(n%2+1,n+n%2+1))

```

or

```
  def^(n:Int)=for(a<-1 to n)println(("x_"*n).substring(a%2+1).take(n))

```

Try it online!
> 2 votes

# Answer
# MATL, 9 bytes

```
:&+o~88*c

```

Try it online!

ASCII `c` 88 multiplied `*` by not `~` the parity `o` of the broadcast self-addition `&+` of the range `:` from 1 to the input.
> 2 votes

# Answer
## Javascript, 67 bytes

```
for(j=n=readline()|0;j--;)console.log(' X'.repeat(n).substr(j%2,n))

```

Try it online

## C, 83 bytes

```
i,j;main(n){for(scanf("%d",&n);i++<n;puts(""))for(j=0;j<n;)putchar(i+j++&1?88:32);}

```

Try it online

## Basic C64, 89 bytes

```
1 INPUTN:FORI=1TON;FORJ=1TON:IFI+JAND1THENPRINT" ";:GOTO3
2 PRINT"X";
3 NEXT:PRINT"":NEXT

```
> 2 votes

# Answer
# Scala, 40 and 54

The number of characters is 40 for a function, 54 for a complete program.

**The solution giving only a function body is:**

`("X "*n)sliding n take n foreach println`

Try it online

**The solution giving a complete program is:**

`val n=readInt;("X "*n)sliding n take n foreach println`

You can run it using the following command line.

`scala -e 'val n=readInt;("X "*n)sliding n take n foreach println' <<< 8`

where 8 is the input.
> 2 votes

# Answer
# brainfuck, 249 bytes

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

```

Try it online!

Could definitely be golfed more.
> 2 votes

# Answer
# C (gcc), ~~90~~ ~~88~~ ~~83~~ 82 bytes

-2 thanks to ceilingcat

And -5 more by ceilingcat. Iterate backwards for extra confusion!

Another -1 by ceilingcat. Iterate using negative integers for extra confusion!

```
m;main(n,v)int**v;{for(n*=m=~(n=atoi(v[1]));n++;)putchar(n%m?n%m-n/m&1?88:32:10);}

```

Try it online!

**Ungolfed**

```
m;

main(n, v) int**v;
{
    for (n *= m = ~(n = atoi(v[1])); n++;)
        putchar(n % m ? n % m - n / m & 1 ? 88 : 32 : 10);
}

```
> 2 votes

# Answer
## Python - 127 characters

```
from sys import*
r=stdout.write
s=int(raw_input())
[[r((x+y+1)%2 and"x"or" ")for x in range(s)]and r("\n")for y in range(s)]

```
> 1 votes

# Answer
## C - 92 86

```
i,j;main(n){for(scanf("%d",&n);i<n;puts(""),i++)for(j=0;j<n;j++)putchar("X "[i+j&1]);}

```
> 1 votes

# Answer
## Python

**48 Chars**

**EDIT:** Kinda Wrong...There's an extra space at the end...but thats not visible. If you change the space to "O" (or any nonwhitespace char) then modify `[i%2:n]` to `[i%2:n+i%2]`. for the correct version.

```
n=input()
i=0;
while i<n:print('X '*n)[i%2:n];i+=1

```
> 1 votes

# Answer
# Q, 33

```
{$[1=x mod 2;x;x-1]cut(x*x)#"X "}

```
> 1 votes

# Answer
## Ruby 58

```
i=ARGV[0].to_i
1.upto(i*i){|n|print n%i==0?"\n":' x'[n%2]}

```
> 1 votes

# Answer
# VB.net, 161

```
Module C
   Sub Main()
     Dim n As Integer
     If Integer.TryParse(Console.ReadLine,n) Then
     For x=1To n
        For y=1To n
          Console.Write("* "((x+y)Mod 2))
        Next
        Console.WriteLine()
      Next
     End If
    End Sub
End Module

```
> 1 votes

# Answer
## PHP - 136 chars (without whitespace)

Allows for x and y function input.

*Also supports odd inputs now.*

If you style the output to have 0.65 em line-height and change this ▒█ and █░ to □■ and ■□ then it comes out looking like a real (square) chessboard.

## Code:

```
function gen_cb($x,$y)
{
$c=0;
$y*=2;
for($i=0;$i<$y;$i++){
for($j=0;$j<$x;$j++){
echo $c%2==0 ? "░█" : "█░";
}
echo "<br/>";
$c++;
}
}
gen_cb(7,7);

```

## Output:

```
░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█

```
> 1 votes

# Answer
## PHP, 87

```
for($x=0;$x<$m=$argv[1];$x++){echo"\n";for($y=0;$y<$m;$y++)echo($y^($x%2))%2?' ':'X';}

```
> 1 votes

# Answer
# CJam, 18 bytes

I probably could have just ported the GolfScript answer, but here is a different approach. (And CJam is not eligible for winning anyway.)

```
l~,_f{f{+2%S'X?}N}

```

Test it here.

The idea is to iterate over the 2D grid with x and y indices on the stack, using the `f{f{...}}` trick. Given x and y, we can simply determine black and white as `(x+y)%2` and use that to pick between the character `X` and a string containing a space.
> 1 votes

# Answer
# J, 21 chars

J was missing too.

```
   ([:u:32+56*=/~@$&1 0) 5
X X X
 X X
X X X
 X X
X X X

```

Previous, 22 chars:

Char codes from mod2 pattern of `row #` \+ `column #`:

```
   ([:u:88-56*2&|@+/~@i.) 5

```
> 1 votes

# Answer
## PHP, 75 bytes

```
for(;@$i++<$k=$argv[1];){for($j=0;$j++<$k;)echo($i+$j)%2?' ':'X';echo"\n";}

```
> 1 votes

# Answer
# Japt v1.4.6 `-R`, 10 bytes

```
Æç"X " tXU

```

Try it

-3 bytes thanks to @Shaggy!

```
Æç"X " tXU   # full program
Æ            # generate a range of numbers based on input
             # and map each number through a function
 ç"X "       # inside the function, repeat "X " a bunch of times
       tXU   # select a substring from the "X " repeated string
             # The -R flag joins the array with new lines

```
> 1 votes

# Answer
# Canvas, 6 bytes

```
XX＼ｍ⤢ｍ

```

Try it here!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 61 bytes

```
x=>{for(int i=x++*x;--i>0;)Write(" X\n"[i%x<1?2:i/x+i%x&1]);}

```

Try it online!

-2 bytes thanks to @ceilingcat!
> 1 votes

# Answer
# 05AB1E, 13 bytes

```
„X ×Â‚εI∍}I∍»

```

Can definitely be golfed a bit more..

Try it online or verify some more test cases.

**Explanation:**

```
„X ×           # Repeat string "X " the (implicit) input amount of times
    Â‚         # Pair it with its reverse
      εI∍}     # Shorten both strings to a length equal to the input
          I∍   # Extend this list of strings to a length equal to the input
            »  # Join the strings by newlines (and output implicitly)

```
> 1 votes

# Answer
# PowerShell, 39 bytes

```
param($n)1..$n|%{' X'*$n|% S*g($_%2)$n}

```

Try it online!
> 1 votes

# Answer
# Unexpanded Sinclair ZX-81/Timex TS-1000/1500 and compatibles, ~96 Tokenized BASIC bytes

```
 1 LET X$="X X X X X X X X X X X "
 2 INPUT I
 3 FOR X=SGN PI TO I
 4 PRINT X$( TO I)
 5 LET X$=X$(VAL "2" TO )+X$(SGN PI)
 6 NEXT X

```

There are some limitations here; as the Sinclair ZX-81 by default only allows 32 character per line, and only 22 lines per screen by default, I have limited the maximum "chess board" to that, 22 x 22.

`I` is used here as a user input variable to determine the required "size" of the chess board. Once entered into the loop, the `X$` string is essentially shifted to the right by one character in line 5.

Enjoy typing!
> 1 votes

# Answer
# C64/128 and C64Mini (and compatibles), 68 tonekized BASIC bytes

```
 0fOi=0to11:a$=a$+"V ":nE:inputi:fOx=1toi:?leF(a$,i):a$=rI(a$,21)+leF(a$,1):nE

```

I've limited the potential size of the chess board pattern to a width of 22 because whilst the C64 might have 40 text columns, it only has 25 rows and therefore going over 22 will mean that some of the pattern is lost because when exiting a symbolic listing the C64 with typically add a carriage return, then the `ready.` prompt, and another carriage return where the cursor will reside.

To explain, here is the non-obfuscated symbolic listing:

```
 0 for i=0 to 11
 1  let a$=a$+"V "
 2 next i
 3 input i
 4 for x=1 to i
 5  print left$(a$, i)
 6  let a$=right$(a$, 21)+left$(a$, 1)
 7 next x

```

First the chess board patters is built in the `a$` variable with the shifted (or uppercase) `v` representing an X.

The user is then asked for an input of a numeric value. This will work with positive Integers with a greater value than zero, though will work also with positive floating point numbers greater or equal to one.

A `for/next` loop is set up to the Integer value of the number entered, printing out the pattern to the length of the number entered.

The `a$` variable is then shuffled one character to ensure the chess board effect in the loop.

Enjoy programming!
> 1 votes

# Answer
# K (oK), 19 bytes

**Solution:**

```
{x$(x;x+~2!x)#"X "}

```

Try it online!

**Explanation:**

Reshape the input with an odd-length so that the `X_` wraps to create the checkerboard, and then truncate to the correct width:

```
{x$(x;x+~2!x)#"X "} / the solution
{                 } / lambda taking implicit input x
              "X "  / string "X "
   ( ;      )#      / reshape to (length;width)
         2!x        / x mod 2
        ~           / not (0=>1, 1=>0)
      x+            / add to x
    x               / length is input
 x$                 / pad width to x

```
> 1 votes

# Answer
# Scala, 84 bytes

```
for(i<-1 to a;s=Seq.fill((a+1)/2)("X ").mkString)println(if(i%2==1)s else s.reverse)

```

Try it online!
> 1 votes

# Answer
# Perl 5 \+ `-n -M5.10.0`, 35 bytes

```
eval'say substr"X "x$_,$-++,$_;'x$_

```

Try it online!
> 1 votes

# Answer
# Vyxal, 10 bytes

```
‛X *½h:(…Ṙ

```

Try it Online!

A little long...
> 1 votes

# Answer
## Haskell ~~89~~ 74 charaters

```
main=do n<-readLn;mapM_(putStrLn.take n).take n.cycle$map cycle["X "," X"]

```
> 0 votes

# Answer
# PHP, 88 80 78

```
for($x=0;$x++<$i=$argv[1];){for($y=0;$y++<$i;)echo($y+$x)%2?" ":"X";echo"\n";}

```
> 0 votes

# Answer
# cQuents, 17 bytes

```
|
&"X "Tn/2,Z[1:]

```

Try it online!

## Explanation

```
|
                     Separate terms on newline
 &                   Given input n, output first n terms in sequence
                     Odd terms equal
  "X "                               "X "
      *              implicit             repeated                  times
      T                                            ceiling of
       n/2                                                    n / 2
          ,          Even terms equal
           Z                          previous term
            [1:]                                    with the first character removed (Python slice notation)

```
> 0 votes

# Answer
# Charcoal, 10 bytes

```
Ｅθ⭆θ§X ⁺ιλ

```

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

### Explanation

```
Ｅθ           Map over first input (predefined variable). Since it's a number, maps over 0 to input (excluding upper bound) instead
   ⭆θ        String map over first input
      §  ⁺ιλ  At (cyclic) index i + l (current loop variable for inner and outer loop respectively)
       X      The string "X ". Note there is a space after the "X"

```
> 0 votes

# Answer
# Oracle SQL, 84 bytes

```
SQL> select rpad(substr(rpad('_',n,'x_'),mod(level,2)+1),n,'_')from t connect by level<=n
  2  /

RPAD(SUBSTR(RPAD('_',N,'X_'),MOD(LEVEL,2)+1),N,'_')
--------------------------------------------------------------------------------
x_x_x_x_x_
_x_x_x_x_x
x_x_x_x_x_
_x_x_x_x_x
x_x_x_x_x_
_x_x_x_x_x
x_x_x_x_x_
_x_x_x_x_x
x_x_x_x_x_
_x_x_x_x_x

10 rows selected.

```
> 0 votes

# Answer
# MUMPS (~~58~~ ~~56~~ ~~88~~ ~~86~~ 88 bytes)

Assuming you can execute this code in an interpreter:

## (ANSI M)

```
  r v,! f i=1:1:v d  w !
  . f j=1:1:v w $s(i#2:$s(j#2=1:"X",1:" "),1:$s(j#2:" ",1:"X"))

```

We could bring this down to 82 bytes if we allow a new line at the beginning of the output:

```
 r v,! f i=1:1:v w ! f j=1:1:v w $s(i#2:$s(j#2=1:"X",1:" "),1:$s(j#2=1:" ",1:"X"))

```

### Bonus

We can take advantage of the fact that M doesn't have any reserved keywords to give further headache:

```
s s=8 f f=1:1:s w ! f w=1:1:s w $s(f#2:$s(w#2=1:"X",1:" "),1:$s(w#2=1:" ",1:"X"))

```

## Caché ObjectScript (a superset of ANSI M) (83 bytes):

```
r v,! f i=1:1:v{f j=1:1:v{w $s(i#2:$s(j#2=1:"X",1:" "),1:$s(j#2=1:" ",1:"X"))} w !}

```

Explanation:

both cases are essentially the same. Accept input "v" from user. While looping from 1 to v, execute an inner loop such that if i#2 isn't zero, write "X" if j#2 isn't zero and " " in all other cases (i.e. when j#2 is zero). if i#2 is zero, do the opposite. After completing the inner loop, start a new line.

*dang, realized I forgot to alternate lines* \*added another version of ANSI M and an ObjectScript version
> 0 votes

# Answer
# Stax, 6 bytes

```
òeφ→α♪

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
cK      map over the cartesian square of [1..n] * [1..n]
        implicitly output from each row on separate lines
  +     add the coordinates
  .X @  index into string "X "

```

Run this one
> 0 votes

# Answer
# Jelly, 17 bytes

```
⁾X ẋs2UÐeẋ³ŒHḢƊ€Y

```

Try it online!

This almost certainly can be golfed further; 17 bytes seems like too many.

**Explanation:**

```
⁾X ẋs2UÐeẋ³ŒHḢƊ€Y    Example input: 3
⁾X ẋ                 Repeat the string "X " times the input: "X X X "
    s2               Split it into chunks of length 2: ["X ", "X ", "X "]
      UÐe            Upend (reverse) the even indexes: ["X ", " X", "X "]
              Ɗ€     Apply to each...
         ẋ³          ...repeat each chunk times the input...:  ["X X X ", " X X X", "X X X "]
           ŒH        ...approximately split it into halves...: [["X X", " X "], [" X ", "X X"], ["X X", " X "]]
             Ḣ       ...take the head (first item) of each: ["X X", " X ", "X X"]
              Y      Join with newlines
                     Implicit output

```
> 0 votes

# Answer
# Pip, 25 bytes

```
Y"X "XaFi,aP(i%2?RVyy)@<a

```

A simple for loop.

Try it online!
> 0 votes

# Answer
# Jelly, 7 bytes

```
+þị⁾ XY

```

Try it online! or see the results for \\$n = 1, 2, ..., 8\\$

## How it works

```
+þị⁾ XY - Main link. Takes n on the left from the command line
 þ      - Yield an n×n matrix where each cell (i,j) is, for 0 ≤ i, j ≤ n:
+       -   i + j
   ⁾ X  - Yield " X"
  ị     - Index modularly into " X". Even numbers are replaced with "X" and odd with " "
      Y - Join by newlines and output

```
> 0 votes

# Answer
# Ly, ~~60~~ 51 bytes

```
ns1[p'Xf' f,,0G]ppl2%>l[<&s[pp0]p(10)&o&lr0Irpr>,]>

```

Try it online!

I thought this would be shorter, but guess I had higher expectations for the approach than was warranted. :)

The high level idea here is to build a `X X X ...` string on a stack, then iterate as many times as requested. Each time time through the loop, the code prints the stack then reverses it.

ns1[p'Xf' f,,0G]ppl2%>l[<&s[pp0]p(10)&o&lr0Irpr>,]>

>> First loop, constructs the "X X X ..." pattern on a stack <<
ns1[p'Xf' f,,0G]
ns1                             # Read board size (N), save and push 1 on stack
   [p      ,,0G]                # Loop, decrement N by 2 each time
     'Xf' f                     # Push "X", pull N forward, push " ", pull N

>> Clean-up and prep for second loop <<
>>              ppl2%>
.. pp                           # Delete N and iterator from stack
..   l2%                        # Load N, push "N%2" on stack (N even/odd bool)
        >                       # Switch to "X X ..." stack

>> Second loop, print the pattern and update <<
>> >>                 l[<&s[pp0]p(10)&o&lr0Irpr>,]
.. l[<              >,]         # Loop, decrements N on stack each time
      &s                        # Save "X X ..." stack in the backup cell
        [p 0]p                  # If-then, true if top of stack is not 0
          p                     # Delete one char (means N is even)
              (10)&o            # Push a LF, print the whole stack
                    &l          # Load the "X X ..." stack from the backup cell
                      r         # Reverse the stack
                       0I       # Push copy of entry 0 (even/odd bool)
                         rpr    # Reverse, pop, reverse (pop entry 0)

>> Final clean-up <<
>> >> >>                                          >
.. >                # Switch stacks to avoid auto print
```

> 0 votes

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


title: Draw me a domino

text:
# Question
Title: Draw me a domino
## Challenge

Given two digits 0-9 as input, output a domino (from the double-nine domino set) with these number of pips (dots) on the two faces. The ten possible faces look like this (separated by pipes):

```
     |     |    o|    o|o   o|o   o|o o o|o o o|o o o|o o o
     |  o  |     |  o  |     |  o  |     |  o  |o   o|o o o
     |     |o    |o    |o   o|o   o|o o o|o o o|o o o|o o o

```

Or on separate lines:

```

-----

  o

-----
    o

o
-----
    o
  o
o
-----
o   o

o   o
-----
o   o
  o
o   o
-----
o o o

o o o
-----
o o o
  o
o o o
-----
o o o
o   o
o o o
-----
o o o
o o o
o o o

```

## Input formats

You may take input in any reasonable format, including but not limited to:

* Two separate integers, strings, or singleton arrays;
* A single integer from 0-99;
* An array of two integers;
* A string of two digits.

## Output formats

* The two faces may be horizontally aligned, separated by pipes like so:

```
    o|o   o
     |  o
o    |o   o

```
* Or they may be vertically aligned, separated by hyphens like so:

```
    o

o
-----
o   o
  o
o   o

```
* You may output a border around the domino if you wish.
* You may also choose to output a list of lines, a list of the two faces, or a combination of these.
* You may use any non-whitespace character for the pips (I used `o`).
* If you really wish, you can use `0` for whitespace and `1` for the pips, or `False`/`True` (or your language's equivalent) if outputting an array.
* You may remove the whitespace between columns; this is a valid output for 7, 7:

```
ooo|ooo
 o | o
ooo|ooo
```
* Any of the faces may be rotated by 90 degrees. This is also a valid output for 7, 7:

```
o   o|o o o
o o o|  o
o   o|o o o
```
* You may have as much/little leading/trailing whitespace as you like, as long as the main part of the output still fits the other constraints.
* Each face must be 3 lines tall, even if the lines are empty. For 0, 1 you could not output this:

```
-----

  o

```

But you *could* output this:

```

-----

  o

```

Similarly, if you were outputting a list of two lists of lines, you could do `[["", "", ""], ["", " o", ""]]`, but not `[[""], [" o "]]`.

## Scoring

This is , so **the shortest code in bytes in each language wins.**

# Answer
# Python 2, ~~101~~ ~~97~~ ~~92~~ ~~68~~ 64 bytes

```
lambda*a:[[[n>3,n>5,n>1],[n>7,n%2,n>7],[n>1,n>5,n>3]]for n in a]

```

Try it online!

# Credits
> 16 votes

# Answer
# C (gcc), ~~252~~ ~~242~~ ~~269~~ ~~262~~ ~~241~~ ~~235~~ 220 bytes

I was on stack overflow for sockets in python, when this popped up, said why not? first code golf, so i'm not entirely sure if I followed the rules 100% (and if not and someone wants to steal my proverbial cookie and fix it, so be it). With 'o' and ' ', ~~255 245 272 265 244 238~~ 228 bytes. replace +48 with \*79+32.

```
#define Q(P,R)(R>>P&1)+48
char a[11];i=0;f(char*c){char b=c[0];a[3]=a[7]='\n';a[5]=Q(0,b);a[1]=a[9]=Q(3,b);a[2]=a[8]=Q(2,b)|a[1];a[0]=a[10]=Q(1,b)|a[2];a[4]=a[6]=a[1]|Q(2,b)&Q(1,b);puts(a);if(i++<1){puts("---");f(c+1);}}

```

Try it online!

How it works:
I use a bit shift and bitwise and to find if a spot should be clear or a pip, then offset the 0 or 1 to the correct ASCII value. it messes up on 4 and 5, so they needed some fixing. actually added a few bytes. was able to remove several bytes by removing a mask and just using 1 (doh)

Special thanks to Mr. Xcoder for the 7 less bytes by removing an excess #define
Changes: removed memset -21 bytes. redid the bit logic for 6, 4, 2 to depend on 8|4&2, 8|4, 8|4|2, respectively. -6 bytes. removed extra newlines by using puts instead of printf, which is also shorter. shortened the array to 11, removing extra assignment. -15 bytes. NOW I think that's the best I can do.
> 13 votes

# Answer
# Jelly, 20 bytes

```
“¤o.ƤẸʠṚ’B¬s5ŒBị@s€3

```

Try it online!

### Alternate version, original output, ~~33~~ ~~32~~ 31 bytes

```
“¤o.ƤẸʠṚ’ṃ⁾ os5ŒBị@s€3K€€Zj€”|Y

```

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

Try it online!

### How it works

First, `“¤o.ƤẸʠṚ’` – an integer literal in bijective base 250 – sets the return value to **1086123479729183**.

Then,  converts the return value to binary and takes the logical NOT of each digit, yielding the array

```
00001001000010110100101011110011101111101111100000

```

Next, `s5ŒB` splits that array into chunks of length **5**, then *bounces* each chunk, turning **abcde** into **abcdedcba**, yielding

```
000010000 001000100 001010100 101000101 101010101

111000111 111010111 111101111 111111111 000000000

```

Now, `ị@` retrieves the **j**th and **k**th item of this array, where **j, k** is the program's first argument. Note that indexing is 1-based and modular, so the zeroth element is also the tenth.

Finally, `s€3` splits each chunk of length nine into three chunks of length three.
> 10 votes

# Answer
# Jelly, 13 bytes

```
⁽½ÑD<;ḂŒBs3µ€

```

Try it online!

Combining Dennis' idea of using `ŒB` (bounce) in this answer and Xcali's observation in this answer to get 13 bytes.

---

# Jelly, 28 bytes

(with pretty printing)

Only now do I know that Jelly string literal is automatically terminated...

```
⁽½ÑD<;ḂŒBị⁾o Ks6Yµ€j“¶-----¶

```

Try it online!
> 9 votes

# Answer
# Perl 5, ~~107 76 70~~ 67 ~~\+ 1 (`-a`)~~ = 67 bytes

```
$,="
---
";say map{'351
7 7
153'=~s/\d/$_>$&||0/ger=~s/ /$_%2/er}<>

```

Try it online!

Uses 0 for whitespace and 1 for pips. Pretty simple method: observe that as the digit goes up, once a pip is "on", it never goes "off," except for the one in the middle. In the middle position, it is on for all odd numbers. Thus, for each position, it's a simple matter of checking if the digit is greater than the last digit for which it is off. The `||0` creates output when the condition is false. In Perl, false is `undef` which outputs as null.
> 9 votes

# Answer
# PHP ~~155~~, 150 bytes

```
function d($a){foreach($a as$n){$o="---";for($i=0;$x=2**$i,$i<9;++$i)$o.=([0,16,68,84,325,341,365,381,495,511])[$n]&$x?0:' ';echo chunk_split($o,3);}}

```

It takes an array of integers as the input. For testing:

```
d([1,2]);

echo "=========\n";

d([0,1,2,3,4,5,6,7,8,9]);

```

Output Format:

```
---

 0

---
  0

0

```

Check it out live here

**My Solution**

For my solution I used a matrix consisting of bitwise numbers ( powers of 2 ). It can be visualized like this:

```
 1  |  2  |  4
 8  | 16  | 32
 64 | 128 | 256

```

And then a storage array consisting of the bit positions for the pips of each domino correlated by the numbered index:

```
[0,16,68,84,325,341,365,381,495,511]

```

So just to clarify:

* example 0: index `0` or value `0` would be the blank domino, which is always false.
* example 1: index `1` or value `16` would be the number one domino and in the matrix that is in the center `16`.
* example 2: index `2` or value `68` would be the number two domino and in the matrix that is top right `4` and bottom left `64` or `4|64`
* example 3: index `5` or value `341` would be the number five domino and in the matrix that is `1|4|16|64|256`
* example 4: index `9` or value `511` would be the number nine domino and in the matrix its the combination of all the bits.

Once that is established it's a fairly simple matter of looping for the 9 positions in the matrix, and setting `$x` to `2` to the power of `$i`

```
for($i=0;$x=2**$i,$i<9;++$i)

```

Then we do a bitwise And `&` as we iterate through those spots. So for examples sake will use example 2 from above and I will use `x`'s instead spaces for sake of visual clarity:

* iteration 1, `68 & 1 ? 0 : 'x'` which results in `'x'`
* iteration 2, `68 & 2 ? 0 : 'x'` which results in `'x'`
* iteration 3, `68 & 4 ? 0 : 'x'` which results in `0`
* iteration 4, `68 & 8 ? 0 : 'x'` which results in `'x'`
* iteration 5, `68 & 16 ? 0 : 'x'` which results in `'x'`
* iteration 6, `68 & 32 ? 0 : 'x'` which results in `'x'`
* iteration 7, `68 & 64 ? 0 : 'x'` which results in `0`
* iteration 8, `68 & 128 ? 0 : 'x'` which results in `'x'`
* iteration 9, `68 & 256 ? 0 : 'x'` which results in `'x'`

When the loop is complete we wind up with this string `"xx0xxx0xx"`.

Then we add the border `"---xx0xxx0xx"` to it *( I actually start with the border, but whatever)*.

And finally we chunk\_split() it on 3's for:

```
---
xx0
xxx
0xx

```

Feel free to let me know what you think.
> 6 votes

# Answer
# JavaScript (ES6), ~~79~~ 78 bytes

*Saved 1 byte thanks to @ETHproductions*

Takes input in currying syntax `(a)(b)` and outputs a vertical ASCII domino.

```
a=>b=>(g=n=>`351
707
153`.replace(/./g,d=>' o'[(+d?n>d:n)&1]))(a)+`
---
`+g(b)

```

### Demo

```
let f =

a=>b=>(g=n=>`351
707
153`.replace(/./g,d=>' o'[(+d?n>d:n)&1]))(a)+`
---
`+g(b)

console.log(f(4)(2))
console.log(f(3)(7))
```

---

# Horizontal version, ~~80~~ 79 bytes

*Saved 1 byte thanks to @ETHproductions*

Takes input as an array of 2 integers and outputs a horizontal ASCII domino.

```
a=>`240|351
686|797
042|153`.replace(/\d/g,d=>' o'[(d<8?(x=a[d&1])>(d|1):x)&1])

```

### Demo

```
let f =

a=>`240|351
686|797
042|153`.replace(/\d/g,d=>' o'[(d<8?(x=a[d&1])>(d|1):x)&1])

console.log(f([4,2]))
console.log(f([3,7]))
```
> 6 votes

# Answer
# APL (Dyalog), 25 bytes

```
2∘|(3 3⍴⊢,,∘⌽)¨>∘3 5 1 7¨

```

Try it online!

-2 thanks to ngn.

The output format is a little bit weird: this function returns an array containing two shape-3,3 arrays each containing 0s and 1s.
> 4 votes

# Answer
# C (gcc), ~~115~~ 113 bytes

-2 bytes thanks to ceilingcat

```
i;g(x){for(i=0;9/++i;)printf("%c%c",32+(i^5?x>" CEAG@GAEC"[i]%8:x%2),i%3?32:10);}f(a,b){g(a),puts("-----"),g(b);}

```

Try it online!
> 4 votes

# Answer
# Javascript (ES6), 87 bytes

```
a=>b=>[(s=n=>[[n>3,n>5,n>1],[n>7,n%2,n>7],[n>1,n>5,n>3]].map(c=>c.map(b=>+b)))(a),s(b)]

```

```
f=a=>b=>[(s=n=>[[n>3,n>5,n>1],[n>7,n%2,n>7],[n>1,n>5,n>3]].map(c=>c.map(b=>+b)))(a),s(b)]
```

```
<div oninput="o.innerText=JSON.stringify(f(a.value)(b.value))"><input id=a type=number min=1 max=9 value=1><input id=b type=number min=1 max=9 value=1><pre id=o>
```
> 2 votes

# Answer
# Haskell - 88 characters

```
map$zipWith(zipWith($))[[(>4),(>5),(>1)],[(>7),odd,(>7)],[(>1),(>5),(>3)]].repeat.repeat

```

Takes a list of two numbers indicating the faces, returns a list of list of list of bool. Not that short but I find the solution interesting.
> 2 votes

# Answer
# Pip, ~~32~~ ~~27~~ ~~24~~ 21 bytes

-3 bytes thanks to @DLosc

```
FcgP[Yc>_M3517c%2RVy]

```

Try it online!

### Explanation:

```
F                      For each
 c                       character $c
  g                      in the list of inputs:
   P                     Print
    [               ]      an array consisting of
                             an array of bits representing whether
      c>                       $c is greater than
        _M                       each of
          3517                     3, 5, 1, and 7
     Y                       (call this bit array $y),
              c%2            $c mod 2,
                 RV          and the reverse
                   y           of $y.

```
> 2 votes

# Answer
# Jelly, 16 bytes

```
>⁽¤xb8¤;ḂŒḄs3
Ç€

```

Try it online!

Used Neil's strategy and base decompression to generate the values; outputs as a binary array. Takes a list as input.

Explanation:

```
Ç€
 € for €ach input,
Ç  execute the previous line.

>⁽¤xb8¤;ḂŒḄs3
 ⁽¤xb8¤       the array [3, 5, 1, 7]
>             1 if the input is greater than each element, 0 otherwise
       ;Ḃ     append input % 2
         ŒḄ   bounce array
           s3 split into chunks of 3

```
> 2 votes

# Answer
# Charcoal, ~~46~~ ~~44~~ ~~43~~ 39 bytes

```
ＥＥ²℅§@APQTUVW^_ＮＥ⪪Ｅ⁹§ o÷ιＸ²↔⁻⁴λ³⪫λ Ｍ⁵↑⁵

```

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

```
ＥＥ²℅§@APQTUVW^_Ｎ

```

Read two integers and map them in the lookup table. Then map over the result. (This effectively captures the result in a temporary.)

```
  Ｅ⁹                Loop `l` (!) from 0 to 8
            ⁻⁴λ     Subtract from 4
           ↔        Absolute value
         Ｘ²         Power of 2
       ÷ι           Divide into the looked-up value `i`
    § o             Convert to space or o
 ⪪             ³    Split into (3) groups of 3
Ｅ                   Map over each group
                ⪫λ  Join the 3 characters with spaces

```

The results are then implicitly printed on separate lines, with an extra blank line between each face because the results are nested.

```
Ｍ⁵↑⁵

```

Move up and draw the dividing line in between the faces.

Previous 43-byte horizontal version:

```
↶Ｐ³Ｍ⁷←ＦＥ²℅§@APQTUVW^_ＮＦ⁹«Ｆ¬﹪κ³⸿⸿§ o÷ιＸ²↔⁻⁴κ

```

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

Work vertically.

```
Ｐ³

```

Print the dividing line.

```
Ｍ⁷←

```

Position to the start of the first face.

```
ＦＥ²℅§@APQTUVW^_Ｎ

```

Read two integers and map them in the lookup table.

```
Ｆ⁹«

```

Prepare to output up to 9 `o`s.

```
Ｆ¬﹪κ³⸿⸿

```

But start a new column every three `o`s.

```
§ o÷ιＸ²↔⁻⁴κ

```

Convert the lower 5 bits of the ASCII code to binary, and then mirror the output for the remaining 4 `o`s.
> 1 votes

# Answer
# C (gcc), ~~150~~ ~~146~~ 145 bytes

```
#define p(x)printf(" %c",33-(x)),
P(a){p(a<4)p(a<6)p(a<2)p(23)p(a<8)p(~a&1)p(a<8)p(23)p(a<2)p(a<6)p(a<4)p(23)0;}f(a,b){P(a),puts(" -----"),P(b);}

```

Try it online!
> 1 votes

# Answer
# \>\<\>, 57+3 = 60 bytes

```
>{:3)$:5)$:1)$:7)$:2%$\ao \
\?%cl999)3$)5:$)1:$)7:/nnn<rp

```

Try It Online. Outputs as a vertical domino with 1s for dots, 0s for whitespace and 9s for separators like so:

```
001
000
100
999
111
111
111

```

Technically this can be extended to up to 12 inputted values.

## Old Version:

## \>\<\>, 76+3 = 79 bytes

```
>{:3)$:5)$:1)$a$:7)$:2%$:7)\&?o~?!n\
\?(*a3la"---"a)3$)5:$)1:$a$/$&:)9::<r~p

```

Try It Online. Outputs as a vertical domino with 1s for dots and 0s for whitespace like so:

```
001
000
100
---
111
111
111

```
> 1 votes

# Answer
# Chip, ~~142~~ 135 bytes

```
! CvDvB
>v-]-x.
|Z-]-]e
|Z]xe|
|ZR(-'
|Zx.AD
|Zxx]x.
|Zx^-]e
|Z<,(-.
|Zx]xe|
|Zx-]-]e
|Zx-]-x'
|Z<C^D^B
|>x~s
|Zx.
|Zx<
|Zxb
|Z+^~f
`zd

```

Try it online!

Input is a string of digits. Uses zeroes as the pips. Draws the pips for one number, reads next input byte. If no next byte, terminate, else draw the divider and go to start.

Each `Z` (or `z`) corresponds to one character of output, they are positioned to fire in order top to bottom. The capitalized `A`, `B`, `C`, and `D` correspond to the low four bits of the input (that's all we look at, so `"34" == "CD" == "st" ...`). The lowercase `b`, `d`, `e`, `f` correspond to various bits of the output.

Can make infinite-length dominoes too; try giving `0123456789` as input.
> 1 votes

# Answer
## Javascript (ES5), 103 characters

```
(a,b,h=(y=7)=>
  ' o   o ooo'.slice(+y,+y+3))=>
    ['223355','242424245','221155'].map(z=>
      h(z[a])+'|'+h(z[b]))

```

Linebreaks and whitespace inserted for readability.
> 1 votes

# Answer
# APL+WIN,  ~~49~~  47 bytes

```
4⌽'|',⌽⍉6 3⍴,⍉(9⍴2)⊤(+\∊0 241 52 24 114,¨16)[⎕]

```

Edited as per Adam's comment, thanks, to run with index origin zero.

Prompts for screen input as a vector of integers one for each face.

The output is of the form:

```
1 1 1 | 0 0 1    0 0 0 | 1 0 1
0 1 0 | 0 1 0    0 0 0 | 0 1 0
1 1 1 | 1 0 0    0 0 0 | 1 0 1

```

for an inputs of `7 3` and `0 5`

Explanation:

```
(+\∊0 241 52 24 114,¨16) create a vector of integers whose binaries
                         represent the dots on the domino faces

[1+⎕] take input integers as indices to select from above vector

⍉6 3⍴,⍉(9⍴2)⊤ convert selected integers to a 9x2 binary matrix and reshape
              to match the orientation of the domino faces

4⌽'|',⌽ rotate, concatenate centre line markers and rotate again to centre

```
> 0 votes

# Answer
# Python 2, 121 bytes

```
lambda x,y,d="001155777702020202570044557777":[("%03d"%int(bin(int(o))[2:]),"---")[o=="3"]for o in d[x::10]+"3"+d[y::10]]

```

Try it online!

Reduced to 121 using a lambda after going back and re-reading the rules. Now outputs a list of lines.

Previous version with nicely formatted output:

# Python 2, ~~156~~ ~~153~~ ~~147~~ 141 bytes

```
x,y=input()
d="001155777702020202570044557777"
a=["%03d"%int(bin(int(o))[2:])for o in d[x::10]+d[y::10]]
for x in a[:3]+["---"]+a[3:]:print x

```

Try it online!

-3 with thanks to @NieDzejkob

Takes input as 2 integers and outputs in vertical format with 0=space and 1=dot.
> 0 votes

# Answer
# Pyt, ~~220~~ 154 bytes

Second attempt (154 bytes)

```
46281ᴇ8264áĐ9ř3%¬Đ¬2⁵*⇹1ᴇ*+03Ș←Đ3Ș≥Đ6²⁺3**⇹¬2⁵*+⇹9ř5=⇹2%*9²2-*+⇹9ř9<*Ž⇹ŕ⇹9ř3%¬Đ¬2⁵*⇹1ᴇ*+03Ș←Đ3Ș≥Đ6²⁺3**⇹¬2⁵*+⇹9ř5=⇹2%*9²2-*+⇹9ř9<*Ž⇹ŕ5⑴9△*Ƈǰ⇹Ƈǰ64ȘƇǰ6↔ŕ↔ŕ↔

```

Explanation:

```
46281ᴇ8264áĐ                                    Pattern matching for every cell but the middle
9ř3%¬Đ¬2⁵*⇹1ᴇ*+03Ș                              Non-pip characters
←Đ3Ș≥Đ6²⁺3**⇹¬2⁵*+⇹9ř5=⇹2%*9²2-*+⇹9ř9<*Ž⇹ŕ⇹     Make top cell
9ř3%¬Đ¬2⁵*⇹1ᴇ*+03Ș                              Non-pip characters
←Đ3Ș≥Đ6²⁺3**⇹¬2⁵*+⇹9ř5=⇹2%*9²2-*+⇹9ř9<*Ž⇹ŕ      Make bottom cell
5⑴9△*Ƈǰ⇹Ƈǰ64ȘƇǰ6↔ŕ↔ŕ↔                          Make boundary and combine

```

---

First attempt (220 bytes):

```
2`↔←Đ4≥Đ6²⁺3**⇹¬5«+2⁵⇹3ȘĐ6≥Đ6²⁺3**⇹¬5«+2⁵⇹3ȘĐ2≥Đ6²⁺3**⇹¬5«+1ᴇ⇹3ȘĐ8≥Đ6²⁺3**⇹¬5«+2⁵⇹3ȘĐ2%Đ6²⁺3**⇹¬5«+2⁵⇹3ȘĐ8≥Đ6²⁺3**⇹¬5«+1ᴇ⇹3ȘĐ2≥Đ6²⁺3**⇹¬5«+2⁵⇹3ȘĐ6≥Đ6²⁺3**⇹¬5«+2⁵⇹3Ș4≥Đ6²⁺3**⇹¬5«+1ᴇ9△ĐĐĐĐ1ᴇ↔⁻łŕ↔ŕŕŕŕŕŕáƇǰ

```

Explanation:

```
2                           Push 2 (this is how many 'cells' to make)
`     ... ł                 While the top of the stack is not zero, loop
↔                           Flip the stack (useless at the beginning, undoes the flip at the end of the loop)
←Đ4≥Đ6²⁺3**⇹¬5«+            Set top-left pip
2⁵⇹3Ș                       Space
Đ6≥Đ6²⁺3**⇹¬5«+             Set top-middle pip
2⁵⇹3Ș                       Space
Đ2≥Đ6²⁺3**⇹¬5«+             Set top-right pip
1ᴇ⇹3Ș                       New line
Đ8≥Đ6²⁺3**⇹¬5«+             Set middle-left pip
2⁵⇹3Ș                       Space
Đ2%Đ6²⁺3**⇹¬5«+             Set center pip
2⁵⇹3Ș                       Space
Đ8≥Đ6²⁺3**⇹¬5«+             Set middle-right pip
1ᴇ⇹3Ș                       New line
Đ2≥Đ6²⁺3**⇹¬5«+             Set bottom-left pip
2⁵⇹3Ș                       Space
Đ6≥Đ6²⁺3**⇹¬5«+             Set bottom-middle pip
2⁵⇹3Ș                       Space
4≥Đ6²⁺3**⇹¬5«+              Set bottom-right pip
1ᴇ                          New line
9△ĐĐĐĐ                      Add 5 dashes
1ᴇ                          New line
↔⁻ł                         Decrement counter (if >0, loop; otherwise, exit loop)
ŕ↔ŕŕŕŕŕŕ                    Remove all unnecessary items on the stack
áƇǰ                         Push stack to an array, get characters at unicode codepoints given by values in the array, join characters with empty string

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 34 bytes

```
•ΩõIº•R2ô¹2÷è¹È-bDg5s-ú.∞3ô»TR„ o‡

```

Try it online!

---

This was difficult because 05AB1E has bad padding.

---

Basic explanation:

* There are 4 significant patterns here which are 2, 4, 6 and 8.
* 3,5,7 and 9 are the other patterns plus 1.
* 1 is not significant due to symmetry, if the input is even, subtract 1 to toggle the middle bit.
* Toggling the LSB allows the middle bit to be flipped due to mirroring.
> 0 votes

# Answer
# SmileBASIC, ~~92~~ 69 bytes

```
INPUT N,M
DEF Q?N>3;N>5;N>1?N>7;1AND N;N>7?N>1;N>5;N>3
END
Q?777N=M
Q

```

Example:

```
? 7,2
111
010
111
777
001
000
100

```

This is what happens when your rules aren't strict enough.
> 0 votes

# Answer
# FALSE, ~~116~~ ~~80~~ ~~78~~ ~~70~~ ~~69~~ ~~66~~ ~~63~~ ~~61~~ ~~59~~ 58 bytes

```
[$3[>_$.\$]$p:!5p;!1p;!"
"7p;!%1&.."
"..."
"]$s:!"---
"s;!

```

still working on this...
> 0 votes

# Answer
# PHP, 116 bytes

```
while($i<6)echo strtr(sprintf("%03b",[_011557777,_202020267,_044557777][$i/2][$argv[$i%2+1]]),10,"o "),"|
"[$i++%2];

```

requires PHP 5.5 or later. Run with `-nr` or try it online.
> 0 votes

# Answer
# Vyxal `j`, 41 bytes

```
»⟑-⁰ɖṄwi⁋ǏSżƛ»b9ẇ:£?i¥?i3(2p)Jƛ`o -`$i;3ẇ

```

Try it Online!

A mess.
> 0 votes

---
Tags: code-golf, game, dominoes
---


title: Graph Florets of a Flower

text:
# Question
Title: Graph Florets of a Flower
Take a look at this chamomile flower:

Pretty, isn't it? Well, what if I told you that this wasn't actually one flower?

A lot of flowers (including sunflowers, chamomiles, daisies and others) actually consist of many very small flowers (the black dots on sunflowers) on a flower head. These miniature flowers are called *florets*, and they are arranged in a very special way.

Basically, the nth floret's position on a flower head is (in polar coordinates):

where c = 1 (Note that 137.508 degrees = golden angle. You don't have to use this exact precision.)

This causes the florets to be formed in a spiral called Fermat's Spiral. The positioning of the florets also is connected with Fibonnaci numbers, but that's a tale for another time.

So, here's the challenge. Given an integer n as input, calculate the positions of the first n florets and **plot them**. This is , so I do actually want you to display the points in either a window of some sort or outputted as data in some common image format to STDOUT or a file. Other than that, this challenge should be fairly straightforward. It's , so shortest code wins. GLHF!

Here is a sample picture of what an output might look like:

# Answer
> 21 votes
# TI-BASIC, 34 bytes

For the TI-83+/84+ series of calculators.

```
Input N
2πe^(-2sinh⁻¹(.5→θstep
AnsN→θmax
"√(θ→r₁
Polar                      ;Displays polar mode graphs to graph screen
Dot                        ;Prevents lines from connecting points
DispGraph                  ;Displays graph screen

```

This considers the dot at the origin to be the 0th dot.

Thanks to the one-byte `sinh⁻¹(` token, `2πe^(-2sinh⁻¹(.5` is a short way of getting the golden angle in radians. This is derived from the fact that `e^(sinh⁻¹(.5` is the golden ratio.

Here are screenshots for N=50.

(Yes, that's a 96x64 monochrome display on a TI-84+. The newer color calculators have a resolution upgrade, but still have only 3.7% the pixels of an iPhone.)

Press `TRACE` to step through each point.

# Answer
> 16 votes
# Python 2, ~~85~~ ~~82~~ 81 bytes

```
from pylab import*
for i in arange(0,input(),2.39996):polar(i,sqrt(i),'o')
show()

```

Shortened by one byte by marinus.

Using the golden angle in radians. Byte length is the same if I used 137.508 instead, but somehow doesn't look as good. Generates a polar plot using pylab. Below is when 300 (for the older version) is the input and 7000 (for the newer version) is the input. Could round the angle up to 2.4 to lower the number of bytes to 77.

Here's a longer version that produces a cleaner look by removing the grid and axis:

```
from pylab import *
def florets(n):
    for i in arange(0, n, 2.39996):polar(i, sqrt(i), 'o')
    grid(0)#turn off grid
    xticks([])#turn off angle axis
    yticks([])#turn off radius axis
    show()

```

The reason for the different colors is because each point is plotted separately and treated as its own set of data. If the angles and radii were passed as lists, then they would be treated as one set and be of one color.

# Answer
> 14 votes
## Blitz 2D/3D, 102 bytes

(The very FIRST EVER Blitz 2D/3D answer on this site!)

```
Graphics 180,180
Origin 90,90
n=Input()
For i=1To n
t#=i*137.508
r#=Sqr(t)
Plot r*Cos(t),r*Sin(t)
Next

```

An input of `50` fills the window. (Yes, I could shave off two bytes by doing `Graphics 99,99`, but that's not nearly so visually interesting or useful.)

Prettier version (and exits more nicely):

```
Graphics 400,400
Origin 200,200

n=Input("How many florets? ")

For i = 1 To n
    t# = i * 137.508
    r# = Sqr(t)

    Oval r*Cos(t)-3,r*Sin(t)-3,7,7,1
Next

WaitKey
End

```

# Answer
> 12 votes
# Mathematica, ~~43~~ 42 bytes

```
ListPolarPlot@Array[(2.39996#)^{1,.5}&,#]&

```

This is an unnamed function taking an integer argument, e.g.

The screenshot uses an older version, but the output looks the same.

Mathematica actually has a built-in `GoldenAngle` for even more accurate results, but that's longer than `2.39996`.

# Answer
> 11 votes
# MATLAB, 42 bytes

```
t=2.39996*(1:input(''));polar(t,t.^.5,'.')

```

Gets the input number, creates a range from 1 to that number.

Multiplies the range by the golden angle in radians (the value used is closer to the true value than 137.508 degrees to 6 s.f.).

Then simply plots **theta** vs. **r** on a polar coordinates chart using dots. Here shown with 2000 points

A slightly prettier looking graph (no grid lines) would be this code:

```
t=2.39996*(1:input(''));[x,y]=pol2cart(t,t.^.5);plot(x,y,'.');axis equal

```

Though that is at the expense of 31 bytes. Again here is it shown with 2000 points

# Answer
> 8 votes
# R, ~~58~~ ~~55~~ 54 bytes

```
x=2.39996*1:scan();plotrix::radial.plot(x^.5,x,rp="s")

```

This requires the `plotrix` package to be installed, but the package doesn't have to be imported because we're referencing the namespace explicitly.

Ungolfed:

```
# Read a number of STDIN
n <- scan()

x <- 2.39996*(1:n)

# The rp.type = "s" option specifies that we want to plot points rather
# than lines (the default)
plotrix::radial.plot(lengths = sqrt(x), radial.pos = x, rp.type = "s")

```

Example output for *n* = 1500:

Saved 3 bytes thanks to plannapus!

# Answer
> 8 votes
# R, ~~55~~ 54 bytes

```
t=1:scan()*2.39996;r=t^.5;plot(r*cos(t),r*sin(t),as=1)

```

Here is the result for n=1000:

Edit: Saved 1 byte using partial matching of arguments (`as` instead of `asp`) thanks to @AlexA.!

# Answer
> 6 votes
# R, ~~48~~ 47 bytes

I think this is sufficiently different from the other R solutions so far. This one uses complex vectors to construct the coordinates. the sqrt of t and t are put into the modulus and argument parameters and the x, y are taking from the real and imaginary. Thanks to @AlexA. for the byte.

```
plot(complex(,,,t^.5,t<-1:scan()*2.39996),as=1)

```

# Answer
> 3 votes
# Html+JavaScript 179

```
<canvas id=C></canvas><script>n=1500,C.width=C.height=400,T=C.getContext('2d');for(n=prompt(M=Math);n--;)r=M.sqrt(t=n*2.4)*9,T.fillRect(M.cos(t)*r+200,M.sin(t)*r+200,2,2)</script>
```

# Answer
> 2 votes
# Jolf, 25 bytes

```
yG@@KyoΜzXDyOUH*Hm°yT'.}

```

(output for n = 5000)

Try it online. (note that the resulting spiral is small)

Non-competing since Jolf was created after this challenge. This is 25 bytes when encoded with ISO-8859-7, and it contains one unprintable (here's a hexdump):

```
0000000: 7947 4096 404b 796f cc7a 5844 794f 5548  yG@.@Kyo.zXDyOUH
0000010: 2a48 6db0 7954 272e 7d                   *Hm.yT'.}

```

## Explanation

```
yG@@KyoΜzXDyOUH*Hm°yT'.}
yG@@K                      goto (150,75) (center of the canvas)
     yo                    set current location as the origin
       MzX                 map over range 1...input
          D                start of function
           yO              goto polar coordinates ....
             UH            radius: square root of argument
               *Hm°        angle: argument times golden angle
                   yT'.    draw a dot there
                       }

```

# Answer
> 2 votes
# K (oK) + `iKe`, 37 bytes

```
{(80+(%t)*(cos;sin)@\:t:x*2.4;;1)}'!:

```

Try it online!

a function which takes n on the right. Uses the approximate 2.4 radian measure.

-8 bytes from JohnE.

## Explanation

```
{draw::{(80+(%t)*(cos;sin)@\:t:x*2.4;;1)}'!x}
 draw::                                       globally set draw to:
       {                                }     the following function
                                         '!x  run on range 0..input-1
        (                              )      create an array:
                             t:x*2.4          multiply right arg by 2.4, set to t
                 (cos;sin)@\:                 apply cos and sin on each
            (%t)*                             multiply by sqrt(t)
         80+                                  add 80 (for compatibility with any size, change to ((w;h)%2)+)

```

# Answer
> 1 votes
# Python 2, 74 bytes

```
from pylab import*
i=arange(1,input(),2.39996)
polar(i,sqrt(i),'o')
show()

```

# Answer
> 1 votes
# MATL, 20 bytes

```
:2.4*tX^wJ*Ze*'.'&XG

```

Try it at **MATL Online!**

The golden angle, `137.708`deg = `pi*(3-sqrt(5))`rad = `2.39996...`rad is approximated as `2.4`rad.

The following version (**25 bytes**) uses the exact value, up to `double` floating-point precision:

```
:YPI5X^-**tX^wJ*Ze*'.'&XG

```

Try it at **MATL Online!**

# Answer
> 1 votes
# Tcl/Tk, 114

```
grid [canvas .c]
proc P n {time {incr i
.c cr o [lmap h {cos sin cos sin} {expr sqrt($i*2.4)*$h\($i*2.4)+99}]} $n}

```

Example of usage:

```
P 1024

```

and outputs the window

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


# Question
Title: Give me odd, even, square, cube, prime and composite 3-digit numbers
Given a string which is guaranteed to be either `odd`, `even`, `square`, `cube`, `prime` or `composite`, your program or function must return an integer \\$100\le N\le 999\\$ which meets this description.

## Rules

* Your code must be deterministic.
* The choice of the integers is up to you. However, the six answers **must be distinct**. (For instance, if you return \\$113\\$ for *odd*, you cannot return \\$113\\$ for *prime*.)
* You may take the input string in full lower case (`odd`), full upper case (`ODD`) or title case (`Odd`) but it must be consistent.
* This is .

## Example

Below is an example of valid I/O:

* odd → \\$501\\$
* even → \\$140\\$
* square → \\$961\\$ (\\$=31^2\\$)
* cube → \\$343\\$ (\\$=7^3\\$)
* prime → \\$113\\$
* composite → \\$999\\$ (\\$=37\times 3\times 3\times 3\\$)

## Brownie points

For what it's worth, my own solution in JS is currently 24 bytes. So, brownie points for beating that.

**JavaScript (ES6), 24 bytes**

```
MD5: 562703afc8428c7b0a2c271ee7c22aff

```

***Edit**: I can now unveil it since it was found by tsh (just with a different parameter name):*

> ```
> s=>parseInt(s,30)%65+204
> ```

# Answer
> 26 votes
# Python 2, ~~25~~ 22 bytes

```
lambda s:hash(s)%591^1

```

Try it online!

Takes input in upper case and returns the following numbers:

```
ODD        -> 263
EVEN       -> 554
SQUARE     -> 121
CUBE       -> 512
PRIME      -> 349
COMPOSITE  -> 371

```

Generated with this script which searches for formulas following `hash(s)%x?y`, where `?` is any binary operator:

```
from sympy import primerange

# from tqdm.notebook import tqdm

hashes = [
    3275334880723988284, -8482906173967949472, -4710393751006474557,
    1654718638908055491, -6487253012923789248, 8925015453505786600
]

dyads = {
    int.__mul__, int.__mod__, int.__add__,
    int.__sub__, int.__rshift__, int.__lshift__,
    int.__xor__, int.__or__, int.__and__,
    int.__pow__, int.__floordiv__
}

primes = set(primerange(100, 1000))
squares = {x**2 for x in range(10, 32)}
cubes = {x**3 for x in range(5, 10)}

# for x in tqdm(range(6, 1000)):
for x in range(6, 1000):
    for y in range(1, 100):
        for z in dyads:
            a, b, c, d, e, f = r = [z(h%x, y) for h in hashes]
            if (
                len(set(r)) == 6
                and min(r) > 99
                and max(r) < 1000
                and a%2 == 1
                and b%2 == 0
                and c in squares
                and d in cubes
                and e in primes
                and f not in primes
            ):
                print(x, y, z)

```

Try it online!

# Answer
> 13 votes
# JavaScript (Node.js), 29 bytes

```
n=>121+'qvdou r'.search(n[1])

```

Try it online!

## How?

I found six numbers which were close to 121, then simply placed them strategically.

And also thanks to Arnauld for reminding me of the `search` method.

# Answer
> 13 votes
# Brachylog, 10 bytes

Takes in the input in full upper case. Sum of the character code points times 415 mod 998. A sum-less version would multiply the second element with 493, modulo 583.

```
ạ+×₄₁₅%₉₉₈

```

Try it online!

```
┌───┬────┬──────┬────┬─────┬─────────┐
│ODD│EVEN│SQUARE│CUBE│PRIME│COMPOSITE│
├───┼────┼──────┼────┼─────┼─────────┤
│403│580 │361   │343 │431  │339      │
└───┴────┴──────┴────┴─────┴─────────┘

```

Found with this crude J script, typing in the operations manually:

```
NB. returns 1 iff correct solution
test_f =: =@i.@# ([ -: *) [: (1 = 2&|)`(0 = 2&|)`((= <.)@%:)`(3 (= <.)@%: ])`(1&p:)`(1 < #@q:)`:0 [:(**/@~:)  (* <&1000 * >&99)"0
NB. try some variants
vars =: ,/ (a=:i.1000)|/ (b=:i.1000)*/ (1#.3&u:)&> ODD`EVEN`SQUARE`CUBE`PRIME`COMPOSITE
NB. show valid solutions
(((,/a,"0/b),.&<"1 [) #~ (test_f :: 0)"1) vars

```

# Answer
> 8 votes
# Rattle, ~~21, 20~~ 18 bytes

```
|Ig1n+8s%7[3g+5s]g

```

Try it Online!

This is my first ever answer with my own interpreter running on my own website!!!

# Outputs

```
odd: 113
even: 126
square: 121
cube: 125
prime: 127
composite: 119

```

# Explanation

```
|                 takes the user's input as a string
 I                splits this string into characters and stores them in consecutive memory
                    slots
  g1              gets the character at index 1 (2nd character, Rattle is 0-indexed)
    n             converts this character to its ASCII code (int value)
     +8           adds 8 to this value
       s          saves this value to memory at the current pointer

   %7             takes mod(7) of the value on top of the stack. This gives three for
                    inputs of "prime" and "odd" (which are special cases)
     [3 .... ]    if the value on top of the stack is three, the code in this if statement
                    executes
        g         gets the value from memory at the pointer
         +5       adds five to this value to fix the special cases
           s      saves the result to memory
              g   gets the value saved in memory, prints implicitly

```

# Answer
> 8 votes
# Python 3, ~~22~~ 21 bytes

```
lambda x:628*x[2]%831

```

Try it online!

Takes input in uppercase as a byte string. Takes the penultimate character's code, and applies some hashing to get:

```
ODD => 323
EVEN => 120
SQUARE => 196
CUBE => 729
PRIME => 139
COMPOSITE => 158

```

Found using this brute-force program: Try it online!

PS: I retract my downvote. Writing and optimising various brute-force programs was actually quite fun. (I don't think it's great to have too many challenges like this, though)

# Answer
> 6 votes
# Jelly,  ~~8~~  7 bytes

-1 thanks to the default. (looked for shorter salt/domain combinations with domains other than the one byte `1000` I'd considered and the different case formats allowed in the OP.)

```
91,651ḥ

```

A monadic Link accepting a list of characters that yields an integer:

```
input      output   (notes)
odd        897
even       516
square     625      (25²)
cube       125      (5³)
prime      347
composite  752      (2⁴×47)

```

**Try it online!**

### How?

```
91,651ḥ - Link: list of characters, S
  ,   ḥ - hash (S) using...
91      - ... salt: literal = 91
   651  - ... domain: literal 651 (i.e. a domain of [1..651])

```

The salt for the 8 byte version, using a domain of `[1..1000]` and only the lower-case version of the inputs, was found using this Python code (Try it online!); it can easily be modified to search other domains and to go through the three allowed case formats:

```
import hashlib

from sympy import isprime

def main():
    odds = set(range(101, 1000, 2))
    evens = set(range(100, 1000, 2))
    primes = set()
    composites = set()
    for n in range(100, 1000):
        if isprime(n):
            primes.add(n)
        else:
            composites.add(n)
    squares = {n ** 2 for n in range(10, 32)}
    cubes = {n ** 3 for n in range(5, 11)}
    values = ["odd", "even", "square", "cube", "prime", "composite"]
    domain_length = 1000
    parts = [
        [
            int.from_bytes(
                hashlib.shake_256(repr(list(v)).encode("utf-8")).digest(512)[i : i + 8],
                "little",
            )
            for i in range(0, 512, 8)
        ]
        for v in values
    ]
    salt = 1
    while 1:
        if (
            hfn(parts, salt, domain_length, 3) in cubes
            and hfn(parts, salt, domain_length, 2) in squares
            and hfn(parts, salt, domain_length, 4) in primes
            and hfn(parts, salt, domain_length, 5) in composites
            and hfn(parts, salt, domain_length, 1) in evens
            and hfn(parts, salt, domain_length, 0) in odds
        ):
            print(salt - 1)
            break
        salt += 1

def hfn(parts, salt, domain_length, value_index):
    return (
        sum(
            ((salt >> i) - (salt >> i + 1)) * parts[value_index][i] for i in range(64)
        )
        % 18446744073709551616
        * domain_length
        >> 64
    )

if __name__ == "__main__":
    main()

```

# Answer
> 5 votes
# JavaScript (Node.js), 28 bytes

```
n=>122+'vdou r'.search(n[1])

```

Try it online!

All credits go to Recursive Co., I would have commented but since It's my first time on posting on stackexchange I don't have the reputation for that. When search doesn't find anything it return -1, making it possible to remove q and saving one byte.

# Answer
> 4 votes
# JavaScript (ES6), 24 bytes

```
x=>parseInt(x,30)%17^212

```

Try it online!

Some other 24 bytes

```
x=>parseInt(x,30)%65+204
x=>parseInt(x,33)%37+497
x=>parseInt(x+87,35)%349

```

---

# JavaScript (Node.js), 22 bytes

```
x=>Buffer(x)[3]%29^115

```

Try it online!

Some other 22 bytes

```
x=>Buffer(x)[3]%87^115
x=>Buffer(x)[3]%89^113
x=>Buffer(x)[3]%55^115 // UpperCase
x=>Buffer(x)[3]%57^113 // UpperCase

```

# Answer
> 4 votes
# Java (JDK), 22 bytes

```
s->150-s.hashCode()%30

```

Try it online!

## Outputs

```
       odd: 139
      even: 140
    square: 169
      cube: 125
     prime: 149
 composite: 155

```

## Alternate

```
s->160-s.hashCode()%50

```

Try it online!

## How

Brute-forced with this code:

```
import java.util.*;

class Main {

  private static long[] cubes = computeCubes(100, 1000);
  private static long[] squares = computeSquares(100, 1000);
  private static long[] primes = computePrimes(100, 1000);

  public static void main(String[] args) {
    for (int o = 0; o <= 1000; o++) {
      for (int m = 2; m < 10000; m++) {
        if (test(o, m)) {
          System.out.printf("o = %d, m = %d%n", o, m);

          System.out.printf("odd: %d%n",       f("odd",       o, m));
          System.out.printf("even: %d%n",      f("even",      o, m));
          System.out.printf("square: %d%n",    f("square",    o, m));
          System.out.printf("cube: %d%n",      f("cube",      o, m));
          System.out.printf("prime: %d%n",     f("prime",     o, m));
          System.out.printf("composite: %d%n", f("composite", o, m));
          System.out.printf("%n");
        }
      }
    }
  }

//  static long f(String s, int o, int m) {
//    return o + s.hashCode() % m;
//  }

  static long f(String s, int o, int m) {
    return o - s.hashCode() % m;
  }

  static boolean test(int o, int m) {
    var odd =       f("odd",       o, m);
    var even =      f("even",      o, m);
    var square =    f("square",    o, m);
    var cube =      f("cube",      o, m);
    var prime =     f("prime",     o, m);
    var composite = f("composite", o, m);

    var values = new long[]{ odd, even, square, cube, prime, composite };

    var result = Arrays.stream(values)
                   .filter(v -> 100 <= v && v < 1000)
                   .distinct()
                   .count()
                 == 6;

    result &= odd % 2 == 1;
    result &= even % 2 == 0;
    result &= Arrays.binarySearch(squares, square) >= 0;
    result &= Arrays.binarySearch(cubes, cube) >= 0;
    result &= Arrays.binarySearch(primes, prime) >= 0;
    result &= Arrays.binarySearch(primes, composite) < 0;

    return result;
  }

  private static long[] computeSquares(int min, int max) {
    var minSqrt = (int)Math.sqrt(min); if (minSqrt * minSqrt < min) minSqrt++;
    var maxSqrt = (int)Math.sqrt(max);
    var squares = new long[maxSqrt - minSqrt + 1];
    for (int i = 0; i < squares.length; i++) {
      var sqrt = minSqrt + i;
      squares[i] = sqrt * sqrt;
    }
    return squares;
  }
  private static long[] computeCubes(int min, int max) {
    int minCbrt = (int)Math.pow(min, 1/3d); if (minCbrt * minCbrt * minCbrt < min) minCbrt++;
    int maxCbrt = (int)Math.pow(max, 1/3d);
    var cubes = new long[maxCbrt - minCbrt + 1];
    for (int i = 0; i < cubes.length; i++) {
      int cbrt = minCbrt + i;
      cubes[i] = cbrt * cbrt * cbrt;
    }
    return cubes;
  }
  private static long[] computePrimes(int min, int max) {
    var composites = new boolean[max];
    composites[2] = false;
    var primes = new long[max];
    var primeCount = 0;
    for (int i = 2; i < max; i++) {
      if (!composites[i]) {
        for (int c = i * i; c < max; c += i) {
          composites[c] = true;
        }
        primes[primeCount++] = i;
      }
    }
    var minPos = Arrays.binarySearch(primes, 0, primeCount, min);
    var maxPos = Arrays.binarySearch(primes, 0, primeCount, max);
    return Arrays.copyOfRange(primes, minPos < 0 ? ~minPos : minPos, primeCount);
  }
}

```

Try it online!

# Answer
> 3 votes
# Python 3, 42 bytes

```
lambda s:sum(s[:-1])-2+6*(81in s)+(77in s)

```

Try it online!

Takes input as `bytes` in uppercase.

Not as short as an uninteresting clone of the current shortest formula, and can very likely be golfed further, but I wanted to show a different approach.

My first instinct on seeing this challenge was to use `sum`, because you can sum a byte string in Python 3 and it's a useful quick method to do string lookups like this.

Cube numbers were definitely the hardest to get to behave with a sum, because there are only 3 practicable cube numbers in the region of the sums of the strings (\\$ 6^3, 7^3, 8^3 \\$).

I played around with different slices of the string and different input casings, and I found that `sum(s[:-1])` was promising:

```
ODD => 147
EVEN => 224
SQUARE => 396
CUBE => 218
PRIME => 312
COMPOSITE => 622

```

Subtracting 2 makes `216`, a cube, while keeping the rest. `396` is also very close to `400`, and the rest were pretty easy too.

`81in s` tests for a `Q`, and then `+6*()` adds 6 if there is one (abusing Python's weak interpretation of booleans). Similarly, `+(77in s)` fixes `PRIME` by making `311` instead of `310`. (I'm sure these bits can be golfed somehow.)

# Answer
> 3 votes
# Python 3, ~~26~~ 25 bytes

```
lambda x:497+int(x,33)%37

```

Try it online!

*-1 thanks to ovs*

Converts the string to an integer in base 33, then does a bit of hashing.

Outputs:

```
odd => 509
even => 508
square => 529
cube => 512
prime => 499
composite => 522

```

Found using this brute-force script and a tiny bit of manual filtration:

```
PRIMES = {101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997}
SQUARES = {256, 900, 144, 400, 529, 784, 289, 676, 169, 441, 576, 961, 196, 324, 841, 729, 225, 100, 484, 361, 625}
CUBES = {125, 216, 343, 512, 729}

CUBE, SQUARE, PRIME, EVEN, ODD, COMPOSITE = "cube", "square", "prime", "even", "odd", "composite"

for s in range(800):
    for b in range(32, 37):
        for m in range(1, 10000):
                if \
                    s + int(CUBE, b) % m in CUBES \
                    and \
                    s + int(SQUARE, b) % m in SQUARES \
                    and \
                    s + int(PRIME, b) % m in PRIMES \
                    and \
                    s + int(COMPOSITE, b) % m not in PRIMES \
                    and \
                    (s + int(ODD, b) % m) % 2 \
                    and \
                    (s + int(EVEN, b) % m) % 2 == 0:
                        print(f"{s} + int(x, {b}) % {m}")

```

Try it online!

# Answer
> 3 votes
# Python 2, 24 bytes

```
lambda s:hash(s)%853^702

```

An unnamed function accepting a string that returns an integer:

```
      odd: 783
     even: 832
   square: 196
     cube: 512
    prime: 661
composite: 679

```

**Try it online!**

---

...or perhaps 21 in Python 3?

```
lambda b:b[2]**95%547

```

where `b` is `bytes` if that is allowed in place of a string.

# Answer
> 3 votes
# 05AB1E, 6 bytes

```
HƵ₅%₁+

```

Try it online!

This computes `from_hex(input)%193+256`, found by the same script I used for my Python answer.

# Answer
> 2 votes
# Charcoal, 12 bytes

```
Ｉ﹪⁺⁴⁷⁰⍘Ｓγ⁸⁶⁶

```

Try it online! Link is to verbose version of code. Takes input in lower case. Explanation:

```
       Ｓ        Input string
      ⍘ γ       Converted from base 95
  ⁺⁴⁷⁰          Plus 470
 ﹪       ⁸⁶⁶    Modulo 866
Ｉ               Cast to string
                Implicitly print

```

These constants were the only ones I could find that worked with lowercase inputs. There are other constants that work for title or upper case:

```
           lower    Title       UPPER
           + 470 162 710 100 254 588 708
           % 866 586 778 840 851 948 972
         odd 327 155 401 723 683 671 659
        even 206 400 750 278 286 386 470
      square 729 169 529 529 361 841 841
        cube 343 343 729 729 343 729 729
       prime 269 397 457 659 467 919 571
   composite 299 511 119 539 495 451 763

```

I also tried base 26 but I didn't find any solutions. I also tried "base 1000" which had one solution for each case: `+499, %837: 819 176 121 512 389 371` (lowercase) `+674, %703: 173 194 225 216 577 512` (title case) `+334, %667: 353 186 625 512 383 372` (upper case).

# Answer
> 1 votes
## Batch, 74 bytes

```
@cmd/cset/aeven=120,square=121,odd=123,cube=125,prime=127,composite=128,%1

```

Case insensitive. Explanation: Sets six variables and evaluates the input.

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~24~~ ~~19~~ 18 bytes

```
Hash@#~Mod~619-90&

```

Try it online!

```
Hash@#~Mod~775+35&

```

Try it online!

This code was developed on Mathematica `12.3.0 for Mac OS X x86 (64-bit) (May 10, 2021)` and verified on `12.0.1 for Linux x86 (64-bit) (October 16, 2019)`. According to the documentation,

> The "Expression" hash code is computed from the internal representation of an expression and may vary between computer systems and from one version of the Wolfram Language to another.

# Answer
> 0 votes
# C (gcc), 23 bytes

```
#define f(n)n[3]%29^115

```

Try it online!

* just a port of tsh answer the difference is : while js had to use buffer() C can access every single character directly.

---
Tags: code-golf, integer, open-ended-function
---


title: Tips for golfing in Red

text:
# Question
Title: Tips for golfing in Red
As the June 2021 Language of the Month is Red, what are some general tips for golfing in Red language?

Please suggest tips that are at least somewhat specific to Red (e.g. "remove comments" isn't a valid tip here).

Please one tip per answer!

# Answer
## Type casting:

In Red you usually use `to <type> <spec>` or the predifined `to-<type> value` functions:

```
>> to integer! 3.14
== 3
>> to-integer 2.71
== 2
>> to char! 65
== #"A"
>> to-integer #"A"
== 65

```

`<type>` can be a datatype or an example value (a prototype). That's why we can shorten the above examples as follows:

```
>> to 1 3.14
== 3
>> to 0 2.71
== 2
>> to sp 65   ; sp is space = #" "
== #"A"
>> to 1 #"A"
== 65

```

Of course this can be applied to all datatypes that have literal representation:

```
>> to[]123 ; to block! 123
== [123]
>> to""[123] ; to-string [123]
== "123"
>> to 1-1-1[2 6 2021]; to-date [2 6 2021]
== 2-Jun-2021
>> to now[2 6 2021]
== 2-Jun-2021
>> to 0.0.0[255 0 0] ; to tuple! [255 0 0]
== 255.0.0
>> to sky[255 228 196] ; sky is a predifined color 164.200.255 (a tuple!)
== 255.228.196
>> to 1x1[-10 42]; to-pair [-10 42]
== -10x42
>> to#{}"string"; to-binary "string"
== #{737472696E67}

```
> 7 votes

# Answer
## String conversion with `do`

`do` is Red's equivalent of an `eval` command. It evaluates code as a string. It is useful when wanting to convert a string to an integer (or any valid Red expression):

```
to-integer n  # The obvious way
to 0 n        # From @GalenIvanov's type casting tip
do n          # `do` is shortest

```
> 6 votes

# Answer
## Flatten a list of lists:

`form` the block into a string (`form` returns a user-friendly string representation of a value), then `load` the string (`load` returns a value or block of values by reading and evaluating a source)

```
>> b: [1 [2 3] [4 [5 6] 7]]
>> form b
== "1 2 3 4 5 6 7"
>> load form b
== [1 2 3 4 5 6 7]

>> b: [a b [c d [e f [g]]]]
== [a b [c d [e f [g]]]]
>> form b
== "a b c d e f g"
>> load form b
== [a b c d e f g]

```
> 4 votes

# Answer
# The many uses of `collect` and `keep`

`collect`'s help page shows the following:

```
USAGE:
     COLLECT body

DESCRIPTION:
     Collect in a new block all the values passed to KEEP function from the body block.
     COLLECT is a function! value.

ARGUMENTS:
     body         [block!] "Block to evaluate."

REFINEMENTS:
     /into        => Insert into a buffer instead (returns position after insert).
        collected    [series!] "The buffer series (modified)."

```

basically, `collect` takes all values passed to `keep` within its argument block and returns a series with those return values.

Effectively, it works as a way in which you can apply any block of code to a series and collect results from it.

You can use it as a map:

`collect[foreach i arr[keep i + 1]]` (increments each array element)

a filter:

`collect[foreach i arr [if i < 2 [keep i]]]` (keeps all array elements less than 2)

and much more. It finds use in any general place where you need to gather values for a code golf question. I have used it in this answer as a flatmap, for example.
> 4 votes

# Answer
## More on type casting

Another non-universal alternative to type conversion is to use some arithmetic operation on the identity value (in the desired type) for the operation and the value to convert:

`integer!` to `float!`:

```
>> to-float 5
== 5.0
>> to 0.0 5
== 5.0
>> 0.0 + 5
== 5.0

```

`char!` to `integer!`:

```
>> to-integer #"A"
== 65
>> to 0 #"A"
== 65
>> 0 +#"A"
== 65

```

`integer!` to `pair!` (a pair with equal `x` and `y` values)

```
>> as-pair 5 5
== 5x5
>> to-pair[5 5]
== 5x5
>> as-pair 5 5
== 5x5
>> to 1x1 5
== 5x5
>> 1x1 * 5
== 5x5

```

`integer!` to `tuple!` (a tuple with all parts equal)

```
>> to-tuple[255 255 255]
== 255.255.255
>> to 0.0.0[255 255 255]
== 255.255.255
>> 0.0.0 + 255
== 255.255.255

```

`integer!` or `float!` to `percent!`:

```
>> to-percent 12
== 1200%
>> to 1% 12
== 1200%
>> 0%+ 12
== 1200%

```
> 3 votes

# Answer
## Use `any` to provide a default value

Some functions (`find`, `select` and so on) could return `none`. The long way to structure your code around their result is to use conditionals - `if`, `either` etc.

Let's find the number of occurences of each character in the string "Tips for golfing in Red". `h` is a `map!` that wiil hold the frequencies. The verbose way is to use `either key[true-code][false-code]` \- if the `key` exists do `true-code`, otherwise do `false-code` :

```
h: #()
s: "Tips for golfing in Red"
foreach c s[h/:c: 1 + either k: h/:c[k][0]]
h
== #(
    #"T" 1
    #"i" 3
    #"p" 1
    #"s" 1
    #" " 4
    #"f" 2
    #"o...

```

We can achieve the same result with `any` \- it evaluates and returns the first truthy value. The first value in the block is the value we want to test for existence, the seconf one - the default value. So, if the key doesn'r exist, `any` will return the default value:

```
h: #()
s: "Tips for golfing in Red"
foreach c s[h/:c: 1 + any[h/:c 0]]
h
== #(
    #"T" 1
    #"i" 3
    #"p" 1
    #"s" 1
    #" " 4
    #"f" 2
    #"o...

```
> 3 votes

# Answer
## Use `alter` instead of append/insert

Sometimes it is certain that the value we are appending to a list, is not aleady present. In such case we can use `alter` instead of `append` for 1 byte less. `alter` appends a value if it's not found in the series, otherwise, removes it from the series.

```
>> b: [1 2 3 4 5]
== [1 2 3 4 5]
>> alter b 6
== true
>> b
== [1 2 3 4 5 6]

```
> 2 votes

# Answer
## `forall` instead of `foreach`

If you reference the current value of the series only once, you can save a byte by using `forall` instead of `foreach` :

```
>> p: [3 1 4 1 5 9 2]
== [3 1 4 1 5 9 2]
>> foreach n p[prin n]
3141592
>> forall p[prin p/1]
3141592

```
> 2 votes

# Answer
## Use some of the predefined `char!` values

```
>> ? char!
    null             #"^@"
    newline          #"^/"
    slash            #"/"
    escape           #"^["
    comma            #","
    lf               #"^/"
    cr               #"^M"
    space            #" "
    tab              #"^-"
    dot              #"."
    sp               #" "
    dbl-quote        #"^""

```

`sp` for space (`#" "` or `" "`), `lf` for newline (`#"^/"` or `"^/"`), `tab` (`#"^-"` or `"^-"`) etc. can save you a byte if enclosed in brackets or between strings:

```
either a/1 = i[1][" "]
either a/1 = i[1][sp]

```
> 1 votes

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


# Question
Title: Tips for golfing in Z80 or SM83 machine code
There's only one question for machine-language golfing, and it's for the ia32 and amd64 architectures. Here's one for a predecessor of them: the Zilog Z80!

The ISA is available here.

As usual, if your tip is only applicable to a certain environment/calling convention, please indicate that in your answer.

> Only one tip per answer (see here).

You can also offer tips for the closely related Sharp SM83. The ISA for that is available here.1

Please mark your tips as to whether they're applicable to Z80, SM83, or both; the ISAs might be similar, but there are many differences.

1. It's labeled as the LR35902; that's the SiC that was used in the DMG and CGB. It had an SM83 core.

# Answer
> 3 votes
## Shadow registers

When you're short on registers, you can use the shadow registers - `af'`, `bc'`, `de'` and `hl'`. These registers map directly to their usual counterparts (without `'`). You can exchange registers using `ex reg, reg'` or `exx`. The later exchanges all registers (`af` and `af'`, `bc` and `bc'`, etc...). Drawbacks:

* not compatible with "usual" registers, you can't use for example `ld` to assign from a standard to a shadow register.
* they were originally meant to be used inside ISRs, so the interrupts should be disabled while you use them.

# Answer
> 2 votes
Here's a tip to start off: `jp` is generally a bad idea.

Unless your code is more than 128 bytes long (which it probably won't be), you can definitely save a byte with a `jr`. As a bonus, your code will be position-independent.

Just one quick warning: the offset of `jr` is from the start of the instruction on Z80 (so `18 00` is an infinite loop), but the end on SM83 (so `18 00` is a two-byte three-cycle no-op).

Therefore, `jr` on SM83 can offset the IP by any amount from -126 to 129, but on Z80 it's -128 to 127.

# Answer
> 2 votes
## Use `ldir` and friends.

Instead of many successive loads, from the same location to a consecutive block of memory, you can use `ldir`:

```
    ld (mem),a
    ld (mem+1),a
    ld (mem+2),a
    ld (mem+3),a
    ld (mem+4),a
    ld (mem+5),a

```

... becomes:

```
    ld hl,mem
    ld de,mem+1
    ld (hl),a
    ld bc,5
    ldir

```

If you're familiar with x86 assembly, `ldir` is somewhat comparable to `rep movsb`. Of course, z80 has many more instructions like that: `cpir, inir, otir, lddr, cpdr, indr, otdr`

# Answer
> 2 votes
## `cp` and `cpl`-related tricks

```
cp 0

cp 1

```

become respectively

```
or a

dec a

```

... saving a single byte. You can also use `cpl` instead of `xor $FF` to flip bits in a byte.

You can also use `cpl` for subtracting accumulator from some constant:

```
cpl
add a, X+1

```

... is one byte shorter than `neg` and `add a, X`

# Answer
> 2 votes
## Messing with flags

You can do the following flag operations in a compact way:

* Carry flag: setting - `scf`, resetting - `or a`, alternatively `and a` (modifies sign and zero).
* Zero flag: setting - `cp a` (resets carry, modifies sign), resetting - `or 1` (resets carry, modifies `a` and sign).
* Sign flag: setting - `or $80` (reset zero and carry, modifies `a`), resetting - `xor a` (clear `a`, set zero, clear carry).
* Half carry: `and a` \- set, `xor a` \- reset.

# Answer
> 1 votes
Another simple one:

**Use `xor a` or `sub a` instead of `ld a,0` to reset (load `0` to) the `a` register.**

Their use seems to be controversial in non-golfing situations (some sources use them, some advise against them), but I see no point in *not using* them:

* **They are 1 byte, while an immediate load is two bytes.**
* They are also faster (not generally a consideration for ): they take 4 T-states, while an equivalent immediate load takes 7 T-states (8 on SM83).

They have a single side-effect: they modify the flags, while a load does not. You can play around with this if you also want some flags to be set/reset.

On Z80, the flags are affected as follows:

| Flags: | `S` | `Z` | `H` | `P/V` | `N` | `C` |
| --- | --- | --- | --- | --- | --- | --- |
| `xor a` | `0` | `1` | `0` | **`1`** | **`0`** | `0` |
| `sub a` | `0` | `1` | `0` | **`0`** | **`1`** | `0` |

# Answer
> 1 votes
Some of the most useful commands for golfing in Z80 assembly language are `sbc` and `adc`. They often allow you to interact with the flag C in ways that are absolutely amazing. Here are some cool examples:

1. **How to create a decreasing counter in A that stops at 0?** `or a : jr nz,$+3 : dec a` is ugly. `sub 1 : adc 0` is faster, runs in constant time and can often be size-optimized, if you have handy 0s or 1s in one of your other registers. Have to stop at a non-zero value N? No problem: `sub N : adc N-1`. This also works for incrementing counter that is clamped at 255: `add 1 : sbc 0`. This also works for a incrementing counter clamped at an arbitrary value N: `add 256-N : sbc 256-N-1`.
2. **How to load an arbitrary value N to A when flag C is up (or zero otherwise)?** `ld a,N : jr c,$+3 : xor a` is not the way. `sbc a : and N` usually is (it is faster and shorter by 2 bytes).
3. **How about loading into A value N if flag C is up or value M if flag C is down?** Don't mess with conditional jumps! Use `sbc a : and N-M : add M`. (This last trick I believe is invented by GriV).

# Answer
> 0 votes
## Use `jp` instead of `call` and `ret`.

In some cases, `jp` is viable (contrary to the other answer). `call procedure / ret` can in some cases be replaced with `jp procedure`, saving one byte.

---
Tags: code-golf, tips, assembly, machine-code
---


title: A bracket amphitheater

text:
# Question
Title: A bracket amphitheater
## Specification

Write the shortest possible code in any language that does the following:

It takes two arguments, x and y, and generates x + y lines of text.

The first x lines should consist of y nested pairs of square brackets separated by a space surrounding a single digit, which cycles from 1 to 9, then 0 to 9, etc. from line to line.
The following y lines have the letter X in place of the digit and successively replace the innermost remaining pair of square brackets with spaces. The last line only contains the X, surrounded by spaces.

All output is ASCII.
You may choose to output a final newline (following a space), but you may also choose not to.
You may use either CR, CRLF, or LF as newline sequences.
The last line must contain an appropriate number of spaces following the central X.

The only valid inputs are positive integers. Zero is not a valid input.
You’re free to impose a reasonable, technically-driven limit on input size, even if the problem is solvable without. For instance, if there’s some function available for 16 bit integers that isn’t for bigints for some reason, and using it makes your program shorter, that’s a valid reason for a input size constraint.
Your code may reject invalid input or simply behave in any way on invalid input.

## Examples

Example with x = 12, y = 8:

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

```

Example with x = 5, y = 1

```
[ 1 ]
[ 2 ]
[ 3 ]
[ 4 ]
[ 5 ]
  X

```

Example with x = 1, y = 10:

```
[ [ [ [ [ [ [ [ [ [ 1 ] ] ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [ [   X   ] ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [ [     X     ] ] ] ] ] ] ] ]
[ [ [ [ [ [ [       X       ] ] ] ] ] ] ]
[ [ [ [ [ [         X         ] ] ] ] ] ]
[ [ [ [ [           X           ] ] ] ] ]
[ [ [ [             X             ] ] ] ]
[ [ [               X               ] ] ]
[ [                 X                 ] ]
[                   X                   ]
                    X

```

# Answer
> 7 votes
# Jelly,  ~~33~~  27 bytes

-1 thanks to caird coinheringaahing (use of `)`)

```
Ø[j
%⁵Ç¡);”XÇ¡⁶i”];C$$¦ƬḊ¤G

```

A full program that accepts \\$x\\$ and \\$y\\$ and prints the result.

**Try it online!**

### How?

```
Ø[j - Link 1, wrap in []: a
Ø[  - list of characters = ['[', ']']
  j - join (with a) = ['[', a, ']']

%⁵Ç¡);”XÇ¡⁶i”];C$$¦ƬḊ¤G - Main Link: x, y
    )                   - for each (v in [1..x]):
 ⁵                      -   ten
%                       -   (v) modulo (10)
   ¡                    -   repeat (y times):
  Ç                     -     call last Link (1) as a monad
                     ¤  - nilad followed by link(s) as a nilad:
      ”X                -   character = 'X'
         ¡              -   repeat (y times):
        Ç               -     call last Link (1) as a monad
                   Ƭ    -   loop until no change, collecting up inputs:
                  ¦     -     sparse application...
                 $      -     ...to (1-based) indices: last two links as a monad:
           i”]          -       first index of character ']' (call this i)
                $       -       last two links as a monad:
               C        -         complement -> 1-i
              ;         -         concatenate -> [i, 1-i]
          ⁶             -     ...of: space character (replaces innermost [] with spaces)
                    Ḋ   -   dequeue (remove the leading one with all []s present)
     ;                  - concatenate
                      G - format as a grid
                        - implicit print

```

# Answer
> 7 votes
# 05AB1E, 22 bytes

Takes the inputs in reversed order.

```
L<+'[δиR²LT%¹'Xи«ªζ».º

```

Try it online!

This works by creating half of the columns, transposing to rows and adding the other half with a mirror.

```
L<+                     # push range [x .. x+y-1]
   '[δи                 # for each number in the range, create a list of that many '['
       R                # reverse the list of lists
        ²L              # push range [1 .. x]
          T%            # each number %10
            ¹'Xи        # a list of y 'X'
                «       # append this to the modulo range
                 ª      # append to the list of columns
                  ζ     # transpose to list of rows, filling with space
                   »    # join each row by spaces, rows by newlines
                    .º  # self-intersected mirror

```

# Answer
> 4 votes
# Python 2, 87 bytes

*-1 byte thanks to @Lynn, with a `min` trick*

The main difference from the previous answer is a clever use of `min`. When `i <= x`, `v+'X'+v` equals `X`, which is lexicographically larger than any digit `[0-9]`. When `i > x`, `v` starts with leading spaces, which causes `i%10` to be chosen instead.

```
x,y=input()
i=0
while y:i+=1;y-=i>x;v=(i-x)*'  ';print'[ '*y+min(`i%10`,v+'X'+v)+' ]'*y

```

Try it online!

### Python 2, 88 bytes

Input is taken from STDIN.

```
x,y=input()
i=0
while y:i+=1;y-=i>x;v=-x%i*'  ';print'[ '*y+[`i%10`,v+'X'+v][i>x]+' ]'*y

```

I finally get an oppurtunity to show off this nice trick: `-x%i*' '`. It turns out that `-x%i` is equivalent to `i-x`, when `i>=x`. On its own, it is one byte longer, but it allows us to drop the parentheses in the string multiplication.

Try it online!

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

Building line by line.

Expects `(x)(y)`.

```
(x,n=0)=>g=y=>y?'[ '[R='repeat'](y-=++n>x)+(n>x?(p='  '[R](n-x))+'X'+p:n%10)+' ]'[R](y)+`
`+g(y):''

```

Try it online!

---

# JavaScript (ES6), 115 bytes

Building character by character.

Expects `(x)(y)`.

```
x=>y=>(k=x-1,g=n=>k-~y?`
][X${(x-k)%10}`[--n?(q=n-y+~y)?n&(k>0|q*q>k*k*4)&&2^q>0:5^k<0:k---k]+g(n||w):'')(w=y*4+2)

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 92 bytes

```
x=>h=(y,N=x+y)=>N?h(y,N-1)+(g=_=>y--?x+y<N?`  ${g()}  `:`[ ${g()} ]`:N>x?'X':N%10)(y)+`
`:''

```

Try it online!

# Answer
> 2 votes
# , ~~105~~ 115 bytes

```
function(x,y,`|`=strrep,l="[ ",r=" ]",p=paste0)cat(p(l|y,1:x%%10,r|y),p(l|y:1-1,s<-"  "|1:y,"X",s,r|y:1-1),sep="
")

```

Try it online!

~~Returns a vector of lines.~~
Prints the result.

```
function(x,y,           # function taking x and y as input
`|`=strrep,             # assign strrep to operator with low precedence
l="[ ",r=" ]",p=paste0) # defining variables in function's arguments saves bytes
cat(                    # concatenate the two parts
p(                      # paste element-wise (recycling if necessary)
 l|y,                   # left bracket with space y times
  1:x%%10,              # row index mod 10
   r|y),                # and right bracket preceded by space y times
p(                      # the second part
 l|y:1-1,               # `l` declining number of times
  s<-"  "|1:y,          # required number of spaces (save as s for later)
   "X",                 # literal X
    s,                  # we've seen that before
     r|y:1-1),          # right brackets
sep="\n")               # join elements by newline

```

# Answer
> 2 votes
# , 73 bytes

```
+:@[|."1((,'X'$~,&1)~10":@|1+i.),.~' []'{~[:(,.~2*|."1)@|.@,.0,~"0+>/&i.[

```

Try it online!

# Answer
> 2 votes
# Vyxal, 56 bytes

```
(‛[ ¹*n₀%‛ ]¹*++,)¹‹(‛  n›*‛[ ¹nε‹*p\X+‛  n›*+‛ ]¹nε‹*+,

```

Try it Online!

Its bad I know.

# Answer
> 1 votes
# JavaScript (Node.js), ~~166 164~~ 128 bytes

```
x=>y=>[...Array(x+y)].map((e,i)=>'[ '[r='repeat'](d=i<x?y:y-i+x-1)+(m='  '[r](i>=x&&y-d))+(i<x?++i%10:'X')+m+' ]'[r](d)).join`
`

```

Try it online!

Unlike my previous submission which replaced a string of spaces, this simply builds each line.

# Answer
> 1 votes
# Charcoal, ~~33~~ ~~30~~ 28 bytes

```
ＮθＮη↷²⭆θ﹪⊕ιχ×Xη⸿Ｅη×[⁺θι‖ＢＵＥ¹

```

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

```
ＮθＮη

```

Input `x` and `y`.

```
↷²

```

Change the default output direction to downwards.

```
⭆θ﹪⊕ιχ

```

Print the central column of digits.

```
×Xη

```

Print the `X`s.

```
⸿Ｅη×[⁺θι

```

Move to the previous column and print the right trapezium of `[`s to the left.

```
‖Ｂ

```

Mirror the canvas.

```
ＵＥ¹

```

Spread out the columns.

# Answer
> 1 votes
# Canvas, 22 bytes

```
[×＊ω［］ｋ⇵∔⁷｛Ａ％］╶X＊∔＋ ＊│

```

Try it here!

Takes input as `y` on the first line and `x` on the second line.

# Answer
> 1 votes
# Excel, 112 bytes

```
=LET(z,SEQUENCE(A1+B1),s,IF(z>A1,z-A1,0),b,REPT(" ",s),REPT("[",B1-s)&b&IF(z>A1,"X",MOD(z,10))&b&REPT("]",B1-s))

```

Link to Spreadsheet

## Explanation

* `=LET(z,SEQUENCE(A1+B1),` z = vertical array of numbers from 1 to x+y
* `s,IF(z>A1,z-A1,0),` if z \> x then s = z - x else z = 0
* `b,REPT(" ",s),` string of spaces for each row
* `REPT("[",B1-s)` string of "\[" for each row
* `&b&IF(z>A1,"X",MOD(z,10))&b` spaces and middle for each row
* `&REPT("]",B1-s))` string of "\]" for each row

# Answer
> 1 votes
# Haskell, 122 bytes

```
x%y=mapM putStrLn[(r>>"[ ")++min[last$show i](v++"X"++v)++(r>>" ]")|i<-[1..x+y],r<-[[1+max i x..x+y]],v<-[[1..i-x]>>"  "]]

```

Try it online!

The most noteworthy trick here is using `min` to decide between digits and `X`.

Namely, `"X"` \> `"9"` \> `" X "` \> `" X "` \> …

so that if we only make `v` have the right amount of spaces, then `min(digit, v++"X"++v)` will choose the appropriate string.

# Answer
> 0 votes
# Python 2, 147 bytes

```
lambda x,y,N="  ":"\n".join(["[ "*y+`z%10`+y*" ]"for z in range(1,x+1)]+["[ "*z+N*(y-z)+"X"+N*(y-z)+" "+z*"] "for z in range(y,0,-1)])+"\n"+N*y+"X"

```

Try it online!

-8 bytes thanks to @ophact

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