| Bytes | Lang | Time | Link |
|---|---|---|---|
| 002 | Japt | 240827T190431Z | Shaggy |
| 875 | Vyxal | 240827T020836Z | lyxal |
| 064 | Scala | 231110T113708Z | 138 Aspe |
| 052 | R | 231107T192656Z | pajonk |
| 051 | R | 231107T142857Z | Kirill L |
| 004 | Uiua | 231107T110857Z | chunes |
| 004 | Husk | 201003T162915Z | Razetime |
| 005 | Japt | 161219T225057Z | ETHprodu |
| 048 | JavaScript ES6 | 161217T232953Z | Arnauld |
| 063 | PHP | 161219T211135Z | Titus |
| 070 | Clojure | 161219T192052Z | NikoNyrh |
| 045 | Python 2 | 161218T010232Z | Dennis |
| 005 | CJam | 161218T031902Z | Luis Men |
| 003 | Dyalog APL | 161219T002625Z | Adá |
| 005 | J | 161219T011224Z | Conor O& |
| 097 | R | 161218T110837Z | Fré |
| 003 | MATL | 161218T031350Z | Luis Men |
| 040 | Haskell | 161217T232203Z | flawr |
| 069 | Octave | 161218T070232Z | rahnema1 |
| 124 | Java 8 | 161218T062057Z | Jack Amm |
| 015 | Mathematica | 161218T053132Z | alephalp |
| 004 | Pyth | 161218T045226Z | Maltysen |
| 130 | C++14 | 161218T015905Z | Karl Nap |
| 034 | Haskell | 161218T015808Z | Laikoni |
| 004 | Pyke | 161218T004259Z | Blue |
| 011 | Wonder | 161218T000529Z | Mama Fun |
| 001 | Jelly | 161217T225811Z | Dennis |
| 023 | Perl 6 | 161217T230604Z | smls |
Vyxal, 7 bitsv2, 0.875 bytes
∑
Bitstring:
1011001
I can't let Dennis have all the fun with a single built-in.
Sum is implemented as fold-by-addition, which uses the automatic vectorisation of +.
Scala, 64 bytes
Golfed version. Try it online!
l=>{l.map(x=>x.padTo(l.map(_.size).max,0)).transpose.map(_.sum)}
Ungolfed version. Try it online!
object Main {
def columnSum(lists: List[List[Int]]): List[Int] = {
// Ensure the lists are of uniform length for transposing, fill shorter ones with 0s
val maxLength = lists.map(_.length).max
val uniformLists = lists.map(list => list.padTo(maxLength, 0))
// Transpose the list of lists (turns columns into rows) and sum each row
uniformLists.transpose.map(_.sum)
}
def main(args: Array[String]): Unit = {
// Test cases
println(columnSum(List(List(1,2,3,4), List(1), List(5,2,3), List(6,1)))) // Output: List(13, 5, 6, 4)
println(columnSum(List(List(0)))) // Output: List(0)
println(columnSum(List(List(1), List(1,1,1,1)))) // Output: List(2, 1, 1, 1)
println(columnSum(List(List(1), List(1,2), List(1,2,3), List(1,2,3,4)))) // Output: List(4, 6, 6, 4)
println(columnSum(List(List(1,6,2,-6), List(-1,2,3,5)))) // Output: List(0, 8, 5, -1)
}
}
R, 52 bytes
\(x)colSums(t(sapply(x,\(v)v[1:max(lengths(x))])),T)
Only one byte longer than Kirill L.'s answer, so I thought it's worth posting as well.
R, 53 52 51 bytes
\(x){for(i in x)F=F+i*!seq(!i)-1:max(lengths(x));F}
Thanks to Giuseppe for a byte saved.
Husk, 4 bytes
mΣT0
Explanation
mΣT0
T0 Transpose matrix, padding with 0's where needed
mΣ map each column to its sum
Japt, 5 bytes
Uz mx
U is the input array, and z on arrays rotates the array clockwise by 90 degrees. Therefore,
[
[1,2,3,4],
[1 ],
[5,2,3 ],
[6,1 ]
]
becomes
[
[6,5,1,1],
[1,2, 2],
[ 3, 3],
[ 4]
]
(Spacing added only for display purposes.)
mx then maps by summation (x), which gives the desired result: [13,5,6,4].
JavaScript (ES6), 51 48 bytes
Saved 3 bytes, thanks to ETHproductions
a=>a.map(b=>b.map((v,i)=>r[i]=~~r[i]+v),r=[])&&r
Test cases
let f =
a=>a.map(b=>b.map((v,i)=>r[i]=~~r[i]+v),r=[])&&r
console.log(f([[1,2,3,4],[1],[5,2,3],[6,1]])); // -> [13,5,6,4]
console.log(f([[0]])); // -> [0]
console.log(f([[1],[1,1,1,1]])); // -> [2,1,1,1]
console.log(f([[1],[1,2],[1,2,3],[1,2,3,4]])); // -> [4,6,6,4]
console.log(f([[1,6,2,-6],[-1,2,3,5]])); // -> [0,8,5,-1]
PHP, 63 bytes
<?foreach($_GETas$a)foreach($a as$i=>$x)$r[$i]+=$x;print_r($r);
call in browser with GET parameters as list of inputs.
Example:
script.php?a[]=1&a[]=2&a[]=3&a[]=4&b[]=1&c[]=5&c[]=2&c[]=3&d[]=6&d[]=1
(Array names are ignored, so you can name them any way you want.)
Try this function for testing:
function s($a){foreach($a as$b)foreach($b as$i=>$x)$r[$i]+=$x;return$r;}
or use http_build_query($array,a) to convert a given array of arrays to GET parameters.
Clojure, 70 bytes
#(for[i(range(apply max(map count %)))](apply +(for[v %](get v i 0))))
A basic nested loop.
Python 2, 47 45 bytes
lambda x:map(lambda*y:sum(filter(None,y)),*x)
Thanks to @vaultah for golfing off 2 bytes!
CJam, 7 5 bytes
2 bytes off thanks to Dennis!
{:.+}
This defines an anonymous block that takes a list of lists, such as [[1 2 3 4] [1] [5 2 3] [6 1]], and replaces it by a list, [13 5 6 4].
Try it online! Or verify all test cases.
Explanation
{ } e# Define block
: e# Fold over the following dyadic function
.+ e# Vectorized addition
Dyalog APL, 3 bytes
+⌿↑
+⌿ sum column-wise
↑ the mixed (list of list, stacked into matrix, padding with zeros) argument
J, 5 bytes
+/@:>
Takes input as a boxed list of lists.
Test cases
1 ; 1 1 1 1
+-+-------+
|1|1 1 1 1|
+-+-------+
(+/@:>) 1 ; 1 1 1 1
2 1 1 1
1 ; 1 2 ; 1 2 3 ; 1 2 3 4
+-+---+-----+-------+
|1|1 2|1 2 3|1 2 3 4|
+-+---+-----+-------+
(+/@:>) 1 ; 1 2 ; 1 2 3 ; 1 2 3 4
4 6 6 4
R, 105 97 bytes
a=c();l=length;for(i in 1:l(w)){length(w[[i]])=max(sapply(w,l));a=rbind(a,w[[i]])};colSums(a,n=T)
This takes in input a list object called w in the form :
w=list(c(1,2,3,4),c(1),c(1,2))
It outputs the column-wise sum : [1] 3 4 3 4
This solution is quite long to me. R has the particularity to recycle when you try to bind vectors of different length. For example :
a=c(1,2,3,4)
b=c(1,2)
cbind(a,b)
a b
[1,] 1 1
[2,] 2 2
[3,] 3 1
[4,] 4 2
b is re-used once to fit, which is why I begin with a list.
The program adjusts the length of all the elements of the list as the one of the longest, binds the elements and computs the column-wise sum.
The length adjusting produces NA's, that are ignored by the sum.
-8 bytes thanks to @Jarko Dubbeldam !
MATL, 3 bytes
oXs
(MATL doesn't know that the plural of "ox" is "oxen"...)
Input is a cell array of numeric row vectors, in the same format as in the challenge text:
{[1,2,3,4],[1],[5,2,3],[6,1]}
Try it online! Or verify all test cases.
% Implicit input
o % Convert cell array to a matrix, right-padding with zeros each row
Xs % Sum of each column
% Implicit display
Haskell, 61 41 40 bytes
Thanks @Laikoni for -20 bytes, @nimi for -1 byte!
f[]=[]
f l=sum[h|h:_<-l]:f[t:u|_:t:u<-l]
Explanation: It is just a recursive summation of the first elements of the list, also dealing with discarding empty lists in every intermediate step:
sum[h|h:_<-l] -- sums up all the first elemetns of the list
[t:u|_:t:u<-l] -- removes the first element of all the list, and removes empty lists
f -- applies f to the remaining list
: -- prepends the sum to the rest
Octave, 69 bytes
@(a){g=1:max(s=cellfun(@numel,a))<=s';f=g'+0;f(g')=[a{:}];sum(f')}{4}
Java 8, 124 bytes
this is a lambda expression for a Function< int[ ][ ], int[ ] >
i->{int L=0,t,r[];for(int[]a:i)L=(t=a.length)>L?t:L;r=new int[L];for(;0>L--;)for(int[]a:i)r[L]+=a.length>L?a[L]:0;return r;}
it takes the largest array length from the input, creates a new array of that size, and then writes the sums of each column to the array.
Mathematica, 15 bytes
Total@*PadRight
C++14, 130 bytes
As unnamed generic lambda:
[](auto C,auto&r){r.clear();int i=0,b=1;while(b--){r.push_back(0);for(auto c:C)r.back()+=i<c.size()?c[b=1,i]:0;++i;}r.pop_back();}
Requires C to be like vector<vector<int>> and return value r to be like vector<int> (should be okay according to meta).
Ungolfed & usage:
#include<vector>
#include<iostream>
auto f=
[](auto C, auto&r){
r.clear(); //clearing r just to be sure
int i=0,b=1; //i is the position in the row, b is a boolean
while(b--){ //while something was added
r.push_back(0); //add zero
for(auto c:C) //for each container
r.back() += i<c.size() ? //add to the last element
c[b=1,i] : 0; //set b and get the element or zero
++i;
}
r.pop_back(); //remove last unnecessary zero
}
;
using namespace std;
int main(){
vector<vector<int> > C = { {1,2,3,4}, {1}, {5,2,3}, {6,1} };
vector<int> r;
f(C,r);
for (int i: r)
cout << i << ", ";
cout << endl;
}
Haskell, 34 bytes
import Data.List
map sum.transpose
Try it online! Usage:
Prelude Data.List> map sum.transpose $ [[1,2,3,4],[1],[5,2,3],[6,1]]
[13,5,6,4]
Wonder, 11 bytes
@->#sum '#0
Transpose and map with sum function. Usage:
(@->#sum '#0)[[1 2 3 4];[1];[5 2 3];[6 1]]
Jelly, 1 byte
S
Try it online! or verify all test cases.
How it works
The sum atom S is a shorthand for +/, which performs reduction by addition.
The quick / reduces along the outmost dimension, so it calls its link for the elements of the input. Here, the elements are the rows.
The addition atom + vectorizes, so adding two row vectors perform element-by-element addition. When the arguments have different lengths, the elements of the longer argument that have no counterpart in the shorter one are left unaltered.
All in all, with an irregular matrix as argument, S computes the column-wise sum, skipping missing entries in the shorter rows.
Perl 6, 23 bytes
{roundrobin(|$_)».sum}