3
$\begingroup$

I have three 1d lists of different length and want to add all elements like this:

a = {1, 5};
b = {12, 15, 17};
c = {21, 23, 24, 28};

Flatten@Outer[{#1 + #2 + #3} &, a, b, c]

whereby results=$(a[[j]] + b[[k]] + c[[l]])|_{(j={1,2}; k={1,2,3}; l={1,2,3,4})}$

The expected result is:

{34, 36, 37, 41, 37, 39, 40, 44, 39, 41, 42, 46, 38, 40, 41, 
 45, 41, 43, 44, 48, 43, 45, 46, 50}

Could you show how the same result is obtained without using Outer but instead only with the slots #1, #2, #3 and Map. Is that possible?

$\endgroup$
2
  • 1
    $\begingroup$ #1 + #2 + #3 & @@@ Tuples[{a, b, c}] or Distribute[{a, b, c}, List, List, List, #1 + #2 + #3 &] or with Plus instead of #1 + #2 + #3 &? $\endgroup$ – kglr Dec 4 '16 at 14:30
  • $\begingroup$ @kglr: Thank you ... $\endgroup$ – lio Dec 4 '16 at 14:34
10
$\begingroup$

If you have to use Map and #1 + #2 + #3 & literally:

Map[#1 + #2 + #3 & @@ # &, Tuples[{a, b, c}]]

{34, 36, 37, 41, 37, 39, 40, 44, 39, 41, 42, 46, 38, 40, 41, 45, 41, \ 43, 44, 48, 43, 45, 46, 50}

You get the same output with:

Map[Total, Tuples[{a, b, c}]]
Total[Tuples[{a, b, c}], {2}]
Flatten@Outer[Plus, a, b, c]
Plus @@@ Tuples[{a, b, c}]
Distribute[{a, b, c}, List, List, List, Plus]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.