32
\$\begingroup\$

Take a positive integer n as input, and output a n-by-n checkerboard matrix consisting of 1 and 0.

The top left digit should always be 1.

Test cases:

n = 1
1

n = 2
1 0
0 1

n = 3
1 0 1
0 1 0
1 0 1

n = 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1

Input and output formats are optional. Outputting the matrix as a list of lists is accepted.

\$\endgroup\$
9
  • \$\begingroup\$ Is a list of strings OK? \$\endgroup\$
    – xnor
    Commented Jun 15, 2017 at 17:52
  • \$\begingroup\$ Yes, that's OK. \$\endgroup\$ Commented Jun 15, 2017 at 17:53
  • 1
    \$\begingroup\$ Related. \$\endgroup\$
    – beaker
    Commented Jun 15, 2017 at 18:51
  • 2
    \$\begingroup\$ Your examples show spaces between numbers on the same row, is that required, so as to look more like a square? \$\endgroup\$
    – BradC
    Commented Jun 15, 2017 at 19:09
  • \$\begingroup\$ @BradC it's not required. The first approach here is valid. \$\endgroup\$ Commented Jun 15, 2017 at 20:19

59 Answers 59

1
2
1
\$\begingroup\$

CJam, 17 bytes

{_[__AAb*<_:!]*<}

Try it online!

Returns a list (TIO link has formatted output).

\$\endgroup\$
2
  • \$\begingroup\$ out-golfed \$\endgroup\$ Commented Jun 15, 2017 at 21:10
  • \$\begingroup\$ @Challenger5 Sorry you can't outgolf with deleted answer. \$\endgroup\$ Commented Jun 16, 2017 at 8:19
1
\$\begingroup\$

Bash + rs, 42

eval echo \$[~{1..$1}+{1..$1}\&1]|rs $1 $1

Try it online.

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

Cheddar, 38 bytes

n->(|>n).map(i->(|>n).map(j->i+j+1&1))

Try it online!

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

Mathematica, 28 bytes

Cos[+##/2Pi]^2&~Array~{#,#}&

Pure function taking a positive integer as input and returning a 2D array. Uses the periodic function cos²(πx/2) to generate the 1s and 0s.

For a little more fun, how about the 32-byte solution

Sign@Zeta[1-+##]^2&~Array~{#,#}&

which uses the locations of the trivial zeros of the Riemann zeta function.

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

braingasm, 21 bytes

;$[$[>+o:<]p[>+<]10.]

Explanation:

;                       Read a number from stdin.
 $[                 ]   That many times...
   $[     ]               That many times...
     >+o:<                  Increase the next cell and print its value modulo 2.
           p[   ]       If the input was even...
             >+<          Increase the next cell once more.
                 10.    Print a newline.
\$\endgroup\$
1
\$\begingroup\$

J, 41 bytes

I know there's a J answer at 9, but I'm pleased to get anything working, even if it's not a tacit programming best possible..

ch=:monad define
2|(2$y)$(1+i.y),(i.y)
)

It takes a number y and generates two lists of numbers 1,2,3,..y and 0,1,2,3,..y-1 to make the offset first and second row, appends them into one long list, reshapes that into a y,y matrix (wrapping around when it runs out), and then does modulo 2 on all the elements to make them a 1 or 0.

   ch 1
1

   ch 2
1 0
0 1

   ch 3
1 0 1
0 1 0
1 0 1

   ch 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1

   ch 5
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
\$\endgroup\$
1
\$\begingroup\$

Python, 73 63 62 66 bytes

Saved 4 bytes thanks to officialaimm

r=range(input());print[''.join([`(x+y+1)%2`for x in r])for y in r]
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Declaring R=range(n) and using R saves 3 bytes. 1 unwanted space between ) and for can be removed as well. \$\endgroup\$
    – 0xffcourse
    Commented Jun 16, 2017 at 7:40
  • 1
    \$\begingroup\$ @officialaimm Sweet, thanks for the tip! I'm new a golfing. I'm thankful for any tips :) \$\endgroup\$
    – Daffy
    Commented Jun 16, 2017 at 19:50
  • 1
    \$\begingroup\$ Just noticed your code is just a snippet, not a function or full program which is not a healthy practice. You can use this instead, only 8 bytes more! \$\endgroup\$
    – 0xffcourse
    Commented Jun 17, 2017 at 1:37
  • 1
    \$\begingroup\$ @officialaimm Noted. Still better than my original submission. Thanks a bunch. :) \$\endgroup\$
    – Daffy
    Commented Jun 17, 2017 at 1:43
