class Array # Applys a block to each possible permutation of an array/enumerable. # # %w[a b c].each_permutation { |x| puts(x.join('')) } # # produces # # abc # acb # bac # bca # cab # cba # #-- # Credit goes to Paul Battley. #++ def each_permutation( prefixed=[] ) s = self.to_a if (length < 2) # there are no elements left to permute yield(prefixed + self) else # recursively permute the remaining elements s.each_with_index do |e, i| (s[0,i]+s[(i+1)..-1]).each_permutation(prefixed+[e]) { |a| yield a } end end end end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # # TODO