From: Rick DeNatale Date: 2009-05-18T23:52:22+09:00 Subject: Re: permute each element of a ragged array? On Mon, May 18, 2009 at 10:35 AM, Mark Thomas wrote: > Not sure why the test must be as written, because the order doesn't > fall in a logical pattern (as far as I can tell). Exactly, I don't see a general way to see a pattern when the assertions are expressed as indexed elements equaling specific values. Here's another 'solution' def permute_sets(sets, selected=[]) if sets.empty? selected << [] else sub_permutations = permute_sets(sets[1..-1]) sub_permutations.each do |sub_permutation| sets.first.each do |selection| selected << [selection] + sub_permutation end selected << sub_permutation end end selected end def assert(perms, i, value) if perms[i] == value puts "permutations[#{i}] passes" else puts "permutations[#{i}] fails" if perms.include?(value) puts " but #{value.inspect} IS included in the list of permutations!" end end end sets = [ %w( android hero ), %w( insane clown posse ), %w( phenomenauts ), ] permutations = permute_sets(sets) permutations.each do |p| p p end assert permutations, 0, %w( android insane phenomenauts ) assert permutations, 1, %w( android insane ) assert permutations, 2, %w( android clown ) assert permutations, 3, %w( android posse ) assert permutations, 4, %w( hero insane phenomenauts ) assert permutations,-1, [] Which produces the output: ["android", "insane", "phenomenauts"] ["hero", "insane", "phenomenauts"] ["insane", "phenomenauts"] ["android", "clown", "phenomenauts"] ["hero", "clown", "phenomenauts"] ["clown", "phenomenauts"] ["android", "posse", "phenomenauts"] ["hero", "posse", "phenomenauts"] ["posse", "phenomenauts"] ["android", "phenomenauts"] ["hero", "phenomenauts"] ["phenomenauts"] ["android", "insane"] ["hero", "insane"] ["insane"] ["android", "clown"] ["hero", "clown"] ["clown"] ["android", "posse"] ["hero", "posse"] ["posse"] ["android"] ["hero"] [] permutations[0] passes permutations[1] fails  but ["android", "insane"] IS included in the list of permutations! permutations[2] fails  but ["android", "clown"] IS included in the list of permutations! permutations[3] fails  but ["android", "posse"] IS included in the list of permutations! permutations[4] fails  but ["hero", "insane", "phenomenauts"] IS included in the list of permutations! permutations[-1] passes -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale