自己添加一个数组


22

今天的挑战是获取一个数组,将其拆分为多个块,然后添加这些块。

这是这样的:程序或函数将被赋予一个整数数组a和一个块大小L。数组应拆分为size个数组L,如果不能将数组长度整除,L则该数组后面应附加0,这样就可以将其整除。数组分块后,所有分块将逐个元素地添加在一起。然后输出结果数组。

您可以假定L大于0,这a是非空的。您不能假设a的内容为正。

这是一个例子:

[1,2,3,4,5,6,7,8], 3 => [1,2,3]+[4,5,6]+[7,8,0] =>  [1+4+7,2+5+8,3+6+0] => [12,15,9]

测试用例:

Array                           Length   Output
[1]                             1        [1]
[1]                             3        [1,0,0]
[0]                             3        [0,0,0]
[1,2]                           3        [1,2,0]
[1,2]                           1        [3]
[-1,1]                          2        [-1,1]
[-7,4,-12,1,5,-3,12,0,14,-2]    4        [12,-1,0,1]
[1,2,3,4,5,6,7,8,9]             3        [12,15,18]

这是,最少字节获胜!


不是骗人吗
sergiol

1
@sergiol如果您可以找到一个重复的问题,我将自己删除此帖子。但是,据我所知这不是骗子。
帕维尔

Answers:


10

MATL,4个字节

e!Xs

在线尝试!

我编写的第一批MATL代码!接受两个输入,分别a作为行向量(逗号分隔)和l数字。算是

e          # reshape `a` into `l` rows (auto pads with 0)
 !         # transpose
  Xs       # sum down the columns



5

Java 7,86字节

没有花哨的褶皱或矩阵,只是一个不错的老式for循环:)

int[]o(int[]a,int l){int i=0,o[]=new int[l];for(;i<a.length;)o[i%l]+=a[i++];return o;}

在Ideone上尝试

内衬:

int[]o(int[]a,int l){
    int i=0,
        o[]=new int[l];
    for(;i<a.length;)
        o[i%l]+=a[i++];
    return o;
}

2
并具有出色的老式Java 7(而不是8)。;)
Kevin Cruijssen


5

JavaScript(ES6),51个字节

a=>n=>a.map((v,i)=>o[i%n]+=v,o=Array(n).fill(0))&&o

以currying语法输入:f([1,2])(3)

测试用例


(a,n,o=[])=>a.map((v,i)=>o[i%n]=~~o[i%n]+v)&&o
奥基

1
@Oki短两个字节:a=>n=>a.map((v,i)=>o[i%=n]=~~o[i]+v,o=[])&&o,但不添加所需的零填充。
贾斯汀·马里纳

f=应该是您字符数的一部分。
nl-x

1
@ nl-x默认情况下允许使用匿名函数,因此只要我不在代码中使用函数名,f=就不需要。继承人的一个贴子元这件事。
贾斯汀·马里纳

1
@ nl-x:不,不应该;仅当函数是递归的(或也许是奎因)时才需要命名。如果不是,那么匿名函数是完全有效的。看这里
毛茸茸的

5

Mathematica,27个字节

Mathematica几乎为此内置了一个

