Ruby permutation method rocks!

Early today I was doing my first homework assignment for the SaaS course by University of California – Berkeley, and was making a Rspec test work. This method was meant to take 2 arguments, one array with integers and one integer. What we have to do is sum two numbers in the array until it gets equal to the second argument. Since I come from a Pascal and C background my mind started to think low level, and then I had to say “calm down Adnilson, this is Object Oriented” but, that didn’t keep me from trying. After hitting a wall I went to the Array documentation where I found Ruby’s permutation¬† method that permitted the program to sum all numbers in the array until it matches n, otherwise returns false. I don’t know if other programming languages have the same method, but this made me feel so happy! Below I will show the code:

def sum_to_n? arr, n
if arr.empty? || arr.length == 1
  false
  elsif arr.permutation(2).any? { |a, b| a + b == n }
    true
  else
    false
  end
end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s