Skip to content

Instantly share code, notes, and snippets.

@lordhumunguz
Created June 17, 2013 16:38
Show Gist options
  • Save lordhumunguz/5798268 to your computer and use it in GitHub Desktop.
Save lordhumunguz/5798268 to your computer and use it in GitHub Desktop.
permutation implementation for array
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
@jfarmer
Copy link

jfarmer commented Jun 17, 2013

Whenever you see code with the following structure:

results = initial_thing
enumerable.each do |thing|
  results = some_method(results, thing)
end
return results

you can write

return enumerable.inject(initial_thing) do |results, thing|
  some_method(results, thing)
end

That's pretty much the definition of inject.

@jfarmer
Copy link

jfarmer commented Jun 17, 2013

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