Total@Partition[##,#2,1,0]&

在Wolfram Sandbox上尝试

用法

Total@Partition[##,#2,1,0]&[{-7, 4, -12, 1, 5, -3, 12, 0, 14, -2}, 4]

{12, -1, 0, 1}

说明

Total@Partition[##,#2,1,0]&

      Partition[##,#2,1,0]   (* Partition the first input into sublists of length
                                second input, using offset second input, and
                                right-pad zeroes for incomplete partitions *)
Total@                       (* Add all *)

您的链接无效。
毛茸茸的

1
@Shaggy,您必须手动复制并粘贴代码。Wolfram Sandbox不支持预填充输入。
JungHwan Min


4

Perl 6、36字节

{[Z+] flat(@^a,0 xx$^b*2).rotor($b)}

测试一下

展开:

{  # bare block lambda with 2 placeholder parameters 「@a」, 「$b」
  [Z+]
    flat(
      @^a,         # declare and use the first parameter
      0 xx $^b * 2 # 0 list repeated 2 * the second parameter
    )
    .rotor($b)     # split into chunks that are the size of the second param
}
[1,2], 3

( [1,2], (0,0,0,0,0,0) ) # @^a,0 xx$^b*2
(1,2,0,0,0,0,0,0)        # flat(…)
( (1,2,0), (0,0,0) )     # .rotor($b) # (drops partial lists)
(1,2,0)                  # [Z+]

3

APL(Dyalog),22字节

需要l为左参数和a右参数。

{+⌿s⍴⍵↑⍨×/s←⍺,⍨⌈⍺÷⍨≢⍵}

在线尝试!

{} 匿名函数其中,左参数(l)和右参数(a)在哪里。

≢⍵ 理货(长度) a

⍺÷⍨ 被除以 l

 天花板(向上)

⍺,⍨ 附加 l

s← 存储在s(对于小号 HAPE)

×/ 的乘积(即需要多少个整数)

⍵↑⍨ 从a(用零填充)中获取那么多整数

s⍴ř ESHAPE到形状s(行,列)

+⌿ 柱状总和



3

Perl 6个字节

{[Z+] (|@^a,|(0 xx*)).rotor($^l)[0..@a]}

在线尝试!

如果您喜欢数字42,则可以交换 *一个。这将使其成为42个字节:-)。

说明

{[Z+] (|@^a,|(0 xx*)).rotor($^l)[0..@a]} The whole function
{                                      } Anonymous block
      (    ,        )                    List with 2 elements
        @^a                              The first argument (it is a list)
             (0 xx*)                     Infinite list of zeroes
       |    |                            Flatten both of the lists into the larger list.
                    .rotor($^l)          Split the list into a list of lists, each (the second argument) long.
                               [0..@a]   Only the first (1 + length of the first argument) of them.
 [Z+]                                    Add the corresponding elements up.

最后一个“累加”的神奇之处在于,运算符是“带+的zip压缩”。顺便说一句,如果我们仅在内部有1个列表的列表上使用它,则此方法将无法解决,但是如果原始列表为非空(由于倒数第二行),则不会发生这种情况。另请注意,我们最终不仅要摄取@a,而且要摄取@a * $l物品。幸运的是,我们仅添加了零,不会影响最终结果。


3

外壳,9个字节

S↑ȯ¡¬Fż+C

在线尝试!

说明

        C    Cut into lists of length n
     Fż+     Sum them element-wise
  ȯ¡¬        Append infinitely many 0s
S↑           Take the first n elements

3

Pyth,8个字节

m+F%Q>vz

在这里尝试!

Pyth,10个字节

sMCc.[EZQQ

在这里尝试!

说明

说明#1

m+F%Q>vz   Full program. Q means input.

m          Map over the implicit range [0, input_1), with a variable d.
     >vz  All the elements of input_2 after d; input_2[d:] in Python.
   %Q     Every Qth element of ^.
 +F       Sum. Implicitly output the result.

说明#2

sMCc。[EZQQ完整程序。

    。[E将第二个输入填充到右侧,并重复复制...
       Z ...零(0),最接近...的倍数
        Q ...第一个输入。
   c Q切成与第一输入相等的长度的块。
  C矩阵转置。获取嵌套列表的所有列。
sM每个加和。
             输出(隐式)。 

这样的事情怎么样:sM.TcEQ
Jakube

@Jakube这是不正确的,因为您必须先填充零。那是Leaky的最初尝试,但失败了[1], 3,这会给[1]代替[1, 0, 0]
Xcoder先生17年

抱歉,是我的错。
雅库布

3

J15 12字节

]{.+/@(]\~-)

在线尝试!

说明

]{.+/@(]\~-)  Input: array A (LHS), chunk size L (RHS)
          -   Negate L
       ]\~    Take each non-overlapping sublist of size L in A
   +/@        Reduce the columns by addition
]             Get L
 {.           Take that many, filling with 0's

有什么原因我们不能取消包装盒?那又如何[:+/-@[[\]呢?
约拿(Jonah)2009年

@Jonah如果块大小大于输入数组的长度,则不会将其填充零。
英里

很好的编辑-现在更干净了。
约拿(Jonah)

3

05AB1E,8个字节

ô0ζO²Å0+

在线尝试!

ô0ζO²Å0+   Full program
ô          Push <1st input> split into a list of <2nd input> pieces
 0ζ        Zip sublists with 0 as a filler
   O       Sum each sublist
           --- from here, the program handles outputs shorter 
               than the required length
    ²Å0    Push a list of zeros of length <2nd input>
       +   Sum the result with that list

3

05AB1E,8个字节

Å0+¹ô0ζO

在线尝试!

Å0       # Push an arrary of all 0s with length l
  +      # Add that to the array
   ¹ô    # Split into chunks of length l
     0ζ  # Zip, padding with 0s
       O # Sum each chunk

几乎与我自己的解决方案相同:codegolf.stackexchange.com/a/143186/73296
scottinet

@scottinet我一定错过了。它们足够不同,我将离开我并投票给你:)
Riley

我真的不介意,只是想指出一点:)
scottinet

@scottinet有趣的是,您可以重新排列操作,并使用相同的字节数和几乎相同的字节数(¹vs ²
Riley 2017年

2

SOGL V0.12,14字节

l⁵%⁵κ{0+}nI⌡∑¹

在这里尝试!尝试所有测试用例。这被写为一个未命名的函数,并且期望chunk length; array在堆栈上。

说明:

padding zeroes
l          get the array's length
 ⁵%        modulo the chunk length
   ⁵κ      chunk length - result of above
     {  }  that many times
      0+     append a 0 to the array

adding the array together
n      split into the chunks
 I     rotate clockwise
  ⌡    for each
   ∑     sum
    ¹  wrap the results in an array

什么是F你挂在试试下面的代码?
Pavel

@Pavel函数名称。相同于JS f=a=>a+2f=部分不计入-在SOGL F\n不计算在内。
dzaima

2

05AB1E,12个字节

gs÷*+Å0¹+ôøO

在线尝试!

说明

gs÷*+Å0¹+ôøO
g            # Get the length of the first input (the array)
 s           # Push the second input on top of the result
  ÷          # integer divide the two values
   *         # Multiply with the second input (the length)...
    +        # and add the second input to the result
     Å0      # Create a list of zeros with that length
       ¹+    # Add it to the first input
         ô   # And finally split it into chunks of the input length...
          ø  # ...transpose it...
           O # and sum each resulting subarray
             # Implicit print



2

R62 57字节

-5字节归功于user2390246

function(a,l)rowSums(matrix(c(a,rep(0,l-sum(a|1)%%l)),l))

在线尝试!

已更新,因为它不再需要处理空的情况。

a用零,构建的矩阵l的行,并计算并返回行总和。



@ user2390246当然!当我们不得不处理空箱时,我有一个较旧的版本,但这是我的“主要”,因此我不打算再次尝试。
朱塞佩

2

堆叠式,24字节

[:@z#<[0 z rpad]map sum]

在线尝试!

说明

[:@z#<[0 z rpad]map sum]
[                      ]   anonymous function
 :@z                       stores TOS as `z` (the length)
    #<                     cut STOS in TOS slices
      [        ]map        for each slice
       0 z rpad               pad the slice with `z` zeroes
                    sum]   summate all inner slices


2

Japt,7个字节

伙计,我使用了错误的Japt方法进行了太长时间的尝试,试图使其[1], 3在合理的字节数下适用于测试用例!

VÆëVX x

试试吧


说明

数组U和整数的隐式输入V

0到生成一个整数数组,V-1并将每个整数X作为当前元素传递给函数。

ëVX

从index开始抓取所有V元素。UX

x

通过加法减少该数组。


2

C,(GCC)101 86字节

在线尝试!

f(int*a,int l,int s,int*m){if(s){int i=l;while(i&&s){m[l-i--]+=*a++;s--;}f(a,l,s,m);}}

用法

int main() {
   int l = 3;
   int a[8] = {1,2,3,4,5,6,7,8};
   int *m = (int *)malloc(sizeof(int) * l);
   f(a, l, 8, m);
   for (int i=0; i<3; i++) {
    printf("%d, ",m[i]);
   }
}

请注意,您必须传入数组的长度和堆上的新动态数组(m)。



1

PowerShell,62字节

param($a,$l)1..$l|%{$y=--$_;($o=0)..$l|%{$o+=$a[$y+$_*$l]};$o}

在线尝试!

我们接受输入的$a精力和精力$l。然后从循环1$l。我们将辅助程序的每次迭代都设置$y为比当前数小1(这是因为PowerShell 0索引但$l强度在1索引中)。然后,将$output 设置为0,然后再次循环到$l。我们将每个内部迭代简单地累积到$o适当索引的$aRray元素中。这利用了以下事实:越过数组末尾的索引将返回$null0 + $null = 0

内循环完成后,我们输出$o并继续进行下一个块。各种输出保留在管道上,并Write-Output在程序完成时通过隐式发生输出。


1

Perl 5 5,44 + 1(-a)= 45字节

@r=(0)x($l=<>);map$r[$i++%$l]+=$_,@F;say"@r"

在线尝试!

编辑:修复了请求的长度小于输入数组的情况


1

外壳,10个字节

Fż+So:`R0C

在线尝试!

取消高尔夫/解释

             -- implicit inputs n & xs                   | 3  [1,2,3,4]
   S      C  -- cut xs into sublists of length n & ...   | [[1,2,3], [4]]
    (:`R0)   -- ... prepend [0,...,0] (length n)         | [[0,0,0], [1,2,3], [4]]
F            -- accumulate the sublists with             |
 ż+          -- element-wise addition                    | [0+1+4, 0+2, 0+3]

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.