1

I have some kind of output like this: {{1, 5}, {1, 13}, {1, 5, 25}}. I would like to be able to enter in each sublist and make sums of every two elements in sublists, for example my desired output would be {{6}, {14}, {6, 30, 26}}. I can export these sublists in txt file, but I don't know if this is even necessary.

Is this possible?

Thank you very much on your help!

corey979
  • 23,947
  • 7
  • 58
  • 101
WayneGacy
  • 101
  • 1
  • 2

1 Answers1

7

Imagine you have these data:

data = Range /@ Range[2, 5]

{{1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 3, 4, 5}}

Then this will do:

(Plus @@@ Subsets[#, {2}]) & /@ data

{{3}, {3, 4, 5}, {3, 4, 5, 5, 6, 7}, {3, 4, 5, 6, 5, 6, 7, 7, 8, 9}}

Application f@@@expr is equivalent to Apply[f,expr,{1}]. It will simultaneously map over internal elements and replace their heads with f. Using this on you data:

(Plus @@@ Subsets[#, {2}]) & /@ {{1, 5}, {1, 13}, {1, 5, 25}}

{{6}, {14}, {6, 26, 30}}

With the same success you could use any functions offered to you for your privious answer. For example:

#~Subsets~{2}~Total~{2} & /@ {{1, 5}, {1, 13}, {1, 5, 25}}

{{6}, {14}, {6, 26, 30}}

or from @Verde & @OleksandrR. comments:

(Total /@ Subsets[#, {2}]) & /@ {{1, 5}, {1, 13}, {1, 5, 25}}

{{6}, {14}, {6, 26, 30}}

Vitaliy Kaurov
  • 73,078
  • 9
  • 204
  • 355