Sha256: 550ae6dada166c653563ef17b4fd9df23f692e51f925e5bcd9ba797cbf7f5a7b
Contents?: true
Size: 1.34 KB
Versions: 19
Compression:
Stored size: 1.34 KB
Contents
module Enumerable # Produces an array of arrays of all possible combinations # of the given arrays in the position given. (Explain me better?) # # a = %w|a b| # b = %w|a x| # c = %w|x y| # Array.combinations(a, b, c).each { |x| p x } # # produces # # ["a", "a", "x"] # ["a", "a", "y"] # ["a", "x", "x"] # ["a", "x", "y"] # ["b", "a", "x"] # ["b", "a", "y"] # ["b", "x", "x"] # ["b", "x", "y"] # def self.combinations(head, *rest) crest = rest.empty? ? [[]] : combinations(*rest) head.inject([]) { |combs, item| combs + crest.map { |comb| [item] + comb } } end end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test require 'test/unit' class TCEnumerable < Test::Unit::TestCase def test_combinations a = [1,2] b = [3,4] r = Enumerable.combinations(a,b) assert_equal( [[1,3],[1,4],[2,3],[2,4]], r ) r = [ ["a", "a", "x"], ["a", "a", "y"], ["a", "x", "x"], ["a", "x", "y"], ["b", "a", "x"], ["b", "a", "y"], ["b", "x", "x"], ["b", "x", "y"] ] a = %w|a b| b = %w|a x| c = %w|x y| z = Enumerable.combinations(a, b, c) assert_equal( r, z ) end end =end
Version data entries
19 entries across 19 versions & 1 rubygems