用总和填充矩阵


23

挑战:

给定一个方形输入矩阵A,在矩阵的所有四个边上分别填充一行和一列。

  • 顶行和底行中每个元素的值应为每个对应列中元素的总和。
  • 左右列中每个元素的值应为每个对应行中元素的总和。
  • 左上角和右下角的元素值应为对角线上的元素之和
  • 右上角和左下角的元素值应为反对角线中元素的总和。

例:

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的总和。

顶部和底部的行(除了角部)的每一列的总和在1 + 3 + 2 = 65 + 2 + 5 = 123 + 4 + 5 = 12。类似地,左和右列(除了角部)各自的行的总和1 + 5 + 3 = 93 + 2 + 4 = 92 + 5 + 5 = 12

输入:

  • 具有非负整数的非空方阵。
  • 可选格式

输出:

  • 如上所述填充的矩阵
  • 可选格式,但必须与输入格式相同

测试用例:

如果您想将输入格式转换为更适合的格式(例如),请使用此挑战中的提交[[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

Answers:


5

八度,64字节

感谢Tom Carpenter节省了4个字节,更正了我在原始代码中遇到的错误!

@(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不同,用于处理矩阵。> _>
暴民埃里克(Erik the Outgolfer)'17年

@EriktheOutgolfer但是您的答案有更多欧元!
路易斯·门多

3
是的,它有欧元和日元……不幸的是,这不是赢家的标准。D:
暴民埃里克(Erik the Outgolfer)'17年

3

APL(Dyalog),37字节

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

在线尝试!

1 1∘⍉ 对角线(将两个轴合拢为一个)

d← 将该函数存储为d并将其应用于参数

+⌿ 在列总和之前

d∘⌽, 前置d应用于反向参数

()⍪ 将以下内容堆叠在顶部:

+/,⊢,+/ 行和,未修改的参数,行和

()⍪ 将以下内容堆叠在顶部:

d,+⌿,d∘⌽ 应用于参数,列求和,d应用于反向参数


3

果冻,26个字节

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

在线尝试!

看起来与Erik的解决方案惊人地不同。

我终于设法了解了它的¦工作原理(通过Jelly的代码进行调试,哈哈)。太糟糕了Ç在我的情况下需要使用。

说明

该代码使用三个链接。第一个辅助链接在其两端填充一个向量,第二个辅助链接固定矩阵的两个角,主链接适当地调用它们。

Ç€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个字节

这是@LeakyNun的建议,它节省了54个字节。然后我自己打了一下。

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
Xcoder先生17年

2

Python 2中268个 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好吧,我刚刚更新了代码:)
mdahmoune

1
我相信这个工程174 tio.run/...
Stewie新

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.tracenp.sum分别用于计算对角线和其他所有位置的和。T用于在将总和串联之前和之后进行转置,因为它比使所有数组二维化并使用短np.r_m[::-1]与第二条对角线进行比较rot90(m)fliplr(m)查找第二条对角线的轨迹时,可以节省字节。


好答案!欢迎来到该网站:)
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

LOGO,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是辅助功能。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.