34
\$\begingroup\$

Take a positive integern as input, and output an-by-n checkerboard matrix consisting of1 and0.

The top left digit should always be1.

Test cases:

n = 11n = 21 00 1n = 31 0 10 1 01 0 1n = 41 0 1 00 1 0 11 0 1 00 1 0 1

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

askedJun 15, 2017 at 17:32
Stewie Griffin's user avatar
\$\endgroup\$
9
  • \$\begingroup\$Is a list of strings OK?\$\endgroup\$CommentedJun 15, 2017 at 17:52
  • \$\begingroup\$Yes, that's OK.\$\endgroup\$CommentedJun 15, 2017 at 17:53
  • 1
    \$\begingroup\$Related.\$\endgroup\$CommentedJun 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\$CommentedJun 15, 2017 at 19:09
  • \$\begingroup\$@BradC it's not required. The first approachhere is valid.\$\endgroup\$CommentedJun 15, 2017 at 20:19

64 Answers64

13
\$\begingroup\$

Jelly, 4 bytes

52 seconds!

+€ḶḂ

Try it online!

answeredJun 15, 2017 at 17:33
Leaky Nun's user avatar
\$\endgroup\$
3
  • 8
    \$\begingroup\$"52 seconds!" like I'm not used to it...\$\endgroup\$CommentedJun 15, 2017 at 17:35
  • 8
    \$\begingroup\$Do ya'll have, like, a beeper, you wear 24/7 for new PPCG challenges?\$\endgroup\$CommentedJun 16, 2017 at 20:43
  • \$\begingroup\$@carusocomputing Those who have a faster internet connection are usually the lucky ones that will win.\$\endgroup\$CommentedJun 17, 2017 at 14:16
9
\$\begingroup\$

MATL, 5 bytes

:otYT

Try it atMATL online!

Explanation

Consider input4 as an example.

:    % Implicit input, n. Push range [1 2 ... n]     %   STACK: [1 2 3 4]o    % Parity, element-wise     %   STACK: [1 0 1 0]t    % Duplicate     %   STACK: [1 0 1 0], [1 0 1 0]YT   % Toeplitz matrix with two inputs. Implicit display     %   STACK: [1 0 1 0;     %           0 1 0 1;     %           1 0 1 0;     5           0 1 0 1]
Suever's user avatar
Suever
11.2k1 gold badge24 silver badges52 bronze badges
answeredJun 15, 2017 at 21:34
Luis Mendo's user avatar
\$\endgroup\$
8
\$\begingroup\$

Haskell,504139 38 bytes

Thanks to nimi and xnor for helping to shave off a total of9 10 bytes

f n=r[r"10",r"01"]where r=take n.cycle

Alternately, for one byte more:

(!)=(.cycle).takef n=n![n!"10",n!"01"]

or:

r=flip take.cyclef n=r[r"10"n,r"01"n]n

Probably suboptimal, but a clean, straightforward approach.

answeredJun 15, 2017 at 17:59
Julian Wolf's user avatar
\$\endgroup\$
9
  • \$\begingroup\$concat.repeat iscycle:n!l=take n$cycle l. If you go pointfree it saves one more byte:(!)=(.cycle).take.\$\endgroup\$CommentedJun 15, 2017 at 18:26
  • \$\begingroup\$Lovely! I knew there was a builtin for that, but couldn't remember the name for the life of me\$\endgroup\$CommentedJun 15, 2017 at 18:31
  • \$\begingroup\$I was going to suggestf n|r<-take n.cycle=r[r"10",r"01"] or similar. but Haskell seems to infer the wrong type forr? It works with explicit typingf n|r<-take n.cycle::[a]->[a]=r[r"10",r"01"].\$\endgroup\$CommentedJun 15, 2017 at 18:59
  • 1
    \$\begingroup\$@JulianWolf Haskell seems to havetrouble inferring polymorphic types\$\endgroup\$CommentedJun 15, 2017 at 19:43
  • 1
    \$\begingroup\$@zbw I thought this was the case but usingNoMonomorphismRestriction didn't help. Nor didRank2Types orRankNTypes. Do you know what's going on there?\$\endgroup\$CommentedJun 16, 2017 at 4:59
