prograMing: create a cycled matrix
- To: mathgroup at smc.vnet.net
- Subject: [mg8490] prograMing: create a cycled matrix
- From: "Xah" <xah at best.com>
- Date: Tue, 2 Sep 1997 16:15:32 -0400
- Organization: smtp.best.com
- Sender: owner-wri-mathgroup at wolfram.com
Another recreational prograMing problem.
Given a list of lists {list1,list2,...}, I want to create a n by m matrix
using the given lists cycled repeatedly. That is, first row would be
elements of list1 cycled, second row being elements of list2 cycled. If the
given list run out of rows, list1 is again used. Here's my best shot. It's
fairly a good solution, but no doubt you have better solutions. (efficiency
is important here)
Clear[cycledMatrix];
cycledMatrix::"usage"="cycledMatrix[{m,n},{list1,list2,...}] returns a
matrix of dimensions {n,m} with elements of lists cycled repeatedly.
Example: cycledMatrix[{5,4},{{1,2,3},{a,b}}]";
cycledMatrix[{m_Integer,n_Integer},cycleLists:{_List..}]:=Module[{},(Flatten
[({Table[#1,{Quotient[#2,#3]}],Take[#1,Mod[#2,#3]]}&)@@({#,m,Length at #}&)@#]&
)/@Flatten[(({(Flatten[#,1]&)@Table[#1,{Quotient[#2,#3]}],Take[#1,Mod[#2,#3]
]}&)@@({#,n,Length at #}&)@cycleLists),1]];
In[79]:=
cycLists=Table[Range@(Random[Integer,{1,6}]),{Random[Integer,{3,7}]}]
Out[79]=
{{1,2,3},{1,2,3},{1,2,3,4},{1,2,3},{1,2},{1,2,3,4}}
In[84]:=
cycledMatrix[{7,4},cycLists]
Out[84]=
{{1,2,3,1,2,3,1},{1,2,3,1,2,3,1},{1,2,3,4,1,2,3},{1,2,3,1,2,3,1}}
Xah
xah at best.com
http://www.best.com/~xah/SpecialPlaneCurves_dir/specialPlaneCurves.html
Mountain View, CA, USA