Tue, 22 Jan 2008

« movemail | MAIN | Annotated Code of Justinian »

Adding pairs of numbers: programming styles in Mathematica

Via Lunchtime Playground: given a list of pairs of numbers, return a list consisting of the sum of each pair.

pairs = {{58, 96}, {85, 22}, {100, 69}, {5, 37}, {32, 64}, {41, 86}, {14, 0}, {79, 22}, {55, 36}, {86, 39}, {11, 15}};

Six ways to add the numbers in Mathematica:

result = Table[Null, {Length[pairs]}];
Do[result[[k]] = pairs[[k, 1]] + pairs[[k, 2]], {k, 1, Length[pairs]}]
result
Table[pairs[[k, 1]] + pairs[[k, 2]], {k, Length[pairs]}]
Apply[Plus, pairs, {1}]
Map[Total, pairs]
pairs /. {p_, q_} -> p + q
pairs[[All, 1]] + pairs[[All, 2]]