7
\$\begingroup\$

Japt, 6 bytes

ÆÇ+X v

Test it online! (Uses-Q flag for easier visualisation)

Explanation

 Æ   Ç   +X vUoX{UoZ{Z+X v}}  // Ungolfed                 // Implicit: U = input numberUoX{          }  // Create the range [0...U), and map each item X to    UoZ{     }   //   create the range [0...U), and map each item Z to        Z+X      //     Z + X            v    //     is divisible by 2.                 // Implicit: output result of last expression

An interesting thing to note is thatv isnot a "divisible by 2" built-in. Instead, it's a "divisible by X" built-in. However, unlike most golfing languages, Japt's functions do not have fixed arity (they can accept any number of right-arguments). When given 0 right-arguments,v assumes you wanted2, and so acts exactly like it was given2 instead of nothing.

answeredJun 15, 2017 at 17:36
ETHproductions's user avatar
\$\endgroup\$
7
\$\begingroup\$

V,16, 15 bytes

Ài10À­ñÙxñÎÀlD

Try it online!

Hexdump:

00000000: c069 3130 1bc0 adf1 d978 f1ce c06c 44    .i10.....x...lD
answeredJun 15, 2017 at 17:43
DJMcMayhem's user avatar
\$\endgroup\$
6
\$\begingroup\$

APL (Dyalog), 8 bytes

~2|⍳∘.+⍳

Try it online!

Explanation

Let's call the argumentn.

⍳∘.+⍳

This creates a matrix

1+1 1+2 1+2 .. 1+n2+1 2+2 2+3 .. 2+n...n+1 n+2 n+3 .. n+n

Then2| takes modulo 2 of the matrix (it vectorises) after which~ takes the NOT of the result.

answeredJun 15, 2017 at 17:42
user41805's user avatar
\$\endgroup\$
5
\$\begingroup\$

JavaScript ES6,555451 46 bytes

Saved 1 byte thanks to @Neil

Saved 2 bytes thanks to @Arnauld

n=>[...Array(n)].map((_,i,a)=>a.map(_=>++i&1))

Try it online!

This outputs as an array of arrays. JavaScript ranges are pretty unweildy but I use[...Array(n)] which generates an array of sizen

answeredJun 15, 2017 at 18:36
Downgoat's user avatar
\$\endgroup\$
3
  • \$\begingroup\$It's still a byte shorter to use the index parameters:n=>[...Array(n)].map((_,i,a)=>a.map((_,j)=>(i+j+1)%2))\$\endgroup\$CommentedJun 15, 2017 at 18:41
  • \$\begingroup\$@Neil huh, I never thought to use the third parameter in map, thanks!\$\endgroup\$CommentedJun 15, 2017 at 18:47
  • \$\begingroup\$@Arnauld thanks! that inspired me to save 5 more bytes!\$\endgroup\$CommentedJun 15, 2017 at 22:55
5
\$\begingroup\$

J, 9 bytes

<0&=$&1 0

Try it online!

answeredJun 16, 2017 at 0:21
miles's user avatar
\$\endgroup\$
5
\$\begingroup\$

05AB1E,9 7 bytes

-2 bytes thanks to Emigna

LDÈD_‚è

Try it online!

Explanation

LDÈD_‚sè» Argument nLD        Push list [1 .. n], duplicate  ÈD      Map is_uneven, duplicate    _     Negate boolean (0 -> 1, 1 -> 0)     ‚    List of top two elements of stack      è   For each i in [1 .. n], get element at i in above created list          In 05AB1E the element at index 2 in [0, 1] is 0 again
answeredJun 16, 2017 at 6:29
kalsowerus's user avatar
\$\endgroup\$
2
  • \$\begingroup\$You can cut the» as list-of-lists output is okay and you can also removes.\$\endgroup\$CommentedJun 16, 2017 at 7:27
  • \$\begingroup\$Explanation is a bit irrelevant.\$\endgroup\$CommentedJun 17, 2017 at 14:14
5
\$\begingroup\$

