From: Trans Date: 2007-02-01T05:31:58+09:00 Subject: Re: cartesian product of arrays On Jan 31, 2:05 pm, Thomas Hafner wrote: > Hello, > > "Trans" wrote/schrieb <1170111266.962275.227...@v45g2000cwv.googlegroups.com>: > > > On Jan 29, 3:53 pm, Thomas Hafner wrote: > > > "Trans" wrote/schrieb <1170083352.801941.114...@p10g2000cwp.googlegroups.com>: > > > It was just my first attempt to implement it, and that somehow > > > accidentally was the result. I'm not unlucky with it, at least it > > > seems to work with just a few lines of code. > > > understood. actually i have a VERY fast implementation already that > > was written by Michael Neuman. to be so fast it's very ugly though :-) > > want to see? > > I was curious enough to run both - my code and the one that you've > adapted from code by Michael Neuman - in irb, and my impression is, > that my code is even much faster. So if you're interested in providing > a really good library, please feel free to benchmark and chose the > best one according to your benchmark results. Very Good! And you are quite right. I must have gotten this confused with some other function. I've put you code in, and credited you. Thanks lots for this! There was only one downside in that using the block form couldn't run on the each possibility as it is computed, but that's okay. I just tied the block into the end result: def cartesian_product(*enums, &block) result = [[]] while [] != enums t, result = result, [] b, *enums = enums t.each do |a| b.each do |n| result << a + [n] end end end if block_given? result.each{ |e| block.call(e) } else result end end > Sorry that I did no benchmark myself (I'm still Ruby newbie); I just > run (1..15).cartesian_product((1..15),(1..15)) with both variants. > > In addition I don't find my implementation ugly, so there's a real > chance to get several advantages at the same time :-) Indeed! :-) Thanks again, T.