From: walter a kehowski Date: 2005-08-12T03:21:10+09:00 Subject: Re: cartesian product - next to last version > > In such cases, I use the Vector class (require 'matrix') as the > 'atomic' unit. Then Array#flatten doesn't peek inside the Vectors and > flatten them inappropriately. > require 'matrix' # see page 694 of PR # class Array def cartprod(b=[]) if b.empty? then #assume self an array of arrays z=inject {|cp,x| cp.cartprod(x) } else z = inject([]) {|a,x| b.inject(a) {|a,y| a << [x,y]}} z.collect! {|x| x.flatten } end end end #Everything works a=[1,2] b=[4,5] c=[7,8] p [a,b,c].cartprod d=[10, Vector[11,12]] p [a,b,c,d].cartprod