Bash + rs, 39

  • 3 bytes saved thanks to @roblogic
eval echo \$[~{1..$1}+{1..$1}\&1]|rs $1

Try it online!

answeredJun 15, 2017 at 18:37
Digital Trauma's user avatar
\$\endgroup\$
1
  • 1
    \$\begingroup\$you can do simplyrs $1, saving 3 bytes\$\endgroup\$CommentedFeb 16 at 7:25
4
\$\begingroup\$

Mathematica, 25 bytes

1-Plus~Array~{#,#}~Mod~2&
answeredJun 15, 2017 at 17:55
Martin Ender's user avatar
\$\endgroup\$
4
\$\begingroup\$

Clojure, 36 bytes

#(take %(partition % 1(cycle[1 0])))

Yay, right tool for the job.

answeredJun 15, 2017 at 21:14
NikoNyrh's user avatar
\$\endgroup\$
4
\$\begingroup\$

Retina,33 30 bytes

.+$*1$_¶1110T`10`01`¶.+¶

Try it online! Explanation: The first stage converts the input to unary using1s (conveniently!) while the second stage turns the value into a square. The third stage inverts alternate bits on each row while the last stage inverts bits on alternate rows. Edit: Saved 3 bytes thanks to @MartinEnder.

answeredJun 15, 2017 at 18:45
Neil's user avatar
\$\endgroup\$
2
  • \$\begingroup\$$`1$' is just$_.\$\endgroup\$CommentedJun 16, 2017 at 5:27
  • \$\begingroup\$01 is justd. (Post is too old for me to bother editing it.)\$\endgroup\$CommentedMar 27 at 16:49
4
\$\begingroup\$

Java (OpenJDK 8),80 77 bytes

-3 bytes thanks to Kevin Cruijssen

j->{String s="1";for(int i=1;i<j*j;s+=i++/j+i%j&1)s+=1>i%j?"\n":"";return s;}

Try it online!

Oh look, a semi-reasonable length java answer, with lots of fun operators.

lambda which takes an int and returns a String. Works by using the row number and column number using / and % to determine which value it should be, mod 2;

Ungolfed:

j->{    String s="1";    for(int i=1; i<j*j; s+= i++/j + i%j&1 )        s+= 1>i%j ? "\n" : "";    return s;}
totallyhuman's user avatar
totallyhuman
17.4k3 gold badges34 silver badges89 bronze badges
answeredJun 15, 2017 at 19:28
PunPun1000's user avatar
\$\endgroup\$
2
  • \$\begingroup\$You can remove the space to save a byte. The challenge states the output format is flexible. Oh, and you can save two more bytes by changing(i++/j+i%j)%2 toi++/j+i%j&1 so you won't need those parenthesis. Which make the total 1 byte shorter than my nested for-loop solution (n->{String r="";for(int i=0,j;i++<n;r+="\n")for(j=0;j<n;r+=j+++i&1);return r;}), so +1 from me. :)\$\endgroup\$CommentedJun 16, 2017 at 7:26
  • \$\begingroup\$@KevinCruijssen Yeah I was still waiting on a response on the space. I didn't think about & having higher precedence than % and &1 == %2\$\endgroup\$CommentedJun 16, 2017 at 12:02
4
\$\begingroup\$

Arturo,3936 32 bytes

$[n][map n'x->map n'y->%x+y+1 2]

Try it

-3 thanks to alephalpha's simpler method

Prettified and rearranged for clarity:

$[n][                     ; a function taking an argument n    map n 'x ->           ; map over 1..n, assign current elt to x        map n 'y ->       ; map over 1..n again, assign current elt to y            (x+y+1)%2     ; what it looks like]                         ; end function
answeredMar 1, 2023 at 22:00
chunes's user avatar
\$\endgroup\$
3
\$\begingroup\$

MATL, 7 bytes

:t!+2\~

Try it online!

Explanation:

         % Implicit input (n):        % Range from 1-n, [1,2,3] t       % Duplicate, [1,2,3], [1,2,3]  !      % Transpose, [1,2,3], [1;2;3]   +     % Add        [2,3,4; 3,4,5; 4,5,6]    2    % Push 2     [2,3,4; 3,4,5; 4,5,6], 2     \   % Modulus    [0,1,0; 1,0,1; 0,1,0]      ~  % Negate     [1,0,1; 0,1,0; 1,0,1]

Note: I started solving this in MATLafter I posted the challenge.

answeredJun 15, 2017 at 17:47
Stewie Griffin's user avatar
\$\endgroup\$
4
  • \$\begingroup\$Equivalent, and shorter::&+o~\$\endgroup\$CommentedJun 15, 2017 at 21:25
  • 1
    \$\begingroup\$Still learning :-) I'll update tomorrow. I liked your other approach too :-)\$\endgroup\$CommentedJun 15, 2017 at 21:44
  • 1
    \$\begingroup\$This is what I came up with, too. And hey, you only use thepure MATL instruction set, not those peskyY-modified instructions @LuisMendo uses.\$\endgroup\$CommentedJun 16, 2017 at 21:04
  • \$\begingroup\$@Sanchises Pesky,huh? :-P\$\endgroup\$CommentedJun 16, 2017 at 21:09
