Re: Generate all k-tuples
- To: mathgroup at smc.vnet.net
- Subject: [mg36217] Re: Generate all k-tuples
- From: Nevin Kapur <nevin at jhu.edu>
- Date: Tue, 27 Aug 2002 02:07:25 -0400 (EDT)
- Organization: Mathematical Sciences, The Johns Hopkins University
- References: <akcp10$52r$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
rdobrow at carleton.edu (Bob) writes:
> Is there an easy (elegant?) way to generate the set of all k-tuples
> taking values from some set (list) S? I want the arguments of the
> function to be k (the length of the tuples) and the set S. That is,
> KTuples[3,{a,b}] should produce
> {{a,a,a},{a,a,b},{a,b,a},{a,b,b},{b,a,a},{b,a,b},{b,b,a},{b,b,b}}.
Here's a first implementation:
ktuples[k_, set_List] :=
Map[ set[[#]] &, Flatten[
Array[ List, Table[ Length[set], {k}]], k - 1]]
In[31]:= ktuples[3,{a,b}]
Out[31]=
{{a,a,a},{a,a,b},{a,b,a},{a,b,b},{b,a,a},{b,a,b},{b,b,a},{b,b,b}}
-Nevin