If there are two sets $A={1,2,3,4}$ and $B={5,6,7,8}$, how to construct list of all possible 3 tuples where the first two entries are any element from set $A$ and the 3rd entry is any element from set $B$ where repetition (for instance $(1,1,5)$) is also allowed.
1 Answer
$\begingroup$ $\endgroup$
3 {a, b} = {Range[4], Range[5, 8]}; triples = Tuples[{a, a, b}] {{1, 1, 5}, {1, 1, 6}, {1, 1, 7}, {1, 1, 8}, {1, 2, 5}, {1, 2, 6}, {1, 2, 7}, {1, 2, 8}, {1, 3, 5}, {1, 3, 6}, {1, 3, 7}, {1, 3, 8}, {1, 4, 5}, {1, 4, 6}, {1, 4, 7}, {1, 4, 8}, {2, 1, 5}, {2, 1, 6}, {2, 1, 7}, {2, 1, 8}, {2, 2, 5}, {2, 2, 6}, {2, 2, 7}, {2, 2, 8}, {2, 3, 5}, {2, 3, 6}, {2, 3, 7}, {2, 3, 8}, {2, 4, 5}, {2, 4, 6}, {2, 4, 7}, {2, 4, 8}, {3, 1, 5}, {3, 1, 6}, {3, 1, 7}, {3, 1, 8}, {3, 2, 5}, {3, 2, 6}, {3, 2, 7}, {3, 2, 8}, {3, 3, 5}, {3, 3, 6}, {3, 3, 7}, {3, 3, 8}, {3, 4, 5}, {3, 4, 6}, {3, 4, 7}, {3, 4, 8}, {4, 1, 5}, {4, 1, 6}, {4, 1, 7}, {4, 1, 8}, {4, 2, 5}, {4, 2, 6}, {4, 2, 7}, {4, 2, 8}, {4, 3, 5}, {4, 3, 6}, {4, 3, 7}, {4, 3, 8}, {4, 4, 5}, {4, 4, 6}, {4, 4, 7}, {4, 4, 8}}
Also
Flatten[Outer[List, a, a, b], 2] % == triples True
and
Flatten[Array[{#, #2, #3} &, {4, 4, 4}, {1, 1, 5}], 2] % == triples True
- 1$\begingroup$ (+1) In addition, if there is an
OuterwithFlatten, there is (usually) aDistributewith none:Distribute[{a,a,b}, List]$\endgroup$user1066– user10662020-07-05 18:13:51 +00:00Commented Jul 5, 2020 at 18:13 - 1$\begingroup$ This is not much of an addition to a good answer. Just a pipeline style, with even simpler function calls.
Outer[List, Range[4], Range[4], Range[5, 8]] // Flatten // Partition[#, 3] &$\endgroup$PaulCommentary– PaulCommentary2020-07-05 22:31:34 +00:00Commented Jul 5, 2020 at 22:31 - $\begingroup$ @PaulCommentary: Or, just for fun, (i)
Range[4]//Outer[List, #, #, 4+#]&// Flatten[#,2]&(ii)Range[4]//Distribute[{#, #, 4+#},List]&$\endgroup$user1066– user10662020-07-06 09:40:28 +00:00Commented Jul 6, 2020 at 9:40