3
\$\begingroup\$

Brachylog, 19 bytes

⟦₁Rg;Rz{z{++₁%₂}ᵐ}ᵐ

Try it online!

answeredJun 15, 2017 at 18:07
Leaky Nun's user avatar
\$\endgroup\$
3
\$\begingroup\$

Charcoal, 8 bytes

UON10¶01

Try it online! Explanation: This roughly translates to the following verbose code (unfortunately the deverbosifier is currently appending an unnecessary separator):

Oblong(InputNumber(), "10\n01");
answeredJun 15, 2017 at 18:38
Neil's user avatar
\$\endgroup\$
3
\$\begingroup\$

Brachylog, 15 bytes

^₂⟦₁%₂ᵐ;?ḍ₎pᵐ.\

Try it online!

Explanation

Example Input: 4^₂               Square:                            16  ⟦₁             1-indexed Range:                   [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]    %₂ᵐ          Map Mod 2:                         [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]       ;?ḍ₎      Input-Chotomize:                   [[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]]           pᵐ.   Map permute such that..             .\  ..the output is its own transpose: [[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]]
answeredJun 15, 2017 at 19:52
Fatalize's user avatar
\$\endgroup\$
3
\$\begingroup\$

Pyth, 9 bytes

VQm%+hdN2

Try this!

another 9 byte solution:

mm%+hdk2Q

Try it!

answeredJun 15, 2017 at 20:15
KarlKastor's user avatar
\$\endgroup\$
3
\$\begingroup\$

///, 87 bytes + input

/V/\\\///D/VV//*/k#D#k/k#D&k/k&DVk/k\D/SD/#/rDSkk/10DSk/1D&/V#rV#0r;VV0;VVV1;V\D/r/S/&[unary input in asterisks]

Try it online! (input for 4)

Unary input in1s, 95 bytes + input

/V/\\\///D/VV//&1/k#&D&|D/#k/k#D&k/k&DVk/k\D/SD/#/rDSkk/10DSk/1D&/V#rV#0r;VV0;VVV1;V\D/r/S/&&[unary input in ones]|

Try it online! (input for 8)

