From: Kristof Bastiaensen Date: 2004-05-13T21:34:00+09:00 Subject: Re: How to make combinations of an array to produce all possible expressions? On Thu, 13 May 2004 10:38:19 +0200, Erik Terpstra wrote: > I have an array 'conds', which contains some sub-expressions for an > xpath query: > > conds = ["@title='Foo'", "@edition='Bar'", "@date='20040513'"] Hi, I have found at least to ways. Using recursion (maybe not so efficient): class Array def combine comb = Proc.new do |a, *t| tail = (t.empty? ? [] : comb[t]) [[a]] + tail.collect{ |e| [a] + e} + tail end comb[self] end end The following should perform better: class Array def combine2 (1..(2**(size) - 1)).collect do |i| i <<= 1 self.select { (i >>= 1) & 1 == 1} end end end irb(main):018:0> puts conds.combine.collect{|n| n.join ' and '} @title='Foo' @title='Foo' and @edition='Bar' @title='Foo' and @edition='Bar' and @date='20040513' @title='Foo' and @date='20040513' @edition='Bar' @edition='Bar' and @date='20040513' @date='20040513' => nil irb(main):019:0> puts conds.combine2.collect{|n| n.join ' and '} @title='Foo' @edition='Bar' @title='Foo' and @edition='Bar' @date='20040513' @title='Foo' and @date='20040513' @edition='Bar' and @date='20040513' @title='Foo' and @edition='Bar' and @date='20040513' => nil Kristof