Додайте масив із собою


22

Ваша задача сьогодні - взяти масив, розділити його на шматки та додати ці шматки.

Ось як це працює: Вашій програмі чи функції буде надано масив цілих чисел aта розмір фрагменту L. Масив слід розділити на масиви за розміром 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]

Це , найменше виграш байтів!


Хіба це не дура?
сергіол

1
@sergiol, якщо ви зможете знайти питання, що це дублікат, я сам видалю це повідомлення. Однак, наскільки я можу сказати, це не дура.
Павло

Відповіді:


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). ;)
Кевін Круїссен


5

JavaScript (ES6), 51 байт

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

Приймає введення в синтаксисі каррінг: 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

Математика, 27 байт

Математика майже не мала для цього побудови

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

Математика, 58 байт

Total@Partition[PadRight[#,(s=Length@#)+Mod[-s,#2]],{#2}]&

Вхідні дані

[{1}, 3]

Вихідні дані

{1,0,0}


це працює для [1], 3 Ви можете протестувати це sandbox.open.wolframcloud.com , додавши введення в кінці коду та натиснувши shift + enter
J42161217

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(для s hape)

×/ добуток цього (тобто скільки цілих чисел потрібно)

⍵↑⍨ візьміть з нього багато цілих чисел a(оббивка нулями)

s⍴r сформувати форму s(рядки, стовпці)

+⌿ стовпчикові суми



3

Perl 6 , 40 байт

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

Спробуйте в Інтернеті!

Якщо вам подобається число 42, ви можете поміняти його *на "an" . Це зробить 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

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 Це невірно, оскільки вам доведеться спочатку робити нулі. Це була первинна спроба Лікі, але провалилася б [1], 3, що дасть [1]замість цього [1, 0, 0].
Містер Xcoder

Вибачте, моя помилка.
Якубе

3

J , 15 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 Якщо розмір шматка більший за довжину вхідного масиву, він не буде набитим нулем.
миль

Приємна редакція - набагато чистіша зараз.
Йона

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 Я, мабуть, це пропустив. Вони настільки різні, що я залишу свою і піднесу вашу :)
Райлі,

Я не дуже заперечую, просто хотів це зазначити :)
scottinet

@scottinet Цікаво, що ви можете переставити операції та вийти з тим самим числом байтів і майже однаковими байтами, які використовуються ( ¹проти ²)
Райлі

2

SOGL V0.12 , 14 байт

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

Try it Here! or Try all the test-cases. this is written as an unnamed function and expects chunk length; array on the stack.

Explanation:

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

What's the F for in the Try it Here code you linked?
Pavel

@Pavel the functions name. The same as in JS f=a=>a+2 the f= part isn't counted - in SOGL F\n isn't counted.
dzaima

2

05AB1E, 12 bytes

gs÷*+Å0¹+ôøO

Try it online!

Explanation

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

R, 62 57 bytes

-5 bytes thanks to user2390246

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

Try it online!

Updated since it no longer has to handle the empty case.

pads a with zeros, constructs a matrix of l rows, and computes and returns the row sums.



@user2390246 of course! I had that in an older version when we had to handle the empty case but this one was my "primary" and I didn't think to try that again.
Giuseppe

2

Stacked, 24 bytes

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

Try it online!

Explanation

[:@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 bytes

Man, I fought with the wrong Japt method for far too long trying to get it to work for the [1], 3 test case in a reasonable amount of bytes!

VÆëVX x

Try it


Explanation

Implicit input of array U and integer V.

Generate an array of integers from 0 to V-1 and pass each through a function with X being the current element.

ëVX

Grab every Vth element of U, beginning at index X.

x

Reduce that array by addition.


2

C, (GCC) 101 86 Bytes

Try it online!

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);}}

Usage

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]);
   }
}

Note that you have to pass in the length of the array (s) and a new dynamic array on the heap (m).



1

PowerShell, 62 bytes

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

Try it online!

We take input $array and $length. Then loop from 1 to $l. Each iteration we set helper $y to be one less than the current number (this is because PowerShell 0-indexes but the $length is in 1-indexing). Then we set our $output to 0 and loop again up to $l. Each inner iteration we're simply accumulating into $o the appropriately-indexed $array element. This leverages the fact that indexing past the end of the array returns $null and 0 + $null = 0.

Once the inner loop is done, we output $o and move on to the next chunk. The various outputs are left on the pipeline and output via implicit Write-Output happens on program completion.



1

Husk, 10 bytes

Fż+So:`R0C

Try it online!

Ungolfed/Explanation

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

1

Scala 2.12.2, 80 bytes

(a:Array[Int],b:Int)=>(0 to b-1).map(i=>a.indices.filter(_%b==i).collect(a).sum)

It is slightly shorter than the Java solution.

Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.