| Bytes | Lang | Time | Link |
|---|---|---|---|
| 032 | Juby | 250512T015551Z | Jordan |
| 064 | Nim | 230811T132608Z | Adam |
| 002 | Thunno 2 | 230811T131436Z | The Thon |
| nan | 221024T133238Z | bigyihsu | |
| 032 | R | 221023T193526Z | Giuseppe |
| 005 | Japt h | 221023T220532Z | Shaggy |
| 027 | Raku | 221023T170754Z | Sean |
| 038 | Ruby | 221023T152809Z | Jordan |
| 021 | Factor | 221023T143124Z | chunes |
| 004 | 05AB1E | 161114T155911Z | Magic Oc |
| 031 | PARI/GP | 220811T022237Z | alephalp |
| 002 | Vyxal | 220811T012839Z | naffetS |
| 067 | Lua | 210123T015621Z | J. А. de |
| 003 | Husk | 210123T000507Z | user |
| 003 | Jelly | 171015T174811Z | Mr. Xcod |
| 047 | Axiom | 161118T224909Z | user5898 |
| 067 | C++14 | 161114T090220Z | Karl Nap |
| 003 | K | 151021T065008Z | JohnE |
| 022 | Gol><> 0.3.10 | 151021T113647Z | Sp3000 |
| nan | C++14 | 151020T231500Z | Zereges |
| 078 | C++ 61 + 17 = | 151023T043431Z | Jerry Co |
| 052 | Python | 151022T234839Z | xnor |
| 010 | Burlesque | 151022T164244Z | mroman |
| 073 | Python 3 | 151021T142416Z | Morgan T |
| 076 | Python | 151020T214522Z | Anthony |
| 038 | JavaScript ES6 | 151021T204452Z | edc65 |
| 067 | Python 2 | 151021T155214Z | mathmand |
| 075 | R | 151020T210244Z | njnnja |
| 073 | Labyrinth | 151021T133844Z | Martin E |
| nan | C# | 151021T013123Z | LegionMa |
| 019 | Mathematica | 151020T193234Z | Martin E |
| 029 | Julia | 151021T062202Z | Glen O |
| 005 | J | 151020T200856Z | Dennis |
| 008 | APL | 151020T193626Z | Dennis |
| 024 | Octave | 151021T033048Z | alephalp |
| 023 | Haskell | 151020T210919Z | Zgarb |
| 041 | R | 151021T012934Z | flodel |
| 009 | Pyth | 151020T211803Z | Jakube |
| 041 | Matlab | 151020T193932Z | flawr |
| 047 | Haskell | 151020T203024Z | Jake |
| 013 | CJam | 151020T205113Z | Martin E |
Nim, 64 bytes
import math
proc s[I](x:var seq[I],n:I)=
for _ in 1..n:x.cumsum
Outputs by mutating the array in place.
Thunno 2, 2 bytes
{ṡ
Explanation
{ṡ # Implicit input
{ # Input number of times:
ṡ # Cumulative sums
# Implicit output
Go, 120 bytes
func f(s[]int,n int)(o[]int){if n<1{return s}
o=[]int{s[0]}
for i:=range s[1:]{o=append(o,s[i+1]+o[i])}
return f(o,n-1)}
R, 32 bytes
function(l,i)diffinv(l,,i)[0:-i]
diffinv is the inverse of diff, with optional parameters lag, differences, and xi; lag defaults to 1 so we skip it and we compute the the inverse of the \$n^\text{th}\$ difference; xi defaults to 0, so it prepends i instances of 0 to the inverse difference list, which we discard by negative indexing.
Japt -h, 5 bytes
ÆV=å+
ÆV=å+ :Implicit input of integer U & array V
Æ :Map the range [0,U)
V= : Reassign to V
å+ : Cumulatively reduce V by addition
:Implicit output of last element
Raku, 27 bytes
{(@^l,{[\+] @$_}...*)[$^n]}
[\+] @array is how to get a list of partial sums in Raku. Here we construct an infinite sequence of sequences of partial sums and then select the one at the desired index.
05AB1E, 4 bytes
F.pO
Explanation
F # Implicitly take first input and loop n times.
.p # Generate prefixes of input.
O # Sum all prefixes (implicitly vectorized).
PARI/GP, 31 bytes
f(a,n)=Vec(Ser(a)/(1-x)^n+.5)\1
Converts the list to a power series, divides it by \$(1-x)^n\$, and then converts it back to a list.
PARI/GP would drop the leading zeros when converting a power series into a list. So I need to do Vec(...+.5)\1.
PARI/GP, 31 bytes
f(a,n)=a*matrix(#a,,i,j,i<=j)^n
Multiples the \$n\$-th power of the upper triangular matrix of ones. A port of my octave answer.
Lua (67 bytes)
function x(t,n)return load("return "..table.concat(t,"+",1,n))()end
Explanation:
table.concat(t,"+",1,n) gives the string formed by concatenation of elements of t from 1 to n using + as connector, i.e. t[1]+...+t[n].
load(<string>)(), as its name suggests, loads a string to be executed as a function. In this case, a function with zero arguments given by table.concat.
Husk, 4 3 bytes
Saved 1 byte thanks to Dominic Van Essen
!¡∫
!¡∫
¡ Repeatedly apply the following function to the first argument, making an infinite list
∫ Cumulative sum (one cycle)
! Index into this list with the second argument
Jelly, 3 bytes
SƤ¡
This is my (Mr Xcoder's) method.
Jelly, 3 bytes
+\¡
This is caird coinheringaahing's solution.
Jelly, 2 bytes
Ä¡
This is a newer solution.
Method #1
SƤ¡ - Full program, dyadic.
¡ - Apply repeatedly, N times.
Ƥ - Map the preceding link over the prefixes of the list.
S - Sum.
- Output implicitly
Method #2
+\¡ - Full program, dyadic. ¡ - Apply repeatedly, N times. \ - Cumulative reduce by: + - Addition.
Method #3
Ä¡ - Full program, dyadic. ¡ - Apply repeatedly, N times. Ä - Cumulative sums.
Axiom 213 47 bytes
m(a,b)==(for i in 1..b repeat a:=scan(+,a,0);a)
ungolf and some example
(3) -> [m([-3,4,7,-1,15],1), m([-3,4,7,-1,15],3)]
Compiling function l with type List Integer -> List Integer
Compiling function m with type (List Integer,Integer) -> List
Integer
(3) [[- 3,1,8,7,22],[- 3,- 5,1,14,49]]
Type: List List Integer
C++14, 67 bytes
As unnamed lambda modifying its input, requiring c as a random-access-container like vector<int>.
[](auto&c,int n){while(n--)for(int i=0;i++<c.size();c[i]+=c[i-1]);}
K, 7 3 bytes
{y+\/x}
Very similar to the J solution. +\ precisely performs a partial sum, and when / is provided with a monadic verb and an integer left argument it iterates a specified number of times, like a "for" loop. The rest is just wrapping it up neatly to suit the order of arguments.
{y+\/x}[-3 4 7 -1 15;1]
-3 1 8 7 22
{y+\/x}[-3 4 7 -1 15;3]
-3 -5 1 14 49
Tested in Kona and oK.
Edit:
If I'm allowed to reverse the arguments, as @kirbyfan64sos determined, I can dispense with the function wrapping entirely:
+\/
Invoked like:
+\/[3;-3 4 7 -1 15]
This works properly in both k2.8 and k5. It doesn't work in oK since that interpreter does not yet support curried (aka "projected") adverbs, and it doesn't appear to work properly in Kona for less clear reasons.
edit: As of a few days ago, the +\/ formulation also works in oK.
Gol><> 0.3.10, 22 bytes
SI
C>rFlMF:}+
NRl<C}<;
The first integer is taken to be the iteration number and the rest make up the list. The final list is outputted newline-separated.
The language is still quite young and unstable, but since I'm pretty set on these operators I thought it'd be okay.
Explanation
SI Read integer, moving down on EOF (first line runs as loop)
r Reverse stack, putting iteration number on top
[outer loop]
F Do #(iterations) times
[inner loop]
lMF Do #(length of stack - 1) times
: Duplicate top of stack
} Rotate stack rightward (top goes to bottom)
+ Add the top two elements of the stack
C Continue inner loop, moving down from F when loop is over
} Rotate once more
C Continue outer loop, moving down from F when loop is over
lRN Print stack as (num + newline)
; Halt
To see why this works, let's try a small example [5 2 1]:
[5 2 1] -- : --> [5 2 1 1] -- } --> [1 5 2 1] -- + --> [1 5 3]
[1 5 3] -- : --> [1 5 3 3] -- } --> [3 1 5 3] -- + --> [3 1 8]
-- } --> [8 3 1]
C++14, 102 103 94 + 17 (include) = 111 bytes
#include<vector>
auto f(std::vector<int>a,int n){for(;n--;)for(int i=0;i<a.size()-1;++i)a[i+1]+=a[i];return a;}
Ungolfed, with test case
#include <vector>
#include <iostream>
auto f(std::vector<int> a, int n)
{
for (; n--;)
for (int i = 0; i < a.size() - 1; ++i)
a[i + 1] += a[i];
return a;
}
int main()
{
auto t = f({-3, 4, 7, -1, 15}, 3);
for (int i : t)
std::cout << i << " ";
}
Relies on order of evaluation. Not sure if it is UB or not, but works It's compiler dependent, so I changed it.
C++ (61 + 17 = 78 bytes)
#include<numeric>
void f(int*a,int*e,int n){for(;n--;)std::partial_sum(a,e,a);}
Test case:
#include <iostream>
#include <iterator>
int main() {
int a[] { -3, 4, 7, -1, 15 };
f(a, std::end(a), 3);
for (auto i : a)
std::cout << i << " ";
}
This takes a slight liberty with the specification: it uses a C-style array, passing pointers to the beginning and end of the array. Internally, as you can see, it's only an extremely thin wrapper around the std::partial_sum in the standard library. Rather than actually return the resulting value, it just modifies the array that's passed in.
If we don't mind pushing definitions of things to the limit (and, arguably, a bit beyond) we can define a "function" in a lambda expression:
#include<numeric>
#include <iostream>
#include <iterator>
int main() {
int a[] { -3, 4, 7, -1, 15 };
int *e = std::end(a);
int n=3;
auto f=[&]{for(;n--;)std::partial_sum(a,e,a);};
f();
for (auto i : a)
std::cout << i << " ";
}
This reduces the definition of the function(-like object) to this piece:
[&]{for(;n--;)std::partial_sum(a,e,a);};
...for 40 bytes (+17 for the #include).
Python, 52 bytes
f=lambda l,n:n*l and f(f(l[:-1],1)+[sum(l)],n-1)or l
A recursive function that recurses both on the list l and the number of iterations n. Let's break it down.
First, let's consider a recursive function g that iterated the partial sum just once.
g=lambda l:l and g(l[:-1])+[sum(l)]
For an empty list l, this returns l itself, the empty list. Otherwise, the last entry of the partial sums of l is the overall sum of l, which is appended to the recursive result for all but the last element of l.
Now, let's look at a function f that applies g for n iterations.
f=lambda l,n:n and f(g(l),n-1)or l
When n is 0, this returns the list l unchanged, and otherwise, applies g once, then calls f recursively with one fewer iteration remaining.
Now, let's look again at the actual code, which combines the two recursions into a single function. The idea is to treat g(l) as the special case f(l,1).
f=lambda l,n:n*l and f(f(l[:-1],1)+[sum(l)],n-1)or l
We took f(g(l),n-1) from the previous definition, expanded g(l) into g(l[:-1])+[sum(l)], and then replaced g(_) with f(_,1) to confined the recursive calls to f.
For the base case, we want to return l whenever n==0 or l==[]. We combine these by noting that either one makes n*l be the empty list, which is Falsy. So, we recurse whenever n*l is non-empty, and return l otherwise.
Even though there are two recursive calls to f, this does not cause an exponential blow-up the recursive definition of the Fibonacci numbers, but remains quadratic.
Burlesque, 10 bytes
{q++pa}jE!
it's not very efficient in general but it does the trick.
blsq ) {-3 4 7 -1 15} 1 {q++pa}jE!
{-3 1 8 7 22}
blsq ) {-3 4 7 -1 15} 3 {q++pa}jE!
{-3 -5 1 14 49}
Python 3, 73
Could probably be golfed down a bit further.
def f(n,i):
p=0;c=[]
for m in n:p+=m;c+=[p]
f(c,i-1)if i else print(n)
This version uses numpy, which feels a little like cheating, but here it is:
Python 3 (with numpy), 72
from numpy import*
def f(n,i):
if i:c=cumsum(n);f(c,i-1)
else:print(n)
Python, 113 93 89 76 bytes
def f(l,n):
for i in[0]*n:l=[sum(l[:j+1])for j in range(len(l))];
print(l)
It works for both of the test cases. Thanks to Status, Morgan Thrapp, and Ruth Franklin for helping me golf the program down to 93, 89, and 76 bytes respectively.
JavaScript (ES6) 38
Surprisingly small using .map recursively
f=(l,n,t=0)=>n?f(l.map(x=>t+=x),n-1):l
function test()
{
var n, v, i = I.value
v = i.match(/\-?\d+/g).map(x=>+x)
n = v.pop()
console.log(v,n)
O.innerHTML = I.value + ' -> ' + f(v,n) + '\n' + O.innerHTML;
}
test()
<input id=I value='[-3, 4, 7, -1, 15], 3'><button onclick="test()">-></button>
<pre id=O></pre>
Python 2, 67
This uses the same summation as Anthony Roitman, and the same recursion as Morgan Thrapp.
f=lambda l,n:f([sum(l[:i+1])for i in range(len(l))],n-1)if n else l
I developed this solution before I saw theirs, and then it just seemed easier to post it as an answer rather than a comment to either or both of them.
R, 75 bytes
It's long but a different take...computing the desired sequence directly instead of cumulative sums:
function(x,n)sapply(1:length(x),function(i)sum(x[1:i]*choose(i:1+n-2,n-1)))
Noting that the coefficients of the terms of xi for cumsum^n(x) are diagonals of Pascal's triangle. i.e.
cumsum^3(x) = choose(2,2) * x1, choose(3,2) * x1 + choose(2,2) *x2, choose(4,2) * x1 + choose(3,2) * x2 + choose(2,2) * x3, ....
edit: to make a function
Labyrinth, 73 bytes
;?
,"
;
#
#;}=
; #
"#;(
_ ;={()"
#;; ( { "
; { !\(@
+=( =
" " "
":{:"
It's been a while since I answered something in Labyrinth, and this seemed doable. :)
Input format is a flat list with the number of iterations first (and then the list to apply the partial sums to). Delimiters don't matter all, as long as there is no character after the last integer, so you can use something readable like:
3 | -3, 4, 7, -1, 15
Output is newline-separated:
-3
-5
1
14
49
C#, 52 + 85 = 148 137 bytes
using E=System.Collections.Generic.IEnumerable<int>;
and
E I(E s,int i){int t=0;return i<1?s:I(System.Linq.Enumerable.Select(s,v=>t+=v),i-1);}
It uses unorthodox practices (v=>t+=v), but this is PPCG. Also note the stack depth constraint.
Mathematica, 19 bytes
Well, if built-ins are okay...
Accumulate~Nest~##&
Defines a function with the same signature as the examples in the challenge. I'm pretty sure, thanks to the long name Accumulate that this will be easily beaten by the golfing languages and the APL-family, though. :)
To elaborate on LegionMammal978's comment for those who don't Mathematica:
## represents a sequence of the function's parameters (which is like a list that automatically "splats" wherever it's inserted, if you're more familiar with that term from your language's of choice). The ~ are syntactic sugar for infix function invocation, so if we call the function with parameters list and n and expand everything, we get:
Accumulate~Nest~##
Nest[Accumulate, ##]
Nest[Accumulate, list, n]
Which happens to be exactly the argument order expected by Nest.
Julia, 29 bytes
f(x,y)=y>0?f(cumsum(x),y-1):x
This really doesn't need much explanation. It's a recursive function, if y==0 then just output x. Otherwise decrement y, perform a cumsum, and recurse. Probably not the most golfed possible Julia solution, I'm still working on it.
J, 5 bytes
+/\^:
Try it online on J.js.
How it works
/\is an adverb (function that takes a left argument) that cumulatively reduces by its argument.Thus
+/\is the cumulative sum verb.^:is the power conjunction;(f ^: n) yappliesfa total ofntimes toy.The verb-conjunction train
+/\^:forms an adverb that repeats+/\as many times as specified in its (left) argument.x (+/\^:) ygets parsed as(x (+/\^:)) y, which is equivalent to executing(+/\^:x) y.
Thanks to @Zgarb for his help with the explanation.
APL, 9 8 bytes
{+\⍣⍺⊢⍵}
This defines a dyadic function that accepts the iterations and list as left and right arguments.
Thanks to @NBZ for golfing off 1 byte!
Try it online on TryAPL.
How it works
⍺and⍵are the left and right arguments to the function.+\is cumulative reduce by sum.⍣⍺repeats the preceding operator⍺times.⊢⍵applies the identity function to⍵.This is a shorter way of parsing the code as
(+\⍣⍺)⍵instead of+\⍣(⍺⍵).
In conjunction, we apply +\ a total of ⍺ times to ⍵
Octave, 24 bytes
@(l,n)l*triu(0*l'*l+1)^n
Haskell, 26 23 bytes
(!!).iterate(scanl1(+))
This defines an anonymous function, invoked as follows:
> let f = (!!).iterate(scanl1(+)) in f [-3,4,7,-1,15] 3
[-3,-5,1,14,49]
Thanks to @nimi for saving 3 bytes.
Explanation
(!!). -- Index by second argument from
iterate( ) -- the infinite list obtained by iterating
scanl1(+) -- the partial sums function (left scan by +) to first argument
R, 41 bytes
function(x,n){for(i in 1:n)x=cumsum(x);x}
Pyth, 9 bytes
usM._GvwQ
Try it online: Demonstration or Test Suite
Explanation
usM._GvwQ implicit: Q = input list
vw input number
u Q repeat the following instruction ^ times to G = Q
._G sequence of prefixes of G
sM sum them up
Matlab, 41 bytes
function f(l,n);for i=1:n;l=cumsum(l);end
Quite straightforward. I still think it is quite annoying not having a built in way of making piecewise defined anonymous functions, or anchors in recursions.
Ungolfed:
function f(l,n);
for i=1:n;
l=cumsum(l);
end
Haskell, 52 47 bytes
First ever code golf 'attempt', and I'm very much a Haskell beginner, so comments are gladly welcomed! It was not clear in the question as to any necessary format of the function call, or whether it was taken by an argument to the program, so I used the exclamation mark as the function identifier to save a couple of spaces.
0!a=a
i!a=(i-1)![sum$take j a|j<-[1..length a]]
Usage (GHCi):
$ ghci partialsums.hs
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main ( partialsums.hs, interpreted )
Ok, modules loaded: Main.
*Main> 1![-3, 4 ,7 ,-1 ,15]
[-3,1,8,7,22]
*Main> 3![-3, 4 ,7 ,-1 ,15]
[-3,-5,1,14,49]