From: Aldric Giacomoni Date: 2009-12-19T01:50:13+09:00 Subject: Re: Unique combination of values from arrays Giampiero Zanchi wrote: > one = ['one', 'two'] > two = ['three', 'four'] > three = ['five', 'six'] > p one.product(two.product(three)).map {|x| x.flatten.join(" ")} > > produces > > ["one three five", "one three six", "one four five", "one four six", > "two three five", "two three six", "two four five", "two four six"] That's really cool. So... def fancy_array_permutation arrays return [""] if arrays.empty? first = arrays.shift return first.product( fancy_array_permutation(arrays) ).map {|x| x.flatten.join(" ")} end produces ["one three five ", "one three six ", "one four five ", "one four six ", "two three five ", "two three six ", "two four five ", "two four six "] Blast. I did find this though: http://snipplr.com/view/5087/arrayproduct-for-ruby-18/ Unfortunately, this method uses too much memory, storing the whole cartesian product Array in memory even its elements are needed only one at a time. One nicer alternative is the Cartesian module: "The Cartesian module provide methods for the calculation of the cartesian producted between two enumberable objects. It can also be easily mixed in into any enumberable class, i.e. any class with Enumerable module mixed in." The Cartesian module is available at http://rubyforge.org/projects/cartesian/ This being said, a quick benchmark indicates that your code indeed runs exponentially faster than mine.. As indicated, probably at the expense of memory. -- Posted via http://www.ruby-forum.com/.