1
\$\begingroup\$

q/kdb+, 37 16 bytes

Solution:

{x#x#'(1 0;0 1)}

Example:

q){x#x#'(1 0;0 1)}1
1
q){x#x#'(1 0;0 1)}2
1 0
0 1
q){x#x#'(1 0;0 1)}3
1 0 1
0 1 0
1 0 1
q){x#x#'(1 0;0 1)}4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1

Explanation:

2nd version is much simpler, and thus shorter and faster (4x). Create a 2-item list containing 01... and 10... to the length of the input, then take 'x' number of items from this new list.

{              } / lambda function
      (1 0;0 1)  / 2-item list of (0;1) and (1;0)
   x#'           / take 'x' items from each list, if x=3 then (1 0 1;0 1 0)
 x#              / take 'x' items from *this* list

Notes:

I've re-written this twice during this edit, went from 37->25->24->16 bytes. Now it's a little more competitive.

Edits:

  • -21 bytes with complete re-write...
\$\endgroup\$
1
\$\begingroup\$

Haskell, 43 bytes

h=1:0:h
l=h:(0:h):l
s x=take x$map(take x)l

Try it online!

This creates the infinite checkerboard matrix and saves it to l. Then our function s chops off a square.

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

Husk, 6 bytes

´Ṫ=↑ݬ

Try it online!

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

Thunno, \$ 12 \log_{256}(96) \approx \$ 9.88 bytes

RD2%D1_ZPsAH

Attempt This Online! or see it in a nicer format

Explanation

RD2%D1_ZPsAH  # Implicit input                Example: n=3
RD            # Duplicate range(input)        STACK: [0, 1, 2],  [0, 1, 2]
  2%D         # Duplicate ^ mod 2             STACK: [0, 1, 2],  [0, 1, 0],  [0, 1, 0]
     1_       # 1 - top copy of ^             STACK: [0, 1, 2],  [0, 1, 0],  [1, 0, 1]
       ZP     # Pair top two items            STACK: [0, 1, 2],  [[0, 1, 0], [1, 0, 1]]
         sAH  # 1-based modular indexing      STACK: [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
              # Implicit output
\$\endgroup\$
1
\$\begingroup\$

Pyt, 7 bytes

ř2%Đɐ=Ɩ

Try it online!

ř                    implicit input; řangify
 2%                  modulo 2
   Đ                 Đuplicate
    ɐ=               for ɐll possible pairs, check for equality
      Ɩ              coerce booleans to integers; implicit print

Prints list of lists

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

Pip -S, 8 bytes

%U$+GMCa

Other list-formatting flags such as -l and -p work too. Without a flag, the list of lists is printed without any separators (e.g. 1001 for input 2), which seemed like stretching the permissive output format a bit too far.

Attempt This Online!

Explanation

       a  ; Command-line argument
     MC   ; Map to a square coordinate grid of that size:
  $+G     ;   Sum the two coordinates
 U        ;   Increment
%         ;   Mod 2
\$\endgroup\$
1
\$\begingroup\$

Go, 89 bytes

import."fmt"
func f(n int){
for i:=1;i<=n;i++{
for j:=i;j<i+n;j++{Print(j%2)}
Println()}}

Attempt This Online!

Prints a multi-line string.

Explanation

import ."fmt"               // Boilerplate
func f(n int) {             // Function f taking an integer n:
for i := 1; i <= n; i++ {   //  Loop through each i in [1..n]:
for j := i; j < i+n; j++ {  //   Loop through each j in [i..i+n]:
Print(j%2)}                 //    Print j mod 2 without a newline
Println()}}                 //   Print a newline
\$\endgroup\$
1
\$\begingroup\$

Thunno 2, 5 bytes

RɗDȷ=

Attempt This Online!

Port of my Vyxal answer.

Explanation

       # implicit input
R      # one range
 ɗ     # mod 2
  D    # duplicate
   ȷ   # outer product:
    =  #  equality
       # implicit output
\$\endgroup\$
1
\$\begingroup\$

Uiua, 6 bytes

⊞=.◿2⇡

Try it!

⊞=.◿2⇡
     ⇡  # range
   ◿2   # modulo 2
  .     # duplicate
⊞=      # table by equality
\$\endgroup\$
0
\$\begingroup\$

Mathematica, 28 bytes

Table[Mod[i+j+1,2],{i,#},{j,#}]&
\$\endgroup\$
0
0
\$\begingroup\$

Julia, 38 bytes

n->map(x->x%2,(1:n).+transpose(0:n-1))

The usual approach

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

Actually, 15 bytes

r;╗⌠╜+u⌠2@%⌡M⌡M

Try it online!

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

Python, 43 bytes

lambda n:[('10'*n)[i:i+n]for i in range(n)]

Try it online!

Anonymous function that outputs a list like ['1010', '0101', '1010', '0101'].

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

Python 2, 72 70 61 54 bytes

-7 bytes thanks to Leaky Nun. -1 byte thanks to Wheat Wizard.

lambda n:[[i-~j&1for i in range(n)]for j in range(n)]

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 62 bytes \$\endgroup\$
    – Leaky Nun
    Commented Jun 15, 2017 at 19:06
  • \$\begingroup\$ 54 bytes \$\endgroup\$
    – Leaky Nun
    Commented Jun 15, 2017 at 19:11
0
\$\begingroup\$

C#, 145 Bytes

int u=1;int n=int.Parse(b.Text);for(int i=0;i<n;i++){if(i%2==0){u=1;}else{u=0;}for(int j=0;j<n;j++){t.Text+=u.ToString();u=1-u;}t.Text+="\r\n";}[enter link description here][1]

Try it online!

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

Bash & coreutils, 82 bytes

x=$1;yes 10|tr -d \\n|dd bs=1 count=$[x*x*2]|fold -w$[x*2-1]|grep -om$x "^.\{$x\}"

Takes one command-line integer as input. Apparently the spaces between are optional.

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

Common Lisp, SBCL, 81 bytes

version 1:

(#1=dotimes(i(set'a(read)))(#1#(j a)(format t"~:[1~;0~] "(oddp(+ j i))))(terpri))

version 2:

(lambda(n)(#1=dotimes(i n)(#1#(j n)(format t"~:[1~;0~] "(oddp(+ j i))))(terpri)))

Two loops, and inside I print either 1 and space or zero and space based on parity of (+ j i). (terpri) for newline.

It's long, I know:/

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

C# (.NET Core), 88 bytes

n=>{var r=new int[n,n];for(int i=0,j;i<n;i++)for(j=0;j<n;j++)r[i,j]=(i+j+1)%2;return r;}

Try it online!

I can't believe this is the shortest way to initialize a 2D array of integers, there must be another way...

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

tcl, 82

time {set a "";time {set a $a[expr [incr i]%2]} $n;puts $a;if \!($n%2) incr\ i} $n

demo

Still a looser, but I think i can be golfed down a little bit further.

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

Perl 5, 49 bytes

$_=10x(($n=<>)/2).1x($n%2);say&&y/01/10/while$n--

Try it online!

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

C (gcc), 60 59 bytes

i;f(n){for(i=n*n;i--;)printf(i%n?"%d":"%d\n",i%n+i/n+1&1);}

Try it online!

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

Japt -m, 5 4 bytes

Outputs a 2D array.

W£°v

Try it

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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