How does this work?

  • V andD are to golf\/ and// respectively.

  • /*/k#/ and/&1/k#&//&|// separate the input into the equivalent of'k#'*len(input())

  • /#k//k#//&k/k&//\/k/k\// move all theks to the/r/S/ block

  • Ss are just used to pad instances whereks come after/s so that they don't get moved elsewhere, and theSs are then removed

  • #s are then turned intor\ns

  • The string ofks is turned into an alternating1010... string

  • Ther\ns are turned into1010...\ns

  • Every pair of1010...\n1010\n is turned into1010...\01010...;\n

  • Either0; or1; are trimmed off (because the01010... string is too long by 1)

answeredJun 15, 2017 at 23:05
boboquack's user avatar
\$\endgroup\$
3
\$\begingroup\$

Swi-Prolog, 142 bytes.

t(0,1).t(1,0).r([],_).r([H|T],H):-t(H,I),r(T,I).f([],_,_).f([H|T],N,B):-length(H,N),r(H,B),t(B,D),f(T,N,D).c(N,C):-length(C,N),f(C,N,1).

Try online -http://swish.swi-prolog.org/p/BuabBPrw.pl

It outputs a nested list, so the rules say:

  • t() is a toggle, it makes the 0 -> 1 and 1 -> 0.
  • r() succeeds for an individual row, which is a recursive check down a row that it is alternate ones and zeros only.
  • f() recursively checks all the rows, that they are the right length, that they are valid rows withr() and that each row starts with a differing 0/1.
  • c(N,C) says that C is a valid checkerboard of size N if the number of rows (nested lists) is N, and the helper f succeeds.

Test Cases:enter image description here

answeredJun 20, 2017 at 8:30
TessellatingHeckler's user avatar
\$\endgroup\$
1
  • \$\begingroup\$Can't you strip off all newlines?\$\endgroup\$CommentedMar 29, 2023 at 21:50
3
\$\begingroup\$

Nekomata, 5 bytes

ᵒ+→2%

Attempt This Online!

ᵒ+→2%ᵒ+       Create an (input x input) matrix where the element at (i,j) is i+j  →      Increment   2%    Mod 2
answeredMar 2, 2023 at 0:10
alephalpha's user avatar
\$\endgroup\$
3
\$\begingroup\$

AWK, 57 bytes

{for(;i++<$1^2;$1%2||i%$1||x=!x)printf(x=!x)(i%$1?FS:RS)}

Attempt This Online!

answeredMar 3 at 21:49
xrs's user avatar
\$\endgroup\$
2
\$\begingroup\$

QBIC, 19 bytes

[:|?[b|?(a+c+1)%2';

Explanation

[:|         FOR a = 1 to b (b is read from cmd line)?           PRINT - linsert a linebreak in the output[b|         FOR c = 1 to b?(a+c+1)%2  PRINT a=c=1 modulo 2 (giving us the 1's and 0's';            PRINT is followed b a literal semi-colon, suppressing newlines and               tabs. Printing numbers in QBasic adds one space automatically.
answeredJun 15, 2017 at 17:59
steenbergh's user avatar
\$\endgroup\$
2
\$\begingroup\$

PHP, 56 bytes

Output as string

for(;$i<$argn**2;)echo++$i%2^$n&1,$i%$argn?"":"".!++$n;

Try it online!

PHP, 66 bytes

Output as 2 D array

for(;$i<$argn**2;$i%$argn?:++$n)$r[+$n][]=++$i%2^$n&1;print_r($r);

Try it online!

answeredJun 15, 2017 at 17:51
Jörg Hülsermann's user avatar
\$\endgroup\$
2
\$\begingroup\$

CJam, 17 bytes

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

Try it online!

Returns a list (TIO link has formatted output).

answeredJun 15, 2017 at 18:15
Erik the Outgolfer's user avatar
\$\endgroup\$
2
  • \$\begingroup\$out-golfed\$\endgroup\$CommentedJun 15, 2017 at 21:10
  • \$\begingroup\$@Challenger5 Sorry you can't outgolf with deleted answer.\$\endgroup\$CommentedJun 16, 2017 at 8:19
2
\$\begingroup\$

Mathematica, 23 bytes

ToeplitzMatrix@#~Mod~2&
answeredJun 16, 2017 at 5:21
alephalpha's user avatar
\$\endgroup\$
2
\$\begingroup\$

Octave, 24 bytes

@(n)~mod((a=(1:n))+a',2)

Try it online!


Or the same length:

@(n)mod(toeplitz(1:n),2)

Try it online!

answeredJun 16, 2017 at 5:11
alephalpha's user avatar
\$\endgroup\$
2
\$\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.

answeredJun 16, 2017 at 7:58
Greg Martin's user avatar
\$\endgroup\$

Your Answer

More generally…

  • …Please make sure to answer the question and provide sufficient detail.

  • …Avoid asking for help, clarification or responding to other answers (use comments instead).

Draft saved
Draft discarded

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.