チェッカーボードマトリックスを作成する


26

入力として正の整数nを取り、10で構成されるnn列のチェッカーボード行列を出力します

左上の数字は常に1でなければなりません。

テストケース:

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

入力および出力形式はオプションです。行列をリストのリストとして出力することができます。


文字列のリストは大丈夫ですか?
-xnor

はい、大丈夫です。
スティーヴィーグリフィン


2
あなたの例は同じ行の数字の間にスペースを示していますが、それは正方形のように見えるために必要ですか?
BradC

@BradCは必須ではありません。最初のアプローチここでは有効です。
スティーヴィーグリフィン

回答:



9

MATL、5バイト

:otYT

MATLオンライン試しください

説明

4例として入力を検討してください。

:    % 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]

7

Japt、6バイト

ÆÇ+X v

オンラインでテストしてください!(使用-Q視覚化を容易にするためにフラグを)

説明

 Æ   Ç   +X v
UoX{UoZ{Z+X v}}  // Ungolfed
                 // Implicit: U = input number
UoX{          }  // 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

興味深いの、「2で割り切れる」ビルトインでvないことです。代わりに、「Xで割り切れる」ビルトインです。ただし、ほとんどのゴルフ言語とは異なり、Japtの関数には固定されたアリティがありません(任意の数の正しい引数を受け入れることができます)。0の右引数を指定vすると2、あなたが望んでいると仮定し2、何も与えられずに与えられたように動作します。



7

Haskell50 41 39 38バイト

合計9 10バイトを削るのを手伝ってくれたnimiとxnorに感謝

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

または、1バイト以上の場合:

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

または:

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

おそらく最適ではありませんが、簡潔でわかりやすいアプローチです。


concat.repeatですcyclen!l=take n$cycle l。ポイントフリーになると、もう1バイト節約されます(!)=(.cycle).take
-nimi

ラブリー!そのためのビルトインがあることは知っていましたが、私の人生の名前を思い出すことができませんでした
Julian Wolf

私は提案f n|r<-take n.cycle=r[r"10",r"01"]または類似するつもりだった。しかし、Haskellは間違った型を推測しているようrです。明示的な型指定で機能しますf n|r<-take n.cycle::[a]->[a]=r[r"10",r"01"]
-xnor

1
@JulianWolf Haskellは多相型の推測に問題がある
-xnor

1
@zbwこれは事実だと思ったが、使用NoMonomorphismRestrictionしても助けにはならなかった。NORましたRank2TypesRankNTypes。何が起こっているか知っていますか?
xnor



4

JavaScriptのES6、55 54 51 46バイト

@Neilのおかげで1バイト節約

@Arnauldのおかげで2バイト節約

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

オンラインでお試しください!

これは、配列の配列として出力します。JavaScriptの範囲はかなり扱いにくいですが[...Array(n)]、サイズの配列を生成するために使用しますn


インデックスパラメータを使用する方が1バイト短くなりますn=>[...Array(n)].map((_,i,a)=>a.map((_,j)=>(i+j+1)%2))
ニール

@Neilハァッ、マップで3番目のパラメーターを使用することを考えたことがありません、ありがとう!
ダウンゴート

@Arnauldありがとう!それで、さらに5バイト節約できるようになりました!
ダウンゴート

4

網膜33 30バイト

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

オンラインでお試しください!説明:最初の段階では1s を使用して入力を単項に変換し(便利です!)、2番目の段階では値を正方形に変換します。3番目のステージは各行の交互ビットを反転し、最後のステージは交互の行のビットを反転します。編集:@MartinEnderのおかげで3バイトを保存しました。


