18
\$\begingroup\$

Input: a positive number, smaller then 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.


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\$
  • 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\$ – Peter Taylor Mar 8 '11 at 0:02

49 Answers 49

5
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ ... but APL isn't. Thanks for bumping. Wonder if OP will re-accept... \$\endgroup\$ – Adám Feb 4 '16 at 22:02
  • \$\begingroup\$ "Pyth is much too new to be eligible to win" I don't understand this and reaccept this one. \$\endgroup\$ – steenslag Feb 4 '16 at 22:25
  • 1
    \$\begingroup\$ @steenslag To explain, there is a standard loophole that languages newer than the question are ineligible. This is to prevent languages specifically designed to do well at a specific challenge. You're free to do what you want with your challenge, of course. \$\endgroup\$ – isaacg Feb 4 '16 at 23:20
11
\$\begingroup\$

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

\$\endgroup\$
5
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ What does the 'x' in 'x 40' do? \$\endgroup\$ – steenslag Mar 8 '11 at 1:45
  • 2
    \$\begingroup\$ @steenslag: x is the string repetition operator. 'a' x 3 yields 'aaa'. \$\endgroup\$ – J B Mar 8 '11 at 7:34
4
\$\begingroup\$

Python, 48 Characters

x,i=input(),0
exec'print(x*"X ")[i:i+x];i^=1;'*x
\$\endgroup\$
3
\$\begingroup\$

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

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.

\$\endgroup\$
3
\$\begingroup\$

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

Ruby 45 42

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

Demo: http://ideone.com/Mw25e

\$\endgroup\$
  • \$\begingroup\$ (x=gets.to_i).times saves three chars. Why the sudden renewed interest in this oldie? \$\endgroup\$ – steenslag Jul 10 '12 at 20:48
  • \$\begingroup\$ @steenslag Thanks! I've applied your tip. I just saw this question at the top of the list and thought I'd post an answer to dust off my Ruby skills. Apparently I haven't dusted them off enough. :) \$\endgroup\$ – Cristian Lupascu Jul 10 '12 at 21:05
2
\$\begingroup\$

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

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);
}
\$\endgroup\$
  • 1
    \$\begingroup\$ I love all the magic numbers. \$\endgroup\$ – Joey Adams Mar 10 '11 at 4:01
2
\$\begingroup\$

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));
\$\endgroup\$
  • \$\begingroup\$ I'm pretty sure you can convert to number like +'1' instead of parseInt('1'). Won't give you an integer, but I don't think having it be an integer is important here, is it? \$\endgroup\$ – Some Guy Dec 12 '12 at 6:12
2
\$\begingroup\$

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

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.

\$\endgroup\$
2
\$\begingroup\$

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
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ @ceilingcat Thanks! I managed to shave off one more byte, and applied your approach to my full program as well. 16 bytes saved there. \$\endgroup\$ – O.O.Balance Apr 19 '18 at 8:34
  • \$\begingroup\$ Doing two s+= is 2 bytes shorter than those parenthesis: n->{var s="";for(int i=0;i<n*n;s+=++i%n<1?"\n":"")s+=(i%n+i/n)%2<1?"X":" ";return s;} \$\endgroup\$ – Kevin Cruijssen Apr 19 '18 at 9:21
  • \$\begingroup\$ Or 1 more byte off (84 in total) by printing directly (with the parenthesis back again xD): 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. \$\endgroup\$ – Kevin Cruijssen Apr 19 '18 at 9:23
  • \$\begingroup\$ Suggest "X ".charAt(i%n+i/n&1) instead of ((i%n+i/n)%2<1?"X":" ") \$\endgroup\$ – ceilingcat Apr 12 at 17:14
2
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Ah, you edited while I was in chat! Was gonna suggest the same thing. \$\endgroup\$ – Shaggy Mar 20 at 22:58
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

Brainfuck, 140 bytes

-[+[+<]>>+]>++++[<++++++++>-]<<<<<<,[->+>+>+<<<]>>[->[->.<[->>.>]<<<]<[<<<]>>>>>[-<+>]>[-<+>]<<[->>+<<]<<[-<+>]<[->+>>+<<<]++++++++++.[-]>>]
\$\endgroup\$
2
\$\begingroup\$

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

enter image description here

\$\endgroup\$
  • \$\begingroup\$ You may use the on...go to command conditionally, like ON-(I+JAND1)GOTO3:?"X";: where it is zero, it will fall through to the following statement, in this case, if (I + J AND 1) === 0 then it will print the X. This allows you to pack in more statements per line and save bytes. \$\endgroup\$ – Shaun Bebbers May 15 at 15:58
  • 1
    \$\begingroup\$ C 81 bytes \$\endgroup\$ – ceilingcat Sep 14 at 2:44
2
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PP&CG and nice first answer. There's a nice site called Try It Online that allows you to get easy byte counts and share runs. Check the other Scala answer to see an example of it. It's not required mind you, just nice to have. \$\endgroup\$ – Veskah May 17 at 15:21
  • \$\begingroup\$ Thanks @Veskah for the suggestion. \$\endgroup\$ – jseteny May 17 at 15:32
  • \$\begingroup\$ Nice solution changing this to a function and using map you get 34 Characters: ("X "*n)sliding n take n map println \$\endgroup\$ – pme May 21 at 15:23
  • \$\begingroup\$ @pme Thanks for the suggestion, but there is no output if I replace foreach with map. However I change it to a function as you suggested. \$\endgroup\$ – jseteny May 23 at 10:23
  • \$\begingroup\$ you are right - sorry seems map is lazy;(. \$\endgroup\$ – pme May 23 at 12:49
1
\$\begingroup\$

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

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

Q, 33

{$[1=x mod 2;x;x-1]cut(x*x)#"X "}
\$\endgroup\$
  • \$\begingroup\$ {(x;x-1-x mod 2)#"X "} for 22... ah no, has the same bug as yours - doesnt have 4 X's on the odd rows for input 8. \$\endgroup\$ – streetster May 20 at 21:19
1
\$\begingroup\$

Ruby 58

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

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:

░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█
\$\endgroup\$
  • \$\begingroup\$ Does it work for boards with an odd number of squares per side? \$\endgroup\$ – Gareth Jul 11 '12 at 15:58
  • \$\begingroup\$ @Gareth Now it does \$\endgroup\$ – Event_Horizon Jul 11 '12 at 16:18
1
\$\begingroup\$

PHP, 87

for($x=0;$x<$m=$argv[1];$x++){echo"\n";for($y=0;$y<$m;$y++)echo($y^($x%2))%2?' ':'X';}
\$\endgroup\$
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\$
  • \$\begingroup\$ -2 Bytes: ([:{&' X'=/~@$&1 0) \$\endgroup\$ – Bolce Bussiere Apr 19 '18 at 19:58
  • \$\begingroup\$ 16 bytes $"1[:|.&'X '"+i. Try it online! \$\endgroup\$ – Jonah Apr 11 at 15:44
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\$

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.