# 每个维度的总和

20

• ķ = j的如果j <= N
• 如果j i = n i +1 则0 <k i <= n i

``````[[1 2 3]
[4 5 6]]
``````

``````[[1 2 3 6]
[4 5 6 15]
[5 7 9 21]]
``````

## 测试用例

``````Input:
[5 2 3]
Output:
[5 2 3 10]

Input:
[[1 2 3] [4 5 6]]
Outputs:
[[1 2 3 6] [4 5 6 15] [5 7 9 21]]

Input:
[[[1] [1] [1] [0]]]
Output:
[[[1 1] [1 1] [1 1] [0 0] [3 3]] [[1 1] [1 1] [1 1] [0 0] [3 3]]]

Input:
[[[[-1]]]]
Output:
[[[[-1 -1] [-1 -1]] [[-1 -1] [-1 -1]]] [[[-1 -1] [-1 -1]] [[-1 -1] [-1 -1]]]]
``````

@Dennis您应该发布它。
jimmy23013 2015年

9

# J，14个字节

``````#@\$(0|:],+/^:)
``````

``````   ]a=.i.2 3
0 1 2
3 4 5

(#@\$(0|:],+/^:)) a    NB. parens are optional
0 1 2  3
3 4 5 12
3 5 7 15
``````

• `^:(#@\$)`重复尺寸`^:`数量：`#``\$`

• `],+/``,`将参数`]`与最后一个维度的和连接在一起`+/`
• `0|:``|:`通过将第一个放在`0`尺寸列表的末尾来旋转尺寸
• 完成上述步骤后，我们将获得原始输入以及所有维度上的总和。

15

# Mathematica，32个 20字节

``````#/.List->({##,+##}&)&
``````

### 例：

``````In[1]:= #/.List->({##,+##}&)&[{{1, 2, 3}, {4, 5, 6}}]

Out[1]= {{1, 2, 3, 6}, {4, 5, 6, 15}, {5, 7, 9, 21}}
``````

10

## Python 2，95个字节

``````from numpy import*
a=copy(input())
for d in r_[:a.ndim]:a=r_[`d`,a,sum(a,d,keepdims=1)]
print a``````

``````\$ python sum.py
[[1, 2, 3], [4, 5, 6]]
[[ 1  2  3  6]
[ 4  5  6 15]
[ 5  7  9 21]]
``````

7

# APL，16 15字节

``````{×≡⍵:∇¨⍵,+/⍵⋄⍵}
``````

### 理念

1. 对数组的最大维度求和。

2. 对每个子数组重复步骤1。

### 码

``````{             } ⍝ Define a monadic function with argument ⍵ and reference ∇.
×≡⍵:           ⍝ If the depth of ⍵ is positive:
∇          ⍝   Apply this function...
¨         ⍝   to each element of...
⍵,       ⍝   the concatenation of ⍵...
+/⍵    ⍝   and the sum across ⍵.
⋄⍵  ⍝  Else, return ⍵.
``````

jimmy23013

2
@ user23013：所以我的代码确实起作用了！您必须喜欢一种编程语言，在该语言中，输入格式比实际代码更难正确……
Dennis

6

# 点，18 15字节

``````{a-a?fMaAE\$+aa}
``````

``````C:\> pip.py -pe "( {a-a?fMaAE\$+aa} [[1 2 3] [4 5 6]] )"
[[1;2;3;6];[4;5;6;15];[5;7;9;21]]
``````

``````{             }  Define a lambda function with parameter a
a-a?            Shortest way I could find to test whether the argument is a list
or scalar: subtracting a number from itself gives 0 (falsy);
subtracting a list from itself gives a list of zeros (truthy!)
fM          If truthy, it's a list, so map the same function (f) recursively to:
aAE         Argument, with appended element...
\$+a      ...sum of argument (fold on +)
a   If falsy, it's a scalar, so just return it
``````

``````{Ja=a?a(fMaAE\$+a)}
``````

1. 在标量或列表测试中保存了一个字节-先前的方法是连接参数（在空字符串上）并测试是否等于其未连接的self（因为起作用`[1 2 3] != 123`）；
2. 消除了括号。它们在原始文件中是必需的，因为`M`它的优先级低于`?`（尽管我可能要更改它的优先级，尤其是现在）：没有它们，代码将被解析为`(Ja=a?af)M(aAE\$+a)`，从而导致奇怪的错误消息。但是，三元运算符的中间参数可以是任何优先级的任何表达式，不需要括号。因此，通过使列表成为真实情况，我可以保存这两个字节。

2

@丹尼斯谢谢！这项工作仍在进行中，但可以完成一些任务。
DLosc

5

# APL（25）

``````{N⊣{N,[⍵]←+/[⍵]N}¨⍳⍴⍴N←⍵}
``````

APL的数组具有内置维，因此此函数采用n维数组，然后沿每个维求和。

``````      {N⊣{N,[⍵]←+/[⍵]N}¨⍳⍴⍴N←⍵} ↑(1 2 3)(4 5 6)
1 2 3  6
4 5 6 15
5 7 9 21
``````

• `N←⍵`：将数组存储在中`N`
• `⍴⍴N`：获取尺寸的数量`N`。（`⍴`给出尺寸，即`⍴↑(1 2 3)(4 5 6)`给出`2 3`，因此`⍴⍴`给出尺寸。）
• `{`... `}¨⍳`：从1到`⍴⍴N`：的 每个数字
• `+/[⍵]N``N`沿维度求和`⍵`
• `N,[⍵]←`：将结果加入该`N`维度
• `N`：最后，返回`N`

3
@Dennis：您需要向函数传递多维数组。的`↑(1 2 3)(4 5 6)`作用是简单地使用从2个1维数组构造2维数组`↑`。它不是内置符号，也没有概括您的思维方式。构造第三个和第四个数组的规范方法是`1 4 1⍴1 1 1 0``1 1 1 1⍴¯1`，但是也可以在不参考大小的情况下构造它们，例如，第三个数组也可以用构建`↑⍉⍪(,1)(,1)(,1)(,0)`，第四个数组可以用构建`↑⍪⊂⍪¯1`
marinus

2
@丹尼斯高尔夫：`{×≡⍵:∇¨⍵,+/⍵⋄⍵}((1 2)(3 4))((5 6)(7 8))`。固定：`{×⍴⍴⍵:∇↓⍵,+/⍵⋄⍵}1 4 1⍴1 1 1 0`。现在比Mathematica还短...
jimmy23013

3

# CJam，36个字节

``````{_`{'[<}#:D{_":"D'.e]'++~a+{S}%}&}:S
``````

### 理念

``````[1 2] :+ e# Pushes 3.
``````

``````[[1 2][3 4]] :.+ Pushes [4 6].
``````

``````[[[1 2][3 4]][[5 6][7 8]]] :..+ e# Pushes [[[6 8] [10 12]]].
``````

### 码

``````{                                }:S e# Define S:
_`                                  e#   Push a string representation of a the array.
{'[<}#                            e#   Find the index of the first non-bracket.
:D                          e#   Save it in D.
{                   }&    e#   If D is positive:
_                        e#     Push a copy of the array.
":"D'.e]                e#     Pad ":" with "."s to a string of length D.
'++~            e#     Add a "+" to the string and evaluate.
a+          e#     Wrap the result in a array and concatenate.
{S}%      e#     Apply S to the elements of the array.
``````

2

## 红宝石（181个139 119个 108字节）

``````def d a;a.push a[0].to_s['[']?a.map{|x|d x}.transpose.map{|x|x.reduce:+}:a.reduce(:+)end
``````

jimmy23013

2

# Java，669字节

``````import java.lang.reflect.Array;enum S{D;<A>A s(A a){int l=Array.getLength(a),x=0;Class t=a.getClass();Class c=t.getComponentType();A r=(A)Array.newInstance(c,l+1);System.arraycopy(a,0,r,0,l);if(t==int[].class)for(;x<l;)((int[])r)[l]=((int[])r)[l]+((int[])r)[x++];else{for(;x<l;)Array.set(r,x,S.this.s(Array.get(r,x++)));Object o=Array.get(r,0);for(;--x>0;)o=s(o,Array.get(r,x));Array.set(r,l,o);}return r;}<A>A s(A a,A b){int l=Array.getLength(a),x=0;Class t=a.getClass();A r=(A)Array.newInstance(t.getComponentType(),l);if(int[].class==t)for(;x<l;)((int[])r)[x]=((int[])a)[x]+((int[])b)[x++];else for(;x<l;)Array.set(r,x,s(Array.get(a,x),Array.get(b,x++)));return r;}}
``````

``````import java.lang.reflect.Array;
import java.util.Arrays;

public enum SumOf{
Dimensions;

<A>A sum(A array){ //call this method to solve the challenge
int length=Array.getLength(array),x=0;
Class arrayType=array.getClass();
Class componentType=arrayType.getComponentType();
//grow the array to include the sum element
A result=(A)Array.newInstance(componentType,length+1);
System.arraycopy(array,0,result,0,length);
if(arrayType==int[].class) //one-dimensional array needs to be handled separately
for(;x<length;) //find the sum
((int[])result)[length]=((int[])result)[length]+((int[])result)[x++];
else{ //multi-dimensional array
for(;x<length;) //find the sum for each element in this dimension's array
Array.set(result,x,sum(Array.get(result,x++)));
//find the total sum for this dimension's array
Object s=Array.get(result,0);
for(;--x>0;)
s=_sum(s,Array.get(result,x)); //add the 2 elements together
Array.set(result,length,s);
}
return result;
}

<A>A _sum(A arrayA,A arrayB){ //this method is used by the previous method
int length=Array.getLength(arrayA),x=0;
Class arrayType=arrayA.getClass();
A result=(A)Array.newInstance(arrayType.getComponentType(),length);
if(int[].class==arrayType) //one-dimensional array needs to be handled separately
for(;x<length;) //find the sum of both arrays
((int[])result)[x]=((int[])arrayA)[x]+((int[])arrayB)[x++];
else
for(;x<length;) //find the sum of both arrays
Array.set(result,x,sum(Array.get(arrayA,x),Array.get(arrayB,x++)));
return result;
}

static int[] intArray( int firstElement, int...array ) {
if( array == null ) array = new int[0];
array = Arrays.copyOf( array, array.length + 1 );
System.arraycopy( array, 0, array, 1, array.length - 1 );
array[0] = firstElement;
return array;
}

static <E> E[] arrayArray( E firstElement, E...array ) {
if( array == null ) array = (E[]) Array.newInstance( firstElement.getClass(), 0 );
array = Arrays.copyOf( array, array.length + 1 );
System.arraycopy( array, 0, array, 1, array.length - 1 );
array[0] = firstElement;
return array;
}

static void printIntArray( int[]array ){
System.out.print("[ ");
for( int x = 0; x < array.length; x++ )
System.out.print( array[x] + " " );
System.out.print("] ");
}

static < A > void printArray( A array ) {
if( array.getClass() == int[].class ){
printIntArray( (int[]) array );
}
else {
System.out.print("[ ");
int length = Array.getLength( array );
for( int x = 0; x < length; x++ )
printArray( Array.get( array, x ) );
System.out.print("] ");
}
}

public static void main(String[]s){
int[] test01 = intArray( 5, 2, 3 );
System.out.print("Input: ");
printArray( test01 );
System.out.print("\nOutput: ");
printArray( SumOf.Dimensions.sum( test01 ) );
System.out.println();

int[][] test02 = arrayArray( intArray( 1, 2, 3 ), intArray( 4, 5, 6 ) );
System.out.print("\nInput: ");
printArray( test02 );
System.out.print("\nOutput: ");
printArray( SumOf.Dimensions.sum( test02 ) );
System.out.println();

int[][][] test03 = arrayArray( arrayArray( intArray( 1 ), intArray( 1 ), intArray( 1 ), intArray( 0 ) ) );
System.out.print("\nInput: ");
printArray( test03 );
System.out.print("\nOutput: ");
printArray( SumOf.Dimensions.sum( test03 ) );
System.out.println();

int[][][][] test04 = arrayArray( arrayArray( arrayArray( intArray( -1 ) ) ) );
System.out.print("\nInput: ");
printArray( test04 );
System.out.print("\nOutput: ");
printArray( SumOf.Dimensions.sum( test04 ) );
System.out.println();

int[][][] test05 = arrayArray( arrayArray( intArray( 1, 2, 3 ), intArray( 4, 5, 6 ), intArray( 7, 8, 9 ) ), arrayArray( intArray( 11, 12, 13 ), intArray( 14, 15, 16 ), intArray( 17, 18, 19 ) ), arrayArray( intArray( 21, 22, 23 ), intArray( 24, 25, 26 ), intArray( 27, 28, 29 ) ) );
System.out.print("\nInput: ");
printArray( test05 );
System.out.print("\nOutput: ");
printArray( SumOf.Dimensions.sum( test05 ) );
System.out.println();
}

}
``````

``````Input: [ 5 2 3 ]
Output: [ 5 2 3 10 ]

Input: [ [ 1 2 3 ] [ 4 5 6 ] ]
Output: [ [ 1 2 3 6 ] [ 4 5 6 15 ] [ 5 7 9 21 ] ]

Input: [ [ [ 1 ] [ 1 ] [ 1 ] [ 0 ] ] ]
Output: [ [ [ 1 1 ] [ 1 1 ] [ 1 1 ] [ 0 0 ] [ 3 3 ] ] [ [ 1 1 ] [ 1 1 ] [ 1 1 ] [ 0 0 ] [ 3 3 ] ] ]

Input: [ [ [ [ -1 ] ] ] ]
Output: [ [ [ [ -1 -1 ] [ -1 -1 ] ] [ [ -1 -1 ] [ -1 -1 ] ] ] [ [ [ -1 -1 ] [ -1 -1 ] ] [ [ -1 -1 ] [ -1 -1 ] ] ] ]

Input: [ [ [ 1 2 3 ] [ 4 5 6 ] [ 7 8 9 ] ] [ [ 11 12 13 ] [ 14 15 16 ] [ 17 18 19 ] ] [ [ 21 22 23 ] [ 24 25 26 ] [ 27 28 29 ] ] ]
Output: [ [ [ 1 2 3 6 ] [ 4 5 6 15 ] [ 7 8 9 24 ] [ 12 15 18 45 ] ] [ [ 11 12 13 36 ] [ 14 15 16 45 ] [ 17 18 19 54 ] [ 42 45 48 135 ] ] [ [ 21 22 23 66 ] [ 24 25 26 75 ] [ 27 28 29 84 ] [ 72 75 78 225 ] ] [ [ 33 36 39 108 ] [ 42 45 48 135 ] [ 51 54 57 162 ] [ 126 135 144 405 ] ] ]
``````