4
$\begingroup$

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.

$\endgroup$

1 Answer 1

5
$\begingroup$
{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 
$\endgroup$
3
  • 1
    $\begingroup$ (+1) In addition, if there is an Outer with Flatten, there is (usually) a Distribute with none: Distribute[{a,a,b}, List] $\endgroup$ Commented 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$ Commented 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$ Commented Jul 6, 2020 at 9:40

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.