Skip to content

Instantly share code, notes, and snippets.

@compactcode
Last active August 29, 2015 13:57
Show Gist options
  • Save compactcode/9405117 to your computer and use it in GitHub Desktop.
Save compactcode/9405117 to your computer and use it in GitHub Desktop.
Array Permutation
def self.permute(one, two, three)
result = []
one.each do |x|
two.each do |y|
three.each do |z|
result << [x, y, z]
end
end
end
result
end
def self.permute(arrays, results=[], current=[])
arrays[0].each do |item|
if arrays[1..-1].empty?
results << current + [item]
else
permute(arrays[1..-1], results, current + [item])
end
end
results
end
@compactcode
Copy link
Author

Generalize for (n) arrays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment