Tue, 22 Jan 2008
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:
- Style 1:
result = Table[Null, {Length[pairs]}];
Do[result[[k]] = pairs[[k, 1]] + pairs[[k, 2]], {k, 1, Length[pairs]}]
result
- Style 2:
Table[pairs[[k, 1]] + pairs[[k, 2]], {k, Length[pairs]}]
- Style 3:
Apply[Plus, pairs, {1}]
- Style 4:
Map[Total, pairs]
- Style 5:
pairs /. {p_, q_} -> p + q
- Style 6:
pairs[[All, 1]] + pairs[[All, 2]]
posted by Bill White at 11:48 | permalink | email me | | |



