和で行列を埋める


23

チャレンジ:

正方形の入力行列Aが与えられた場合、4辺すべてに1行1列の行列を埋め込みます。

  • 上下の行の各要素の値は、対応する各列の要素の合計である必要があります。
  • 左右の列の各要素の値は、対応する各行の要素の合計である必要があります。
  • 左上の要素と右下の要素の値は、対角線上の要素の合計である必要があります
  • 右上隅と左下隅の要素の値は、対角線の要素の合計である必要があります。

例:

A = 
1   5   3
3   2   4
2   5   5

Output:
 8    6   12   12    7
 9    1    5    3    9
 9    3    2    4    9
12    2    5    5   12
 7    6   12   12    8

説明:

左上の要素と右下の要素は、対角線1 + 2 + 5 = 8の合計です。右上と左下の要素は、反対角2 + 2 + 3 = 7の合計です。

(隅を除く)上部と下部の行はの列のそれぞれの和であるA+ 3 1 + 2 = 65 + 2 + 5 = 123 + 4 + 5 = 12。同様に、(隅を除く)は、左と右の列は、列のそれぞれの和であるAは1 + 5 + = 9 3+ 2 + 4 = 9 3及び+ 5 + 5 = 12 2

入力:

  • 負でない整数を持つ空でない正方行列。
  • オプションの形式

出力:

  • 上で説明したようにパディングされたマトリックス
  • オプションの形式ですが、入力形式と同じである必要があります

テストケース:

入力形式をより適切な形式(たとえば)に変換する場合は、このチャレンジで提出物を使用します[[1, 5],[0, 2]]

0
----------------
0 0 0
0 0 0
0 0 0

1 5
0 2
----------------
3 1 7 5
6 1 5 6
2 0 2 2
5 1 7 3

17   24    1    8   15
23    5    7   14   16
 4    6   13   20   22
10   12   19   21    3
11   18   25    2    9 
----------------
65   65   65   65   65   65   65
65   17   24    1    8   15   65
65   23    5    7   14   16   65
65    4    6   13   20   22   65
65   10   12   19   21    3   65
65   11   18   25    2    9   65
65   65   65   65   65   65   65

15    1    2   12
 4   10    9    7
 8    6    5   11
 3   13   14    0
----------------
30   30   30   30   30   30
30   15    1    2   12   30
30    4   10    9    7   30
30    8    6    5   11   30
30    3   13   14    0   30
30   30   30   30   30   30

これはであるため、各言語で最も短いソリューション優先されます。説明を強くお勧めします。


2
魔方陣をチェックするのですか?
mdahmoune

確認するのはかなり簡単ですが、正方形がこのように魔法であるかどうかを確認するのは確かに簡単です、はい:
Stewie Griffin

回答:


5

オクターブ、64バイト

4バイトの節約、元のコードにあったエラーを修正してくれたTom Carpenterに感謝します!

@(a)[b=(t=@trace)(a),c=sum(a),d=t(flip(a));z=sum(a,2),a,z;d,c,b]

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

説明:

@(a)                 % Anonymous function that takes the matrix 'a' as input
 [ ... ]             % Concatenate everything inside to a single matrix
  b=(t=@trace)(a),   % Clever trick by Tom Carpenter. Save a function handle 
                     % for 't=trace', and call it with 'a' as input
                     % Save the result in the variable 'b'
  c=sum(a)           % Sum of all columns of 'a'
  d=t(flip(a));      % Save the trace of 'a' flipped as a variable 'd', while 
                     % concatenating [b,c,d] horizontally at the same time, creating the 
                     % first row of the output
  z=sum(a,2)         % The sum of each row of the input, and store it in a variable 'z'
  ,a,z;              % Concatenate it with 'a' and 'z' again, to create the middle part of the output
 d,c,b]              % Add [d,c,b] to complete the bottom row

注、チャレンジを投稿してからずっと経ちました。



4

MATL27 26バイト

