From: Michael DeHaan Date: 2004-11-10T22:37:23+09:00 Subject: Re: Iterating trough hash "each_ordered_pair_of_elements_in_the_set_except_for_equal_elements" But that would just be overly silly... :) On Wed, 10 Nov 2004 08:08:49 +0900, Mark Hubbart wrote: > On Wed, 10 Nov 2004 06:51:50 +0900, Brian Schr�der > > > wrote: > > On Wed, 10 Nov 2004 06:41:08 +0900 > > > > > > Michael DeHaan wrote: > > > > > Hmm, that's not a good bug there, so I'll pull the "history" thing out > > > (I was trying to be too clever)... > > > > > > module Enumerable > > > def each_permutation > > > each do |item1| > > > each do |item2| > > > yield [item1,item2] unless (item1 === item2) > > > end > > > end > > > end > > > end > > > > > > > > > > Hello Michael, > > > > I think, that this is not each_permutation, but each_ordered_pair_of_elements_in_the_set_except_for_equal_elements. > > > > each_permutation would be all shuffles of the original enumerable. > > > > And it is not what the OP wanted, as he wanted all unordered pairs. So maybe > > oops. I'll try to correct myself now... > > The method I defined should be called each_combination_pair; they > weren't permutations at all. > > So, I submit a revised method: > > module Enumerable > def combinations(min=0, max = nil) > size = 0 > com = [[]] > each do |item1| > size += 1 > com += com.map{|item2| item2.dup << item1 } > end > com.select{|n| (min..max||size) === n.size} > end > end > > Then: > > h.combinations(2,2).each do |(person1, age1), (person2, age2)| > puts "#{person1} shakes hands with #{person2}." + > "Together they are #{age1+age2} years old." > end > > I'm sure #combinations could be optimized to not bother generating > combinations of the wrong size, but it's already questionable whether > the method is short to justify replacing the original code, which is > probably more efficient :) > > cheers, > Mark > >