iterators : Goldberg's problem
- To: mathgroup at smc.vnet.net
- Subject: [mg4040] iterators : Goldberg's problem
- From: Vandemoortele CC Group R&D Center <wouter.meeussen.vdmcc at vandemoortele.be>
- Date: Tue, 28 May 1996 01:46:32 -0400
- Sender: owner-wri-mathgroup at wolfram.com
Re: in response to [mg3965]: After a weekend's thought, maybe a better idea: Creating a set of k indices as iterators for Table or Sum, subject to the condition that their sum be equal to n can be realised by : index[k_,n_]:= Sequence@@ ReplacePart[t=Transpose[ {Array[a,k], Table[0,{k}], FoldList[#-#2&,n,Array[a,k-1]]} ], t[[k,3]],{k,2}] it produces a sequence of iterators : index[3,5] Sequence[{a[1], 0, 5}, {a[2], 0, 5 - a[1]}, {a[3], 5 - a[1] - a[2], 5 - a[1] - a[2]}] The generalised Goldberg problem needs some further input: Times@@({x,y,z}^Array[a,3])//InputForm x^a[1]*y^a[2]*z^a[3] next we make a Sum over the previous expression, and wrap an 'Evaluate' round the iterator: Sum[Times@@({x,y,z}^Array[a,3]),Evaluate[index[3,5]]]//InputForm x^5 + x^4*y + x^3*y^2 + x^2*y^3 + x*y^4 + y^5 + x^4*z + x^3*y*z + x^2*y^2*z + x*y^3*z + y^4*z + x^3*z^2 + x^2*y*z^2 + x*y^2*z^2 + y^3*z^2 + x^2*z^3 + x*y*z^3 + y^2*z^3 + x*z^4 + y*z^4 + z^5 when we further include the Multinomial : Multinomial[Sequence@@Array[a,3]] Multinomial[a[1], a[2], a[3]] We end up with what Golderg wanted: Sum[Times@@({x,y,z}^Array[a,3]) Multinomial[Sequence@@Array[a,3]], Evaluate[index[3,5]]]//InputForm x^5 + 5*x^4*y + 10*x^3*y^2 + 10*x^2*y^3 + 5*x*y^4 + y^5 + 5*x^4*z + 20*x^3*y*z + 30*x^2*y^2*z + 20*x*y^3*z + 5*y^4*z + 10*x^3*z^2 + 30*x^2*y*z^2 + 30*x*y^2*z^2 + 10*y^3*z^2 + 10*x^2*z^3 + 20*x*y*z^3 + 10*y^2*z^3 + 5*x*z^4 + 5*y*z^4 + z^5 Too bad that the implicit variables a[..] need definition inside the index[_,_] function, so that we are not at liberty to choose a name for the iterators. The name t also lingers outside the definition of 'index[ , ]'. I don't know how to get rid of it and still keep a one-liner (maybe with 'Module' or with' t=.'?). Wouter. ==== [MESSAGE SEPARATOR] ====