$`1$'ただ$_です。
マーティンエンダー

@MartinEnderああ、私はなじみがありません$_、ありがとう!
ニール

3

MATL、7バイト

:t!+2\~

オンラインでお試しください!

説明:

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

注:チャレンジを投稿した、MATLでこれを解決し始めました。


同等で短い::&+o~
ルイスメンドー

1
まだ学んでいます:-)明日更新します。私はあなたの他のアプローチも好きでした:
Stewie Griffin

1
これも私が思いついたものです。また、純粋な MATL命令セットのみを使用し、Y@ LuisMendoが使用する厄介な変更された命令は使用しません。
-Sanchises

@Sanchises Pesky、ハァッ?:-P
ルイスメンドー

3

Brachylog、15バイト

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

オンラインでお試しください!

説明

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

3

Clojure、36バイト

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

はい、仕事に最適なツールです。


3

05AB1E9 7バイト

Emignaのおかげで-2バイト

LDÈD_‚è

オンラインでお試しください!

説明

LDÈD_‚sè» Argument n
LD        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

あなたはカットすることができます»ように、リスト・オブ・リスト出力は大丈夫です、あなたも削除することができますs
エミグナ

@Emignaうん、ありがとう!
カルソウェラス

説明は少し無関係です。
エリックアウトゴルファー

3

Java(OpenJDK 8)80 77バイト

Kevin Cruijssenのおかげで-3バイト

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

オンラインでお試しください!

ああ、多くの楽しい演算子を備えた、半合理的な長さのJava回答です。

intを取り、Stringを返すラムダ。/と%を使用して行番号と列番号を使用し、どの値を使用するかを決定します(mod 2)。

ゴルフをしていない:

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

スペースを削除してバイトを節約できます。課題は、出力形式が柔軟であることを示しています。ああ、そしてに変更(i++/j+i%j)%2するi++/j+i%j&1ことでさらに2バイト節約できるので、それらの括弧は必要ありません。これにより、合計1バイトがネストされたforループソリューション(n->{String r="";for(int i=0,j;i++<n;r+="\n")for(j=0;j<n;r+=j+++i&1);return r;})よりも短くなるため、+ 1します。:)
ケビンクルーッセン

@KevinCruijssenええ、私はまだスペースでの応答を待っていました。%および&1 ==%2よりも優先順位が高いことを考えていませんでした
-PunPun1000

2

炭、8バイト

UON10¶01

オンラインでお試しください!説明:これは、大まかに次の冗長コードに変換されます(残念ながら、デバーボシファイアーは現在不要なセパレーターを追加しています):

Oblong(InputNumber(), "10\n01");





2

R38 37バイト

n=scan();(matrix(1:n,n,n,T)+1:n-1)%%2

オンラインでお試しください!

ジュゼッペのおかげで-1バイト

Rのリサイクルルールを利用します。最初にマトリックスを作成するとき、2番目にそのマトリックスに0:(n-1)を追加するときに。


あなたはを取り除くことでバイトをドロップすることができt、代わりに行列を構築するbyrow=T、すなわち、(matrix(1:n,n,n,T)+1:n-1)%%2
ジュゼッペ

1
outer(1:n,1:n-1,"+")%%2かなり短いバイトです:)
JAD

2

Swi-Prolog、142バイト。

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

オンラインで試す-http://swish.swi-prolog.org/p/BuabBPrw.pl

ネストされたリストを出力するため、ルールには次のように記載されています。

  • t() トグルであり、0-> 1および1-> 0になります。
  • r() 個々の行で成功します。これは、1と0のみが交互になっている行を再帰的にチェックダウンすることです。
  • f() すべての行を再帰的にチェックします。正しい長さであること、有効な行であること、 r() and that each row starts with a differing 0/1.
  • c(N,C) 行(ネストされたリスト)の数がNで、ヘルパーfが成功した場合、CはサイズNの有効なチェッカーボードであると言います。

テストケース: enter image description here


2

C、69 67 63バイト

Thanks to @Kevin Cruijssen for saving two bytes and @ceilingcat for saving four bytes!

i,j;f(n){for(i=n;i--;puts(""))for(j=n;j;)printf("%d",j--+i&1);}

Try it online!


printf("%d "出力の別の有効な方法であるため、のスペースを削除できます。
コナーオブライエン

@ ConorO'Brienええ、ありがとう。
Steadybox

を変更(j+++i)%2j+++i&1てこれらの括弧を削除すると、2バイトを節約できます。
ケビンCruijssen

@ceilingcatありがとう!
Steadybox

1

QBIC、19バイト

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

説明

[:|         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.






1

///, 87 bytes + input

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

Try it online! (input for 4)

Unary input in 1s, 95 bytes + input

/V/\\\///D/VV//&1/k#&D&|D/#k/k#D&k/k&DVk/k\D/SD/#/r
DSkk/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 and D 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 the ks to the /r/S/ block

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

  • #s are then turned into r\ns

  • The string of ks is turned into an alternating 1010... string

  • The r\ns are turned into 1010...\ns

  • Every pair of 1010...\n1010\n is turned into 1010...\01010...;\n

  • Either 0; or 1; are trimmed off (because the 01010... string is too long by 1)


1

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.

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.