22
\$\begingroup\$

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
\$\endgroup\$
8
  • 1
    \$\begingroup\$ I was looking for a tag like 'light-weight' for this. \$\endgroup\$
    – steenslag
    Mar 7 '11 at 22:52
  • 1
    \$\begingroup\$ Whole and complete program, I suppose? \$\endgroup\$
    – J B
    Mar 7 '11 at 22:52
  • \$\begingroup\$ @J B: Yes. How do I formulate that? Add 'to stdout' to the required output? \$\endgroup\$
    – steenslag
    Mar 7 '11 at 22:59
  • 1
    \$\begingroup\$ Just say you want a complete program. You might also want to specify command-line arguments, to prevent confusion with function arguments. \$\endgroup\$
    – J B
    Mar 7 '11 at 23:05
  • \$\begingroup\$ When you say top-right, do you mean top-left? If not, please correct the example output for input 8. \$\endgroup\$ Mar 8 '11 at 0:02

56 Answers 56

1
2
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ -2 Bytes: ([:{&' X'=/~@$&1 0) \$\endgroup\$ Apr 19 '18 at 19:58
  • \$\begingroup\$ 14 bytes 'X '{~2|+/~@i. Try it online! \$\endgroup\$
    – Jonah
    Sep 8 '20 at 5:07
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

PHP, 75 bytes

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

Canvas, 6 bytes

XX\m⤢m

Try it here!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
4
  • \$\begingroup\$ 10 bytes \$\endgroup\$
    – Shaggy
    Mar 20 '19 at 18:10
  • \$\begingroup\$ Nice interpreter :) \$\endgroup\$
    – dana
    Mar 20 '19 at 18:12
  • 1
    \$\begingroup\$ Thanks :) Drop into the chatroom if you have any feedback or feature requests. \$\endgroup\$
    – Shaggy
    Mar 20 '19 at 18:15
  • 1
    \$\begingroup\$ @Shaggy 8 bytes :P \$\endgroup\$
    – Oliver
    Mar 20 '19 at 22:41
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 39 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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!

ZX81 Chess Board Generator Simulator

\$\endgroup\$
1
\$\begingroup\$

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!

Commodore C64 Chess Board pattern

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ Think you can drop a couple of the whitespaces for 80 chars... But doesn't look like this works for input of 1 \$\endgroup\$
    – mkst
    May 20 '19 at 21:04
  • \$\begingroup\$ @streetster thanks - this special case cost me 4 bytes;( \$\endgroup\$
    – pme
    May 21 '19 at 6:49
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Perl 5 + -n -M5.10.0, 35 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ This gives an incorrect output for odd inputs. \$\endgroup\$ Mar 21 '19 at 10:28
  • \$\begingroup\$ OK - Think I got it :) Thanks for pointing that out. \$\endgroup\$
    – dana
    Mar 21 '19 at 10:47
1
\$\begingroup\$

Vyxal, 10 bytes

‛X *½h:(…Ṙ

Try it Online!

A little long...

\$\endgroup\$
0
\$\begingroup\$

Haskell 89 74 charaters

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

PHP, 88 80 78

for($x=0;$x++<$i=$argv[1];){for($y=0;$y++<$i;)echo($y+$x)%2?" ":"X";echo"\n";}
\$\endgroup\$
3
  • \$\begingroup\$ There is no opening <?php tag, would this still work? \$\endgroup\$ May 15 '19 at 9:16
  • 1
    \$\begingroup\$ I'm assuming you are running it through the PHP interpreter, not as part of a web-page. \$\endgroup\$
    – moteutsch
    May 16 '19 at 12:39
  • \$\begingroup\$ Thanks, an explanation would be nice to add (i.e., how to run this) \$\endgroup\$ May 16 '19 at 13:41
0
\$\begingroup\$

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)
\$\endgroup\$
0
\$\begingroup\$

Charcoal, 10 bytes

Eθ⭆θ§X ⁺ιλ

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

Explanation

Eθ           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"
\$\endgroup\$
0
\$\begingroup\$

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.
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
5
  • \$\begingroup\$ How would I run this, for example on this site: tio.run/#mumps \$\endgroup\$
    – mbomb007
    May 15 '19 at 14:55
  • \$\begingroup\$ I can't figure out how to give user input in that site you mention, but if you want, you can set the size at the beginning: ` s v=8 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"))` Though the ObjectScript version doesn't work on tio.run (proprietary to Intersystems) \$\endgroup\$ May 15 '19 at 18:36
  • \$\begingroup\$ Input is given as Stdin in the input box, or passed as an argument. How is your program currently taking input? \$\endgroup\$
    – mbomb007
    May 15 '19 at 19:36
  • \$\begingroup\$ In an interactive M session, Stdin is set to be the user's terminal. Something might be wrong with the setup for tio.run. w $ZIO is the translated I/O device and that throws an error. If I try to explicitly say to use Stdin via u 0 or u $Principal, I also get an error. \$\endgroup\$ May 15 '19 at 20:11
  • \$\begingroup\$ output of $ZIO: *** Z function or variable not found in or near line 1 Global arrays closed. Termination message: 100 Software Error \$\endgroup\$ May 15 '19 at 20:13
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

Pip, 25 bytes

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

A simple for loop.

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
1
0
\$\begingroup\$

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
```
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.