Chessboard pattern

18

4

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

steenslag

Posted 2011-03-07T22:51:24.450

Reputation: 2 070

1I was looking for a tag like 'light-weight' for this. – steenslag – 2011-03-07T22:52:27.710

1Whole and complete program, I suppose? – J B – 2011-03-07T22:52:51.260

@J B: Yes. How do I formulate that? Add 'to stdout' to the required output? – steenslag – 2011-03-07T22:59:13.367

1Just say you want a complete program. You might also want to specify command-line arguments, to prevent confusion with function arguments. – J B – 2011-03-07T23:05:52.490

When you say top-right, do you mean top-left? If not, please correct the example output for input 8. – Peter Taylor – 2011-03-08T00:02:44.480

@Peter Taylor: This is.. it is... well , it is corrected. – steenslag – 2011-03-08T00:18:37.200

I assume an input of zero should produce no output? – Shaun Bebbers – 2019-04-11T15:58:16.847

Answers

5

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.

isaacg

Posted 2011-03-07T22:51:24.450

Reputation: 39 268

... but APL isn't. Thanks for bumping. Wonder if OP will re-accept... – Adám – 2016-02-04T22:02:05.800

"Pyth is much too new to be eligible to win" I don't understand this and reaccept this one. – steenslag – 2016-02-04T22:25:18.817

2@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. – isaacg – 2016-02-04T23:20:30.063

11

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

gnibbler

Posted 2011-03-07T22:51:24.450

Reputation: 14 170

5

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

J B

Posted 2011-03-07T22:51:24.450

Reputation: 9 638

What does the 'x' in 'x 40' do? – steenslag – 2011-03-08T01:45:45.247

2@steenslag: x is the string repetition operator. 'a' x 3 yields 'aaa'. – J B – 2011-03-08T07:34:26.930

4

Python, 48 Characters

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

Nolen Royalty

Posted 2011-03-07T22:51:24.450

Reputation: 330

3

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]

Keith Randall

Posted 2011-03-07T22:51:24.450

Reputation: 19 865

3

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.

Gareth

Posted 2011-03-07T22:51:24.450

Reputation: 11 678

3

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.

marinus

Posted 2011-03-07T22:51:24.450

Reputation: 30 224

3

Ruby 45 42

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

Demo: http://ideone.com/Mw25e

Cristian Lupascu

Posted 2011-03-07T22:51:24.450

Reputation: 8 369

(x=gets.to_i).times saves three chars. Why the sudden renewed interest in this oldie? – steenslag – 2012-07-10T20:48:31.213

@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. :) – Cristian Lupascu – 2012-07-10T21:05:16.083

2

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

st0le

Posted 2011-03-07T22:51:24.450

Reputation: 2 002

2

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);
}

Skizz

Posted 2011-03-07T22:51:24.450

Reputation: 2 225

1I love all the magic numbers. – Joey Adams – 2011-03-10T04:01:43.720

2

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));

zzzzBov

Posted 2011-03-07T22:51:24.450

Reputation: 2 915

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? – Some Guy – 2012-12-12T06:12:36.443

2

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
        }
    }
}

O.O.Balance

Posted 2011-03-07T22:51:24.450

Reputation: 1 499

@ceilingcat Thanks! I managed to shave off one more byte, and applied your approach to my full program as well. 16 bytes saved there. – O.O.Balance – 2018-04-19T08:34:26.700

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;} – Kevin Cruijssen – 2018-04-19T09:21:20.300

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.

– Kevin Cruijssen – 2018-04-19T09:23:22.137

Suggest "X ".charAt(i%n+i/n&1) instead of ((i%n+i/n)%2<1?"X":" ") – ceilingcat – 2019-04-12T17:14:30.217

2

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

Oliver

Posted 2011-03-07T22:51:24.450

Reputation: 7 160

Ah, you edited while I was in chat! Was gonna suggest the same thing. – Shaggy – 2019-03-20T22:58:31.473

2

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!

Dr Y Wit

Posted 2011-03-07T22:51:24.450

Reputation: 511

2

Brainfuck, 140 bytes

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

Oyarsa

Posted 2011-03-07T22:51:24.450

Reputation: 136

2

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.

Sanchises

Posted 2011-03-07T22:51:24.450

Reputation: 8 530

2

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

Johan du Toit

Posted 2011-03-07T22:51:24.450

Reputation: 1 524

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. – Shaun Bebbers – 2019-05-15T15:58:56.823

1

C 81 bytes

– ceilingcat – 2019-09-14T02:44:06.643

2

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.

jseteny

Posted 2011-03-07T22:51:24.450

Reputation: 21

1

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.

– Veskah – 2019-05-17T15:21:14.117

Thanks @Veskah for the suggestion. – jseteny – 2019-05-17T15:32:53.153

Nice solution changing this to a function and using map you get 34 Characters: ("X "*n)sliding n take n map println – pme – 2019-05-21T15:23:02.700

@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. – jseteny – 2019-05-23T10:23:20.363

you are right - sorry seems map is lazy;(. – pme – 2019-05-23T12:49:35.043

2

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

skeevey

Posted 2011-03-07T22:51:24.450

Reputation: 4 139

2

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.

manatwork

Posted 2011-03-07T22:51:24.450

Reputation: 17 865

2

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

Adám

Posted 2011-03-07T22:51:24.450

Reputation: 37 779

1

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)]

user468

Posted 2011-03-07T22:51:24.450

Reputation:

1

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]);}

Joey Adams

Posted 2011-03-07T22:51:24.450

Reputation: 9 929

83 Bytes – Johan du Toit – 2019-05-15T10:09:14.560

1

PHP, 75 bytes

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

Boian Ivanov

Posted 2011-03-07T22:51:24.450

Reputation: 41

1

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

dana

Posted 2011-03-07T22:51:24.450

Reputation: 2 541

10 bytes – Shaggy – 2019-03-20T18:10:10.317

Nice interpreter :) – dana – 2019-03-20T18:12:21.640

1

Thanks :) Drop into the chatroom if you have any feedback or feature requests.

– Shaggy – 2019-03-20T18:15:48.040

1

@Shaggy 8 bytes :P

– Oliver – 2019-03-20T22:41:30.973

1

Canvas, 6 bytes

XX\m⤢m

Try it here!

dzaima

Posted 2011-03-07T22:51:24.450

Reputation: 19 048

1

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.

xnor

Posted 2011-03-07T22:51:24.450

Reputation: 115 687

1

C# (Visual C# Interactive Compiler), 63 bytes

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

Try it online!

dana

Posted 2011-03-07T22:51:24.450

Reputation: 2 541

This gives an incorrect output for odd inputs. – Kevin Cruijssen – 2019-03-21T10:28:30.163

OK - Think I got it :) Thanks for pointing that out. – dana – 2019-03-21T10:47:44.113

1

PowerShell, 39 bytes

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

Try it online!

mazzy

Posted 2011-03-07T22:51:24.450

Reputation: 4 832

1

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

Shaun Bebbers

Posted 2011-03-07T22:51:24.450

Reputation: 1 814

1

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

Shaun Bebbers

Posted 2011-03-07T22:51:24.450

Reputation: 1 814

1

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

streetster

Posted 2011-03-07T22:51:24.450

Reputation: 3 635

1

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!

pme

Posted 2011-03-07T22:51:24.450

Reputation: 111

Think you can drop a couple of the whitespaces for 80 chars... But doesn't look like this works for input of 1 – streetster – 2019-05-20T21:04:39.890

@streetster thanks - this special case cost me 4 bytes;( – pme – 2019-05-21T06:49:00.310

1

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.

Martin Ender

Posted 2011-03-07T22:51:24.450

Reputation: 184 808

1

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

randomra

Posted 2011-03-07T22:51:24.450

Reputation: 19 909

-2 Bytes: ([:{&' X'=/~@$&1 0) – Bolce Bussiere – 2018-04-19T19:58:19.720

16 bytes $"1[:|.&'X '"+i. Try it online!

– Jonah – 2019-04-11T15:44:01.067

1

Q, 33

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

tmartin

Posted 2011-03-07T22:51:24.450

Reputation: 3 917

{(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. – streetster – 2019-05-20T21:19:03.383

1

Ruby 58

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

Phong Si

Posted 2011-03-07T22:51:24.450

Reputation: 11

1

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

Adam Speight

Posted 2011-03-07T22:51:24.450

Reputation: 1 234

1

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:

░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█
█░█░█░█░█░█░█░
░█░█░█░█░█░█░█

Event_Horizon

Posted 2011-03-07T22:51:24.450

Reputation: 287

Does it work for boards with an odd number of squares per side? – Gareth – 2012-07-11T15:58:26.840

@Gareth Now it does – Event_Horizon – 2012-07-11T16:18:15.207

1

PHP, 87

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

Dan Lugg

Posted 2011-03-07T22:51:24.450

Reputation: 121

0

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)

Stephen

Posted 2011-03-07T22:51:24.450

Reputation: 12 293

0

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"

ASCII-only

Posted 2011-03-07T22:51:24.450

Reputation: 4 687

0

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)

Kevin Cruijssen

Posted 2011-03-07T22:51:24.450

Reputation: 67 575

0

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.

Dr Y Wit

Posted 2011-03-07T22:51:24.450

Reputation: 511

0

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

João the Clown

Posted 2011-03-07T22:51:24.450

Reputation: 31

How would I run this, for example on this site: https://tio.run/#mumps

– mbomb007 – 2019-05-15T14:55:11.597

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) – João the Clown – 2019-05-15T18:36:48.430

Input is given as Stdin in the input box, or passed as an argument. How is your program currently taking input? – mbomb007 – 2019-05-15T19:36:34.367

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. – João the Clown – 2019-05-15T20:11:12.007

output of $ZIO: *** Z function or variable not found in or near line 1 Global arrays closed.

Termination message: 100 Software Error – João the Clown – 2019-05-15T20:13:12.613

0

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

recursive

Posted 2011-03-07T22:51:24.450

Reputation: 8 616

0

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

Comrade SparklePony

Posted 2011-03-07T22:51:24.450

Reputation: 5 784

0

Haskell 89 74 charaters

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

Thomas Eding

Posted 2011-03-07T22:51:24.450

Reputation: 796

0

PHP, 88 80 78

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

moteutsch

Posted 2011-03-07T22:51:24.450

Reputation: 121

There is no opening <?php tag, would this still work? – Shaun Bebbers – 2019-05-15T09:16:43.937

1I'm assuming you are running it through the PHP interpreter, not as part of a web-page. – moteutsch – 2019-05-16T12:39:19.137

Thanks, an explanation would be nice to add (i.e., how to run this) – Shaun Bebbers – 2019-05-16T13:41:48.157