,!tXswyv]GXds5L(PGPXds5L(P

オンラインでお試しください!または、すべてのテストケースを確認します

説明

,        % Do the following twice
  !      %   Tranpose. Takes input implititly in the first iteration
  t      %   Duplicate
  Xs     %   Row vector with the sum of each column
  wy     %   Push a copy to the bottom of the stack
  v      %   Concatenate stack vertically. This attaches the sum of
         %   each row (first iteration) and column (second), leaving 
         %   the matrix with the correct orientation (transposed twice)
]        % End
G        % Push input again
Xds      % Column vector with the diagonal of the matrix. Sum of vector
5L(      % Write that into first and last entries of the result matrix
         % matrix; that is, its upper-left and lower-right corners
P        % Flip result matrix vertically
GP       % Push input matrix vertically flipped
Xds      % Diagonal, sum. Since the input has been vertically flipped,
         % this gives the sum of the anti-diagonal of the input.
5L(      % Write that into the upper-left and lower-right corners of
         % the verticallly flipped version of the result matrix
P        % Flip vertically again, to restore initial orientation
         % Implicitly display

もちろん、MATLはJellyとは異なり、マトリックスで動作するように設計されています。> _>
エリック・ザ・アウトゴルファー

@EriktheOutgolferしかしあなたの答えにはもっとユーロがあります!
ルイスメンドー

3
ええ、それはユーロドルと円を持っています...残念ながら、それはここでの勝利基準ではありません。D:
エリックアウトゴルファー

3

APL(Dyalog)、37バイト

(d,+⌿,d∘⌽)⍪(+/,⊢,+/)⍪d∘⌽,+⌿,d←+/1 1∘⍉

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

1 1∘⍉ 対角線(点灯。両方の軸を1つに折りたたみます)

d← その関数をdとして保存し、引数に適用します

+⌿ 列の合計を追加する

d∘⌽,逆引きされた引数に プリペンドdを適用

()⍪ 上に次のものを積み重ねます。

+/,⊢,+/ 行の合計、変更されていない引数、行の合計

()⍪ 上に次のものを積み重ねます。

d,+⌿,d∘⌽ 引数に適用、列の合計、逆引数に適用d


3

ゼリー、26バイト

ŒDµḊṖѵ€1¦ŒḌU
S;;S
Ç€Zµ⁺ÑÑ

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

意外と違って見える エリックのソリューションます

私はついに¦(Jellyのコードを使ってデバッグすることで)仕組みを理解することができました(笑)残念なことにÇ、私の場合は作業です。

説明

コードは3つのリンクを使用します。最初のヘルパーリンクはベクトルの両端にその和を埋め込み、2番目のヘルパーリンクはマトリックスの2つの角を修正し、メインリンクはこれらを適切に呼び出します。

Ç€Zµ⁺ÑÑ    Main link. Argument: M (matrix)
Ç            Call the first helper link (pad row with sums)...
 €           ...on each row of the matrix.
  Z          Transpose, so that the second invocation uses the columns.
   µ         Begin a new monadic chain.
    ⁺        Repeat the previous chain (everything up to here).
     ÑÑ      Call the second helper link twice on the whole matrix.

S;;S    First helper link. Argument: v (1-dimensional list)
S         Sum the argument list.
 ;        Append the argument list to the sum.
  ;       Append...
   S      ...the sum of the argument list.

ŒDµḊṖѵ€1¦ŒḌU    Second helper link. Argument: M (matrix)
ŒD                 Get the diagonals of the matrix, starting with the main diagonal.
  µ                Begin a new monadic chain.
      µ€           Perform the following actions on each diagonal...
        1¦         ...and keep the result for the first item (main diagonal):
   Ḋ                 Remove the first item (incorrect top corner).
    Ṗ                Remove the last item (incorrect bottom corner).
     Ñ               Call the first helper link on the diagonal to pad it with its sum.
          ŒḌ       Convert the diagonals back to the matrix.
            U      Reverse each row, so that consecutive calls fix the other corners.

3

Python 3、155バイト

これは、54バイトを節約する@LeakyNunの提案です。それから自分で少しゴルフをしました。

def f(m):l=len(m);r=range(l);s=sum;b=[s(m[i][i]for i in r)];c=[s(m[i][l+~i]for i in r)];d=[*map(s,zip(*m))];return[b+d+c,*[[s(a),*a,s(a)]for a in m],c+d+b]

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

初期解- Pythonの3、216のバイト

def f(m):l=len(m);r,s=range(l),sum;a,b,c,d=s(m[i][i]for i in r),s(m[i][l-i-1]for i in r),[s(m[i][j]for j in r)for i in r],[s(m[i][j]for i in r)for j in r];print([[a]+d+[b]]+[[c[i]]+m[i]+[c[i]]for i in r]+[[b]+d+[a]])

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



@LeakyNunありがとう。〜190バイトで更新していましたが、これははるかに短いです:P
Mr. Xcoder

2

パイソン2268 250 184 174バイト

10 Stewie Griffinに感謝

from numpy import *
a,c,v,s=sum,trace,vstack,matrix(input())
l,r,d,e=a(s,0),a(s,1),c(s),c(fliplr(s))
print hstack((v(([[d]],r,[[e]])),v((l,s,l)),v(([[e]],r,[[d]])))).tolist()

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

いくつかの説明 入力はマトリックスとしてアップロードされます。最初に、コードはnumpy.sumを使用して各列と各行の合計を計算します。次に、numpy.traceによって対角線の合計を計算します。この後、マトリックスを左右に反転させることにより、もう一方の対角線を取得します。最後に、numpy.vstackとnumpy.hstackを使用してピースを接着します。


@StewieGriffin OK、コードを更新しました:)
mdahmoune

1
これは174 tio.run/で
Stewie Griffin

2

R、129バイト

pryr::f(t(matrix(c(d<-sum(diag(m)),c<-colSums(m),a<-sum(diag(m[(n<-nrow(m)):1,])),t(matrix(c(r<-rowSums(m),m,r),n)),a,c,d),n+2)))

入力として正方行列を取る匿名関数。興味があれば説明を掲載します。


2

PHP、211バイト

<?foreach($_GET as$l=>$r){$y=0;foreach($r as$k=>$c){$y+=$c;$x[$k]+=$c;$l-$k?:$d+=$c;($z=count($_GET))-1-$k-$l?:$h+=$c;}$o[]=[-1=>$y]+$r+[$z=>$y];}$o[]=[-1=>$h]+$x+[$z=>$d];print_r([-1=>[-1=>$d]+$x+[$z=>$h]]+$o);

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

拡大

foreach($_GET as$l=>$r){
  $y=0; # sum for a row
  foreach($r as$k=>$c){
    $y+=$c; # add to sum for a row
    $x[$k]+=$c; # add to sum for a column and store in array
    $l-$k?:$d+=$c; # make the diagonal sum left to right
    ($z=count($_GET))-1-$k-$l?:$h+=$c; # make the diagonal sum right to left
  }
  $o[]=[-1=>$y]+$r+[$z=>$y]; # add to result array the actual row with sum of both sides
}
$o[]=[-1=>$h]+$x+[$z=>$d]; # add to result array the last array
print_r([-1=>[-1=>$d]+$x+[$z=>$h]]+$o); #output after adding the first array to the result array

2

Python 3、125バイト

from numpy import*
f=lambda m,t=trace,s=sum:c_[r_[t(m),s(m,1),t(m[::-1])],c_[s(m,0),m.T,s(m,0)].T,r_[t(m[::-1]),s(m,1),t(m)]]

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

わずかに未使用:

import numpy as np

def f_expanded(m):
    return np.c_[np.r_[np.trace(m), np.sum(m, 1), np.trace(m[::-1])],
                 np.c_[np.sum(m, 0), m.T, np.sum(m, 0)].T,
                 np.r_[np.trace(m[::-1]), np.sum(m, 1), np.trace(m)]]

これは、numpy配列としてフォーマットされた入力を受け取りnp.c_np.r_インデックス作成ツールとインデックス作成ツールを使用して、新しい配列を一度に構築します。np.traceおよびnp.sumは、それぞれ対角線およびその他の場所で合計を計算するために使用されます。Tは、すべての配列を2次元にしてを使用するよりも短いため、合計を連結する前後に転置を行うために使用されますnp.r_。2番目の対角線m[::-1]と比較しrot90(m)たりfliplr(m)、2番目の対角線のトレースを見つけるためにバイトを節約します。


いい答えだ!サイトへようこそ:)
DJMcMayhem

1

JavaScript(ES6)、170バイト

(a,m=g=>a.map((_,i)=>g(i)),s=x=>eval(x.join`+`))=>[[d=s(m(i=>a[i][i])),...c=m(i=>s(m(j=>a[j][i]))),g=s(m(i=>a[i][a.length-i-1]))],...a.map(b=>[r=s(b),...b,r]),[g,...c,d]]

入力と出力は、数値の2D配列です。

説明した

(a,                             // input matrix: a
    m=g=>a.map((_,i)=>g(i)),    // helper func m: map by index
    s=x=>eval(x.join`+`)        // helper func s: array sum
) =>
[
    [
        d = s(m(i=>a[i][i])),           // diagonal sum: d
        ...c=m(i=>s(m(j=>a[j][i]))),    // column sums: c
        g = s(m(i=>a[i][a.length-i-1])) // antidiagonal sum: g
    ],
    ...a.map(b=>[r = s(b), ...b, r]),   // all rows with row sums on each end
    [g, ...c, d]                        // same as top row, with corners flipped
]

テストスニペット

入力/出力は、改行とタブでフォーマットされています。

f=
(a,m=g=>a.map((_,i)=>g(i)),s=x=>eval(x.join`+`))=>[[d=s(m(i=>a[i][i])),...c=m(i=>s(m(j=>a[j][i]))),g=s(m(i=>a[i][a.length-i-1]))],...a.map(b=>[r=s(b),...b,r]),[g,...c,d]]

let tests=[[[0]],[[1,5],[0,2]],[[17,24,1,8,15],[23,5,7,14,16],[4,6,13,20,22],[10,12,19,21,3],[11,18,25,2,9]],[[15,1,2,12],[4,10,9,7],[8,6,5,11],[3,13,14,0]]];
<select id=S oninput="I.value=S.selectedIndex?tests[S.value-1].map(s=>s.join`\t`).join`\n`:''"><option>Tests<option>1<option>2<option>3<option>4</select> <button onclick="O.innerHTML=I.value.trim()?f(I.value.split`\n`.map(s=>s.trim().split(/\s+/g))).map(s=>s.join`\t`).join`\n`:''">Run</button><br><textarea rows=6 cols=50 id=I></textarea><pre id=O>


0

ロゴ、198バイト

to g :v[:h reduce "+ :v]
op(se :h :v :h)
end
to f :s[:a reduce "+ map[item # ?]:s][:b reduce "+ map[item # reverse ?]:s][:c apply "map se "sum :s]
op `[[,:a ,@:c ,:b],@[map "g :s][,:b ,@:c ,:a]]
end

この関数fは、マトリックスを2Dリストとして受け取り、結果のマトリックスを出力します。gヘルパー関数です。

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