Skip to content

Instantly share code, notes, and snippets.

@jalada
Last active August 29, 2015 14:22
Show Gist options
  • Save jalada/28fa2cfdfa31717b0f28 to your computer and use it in GitHub Desktop.
Save jalada/28fa2cfdfa31717b0f28 to your computer and use it in GitHub Desktop.
Create all permutations of an array of an array.
comb([[3], ['a', 'c', 'f'], [4,6], [5,9]])
=> ["3a45", "3a49", "3a65", "3a69", "3c45", "3c49", "3c65", "3c69", "3f45", "3f49", "3f65", "3f69"]
def comb(arr)
head = arr[0]
if arr[1..-1].present?
results = []
head.each{|x|
comb(arr[1..-1]).each{|s|
results << "#{x}#{s}" # Adjust concatentation to suit your types.
}
}
return results
else
head
end
end
# Then I discovered Array#product. D'oh!
def comb(arr)
arr.first.product(*arr[1..-1]).map(&:join)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment