Created
June 17, 2013 16:38
-
-
Save lordhumunguz/5798268 to your computer and use it in GitHub Desktop.
permutation implementation for array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def generate_permutations | |
return [self] if self.size < 2 | |
permutation = [] | |
self.each do |element| | |
(self - [element]).generate_permutations.each do |perm_accumulator| | |
permutation.push ([element] + perm_accumulator) | |
end | |
end | |
permutation | |
end | |
end |
Removing or adding elements from anywhere but the end of an array is very expensive. Why?
You should avoid it if you can.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Whenever you see code with the following structure:
you can write
That's pretty much the definition of
inject
.