What’s that? You want me to ask more questions? Sure!
So I’m writing a pascals triangle program. My goal is to write it in
fewer lines than those on the RubyQuiz site. My idea is to use more
math, and less programming.
So in order for my method to work, I sorta need to recreate nPr and
nCr functions. To be official and learn more, I am doing this through
a class. However, every time I run it, I get the following errors:
pascal.rb:29:in pascal': undefined methodnCr’ for 1:Fixnum
(NoMethodError)
from pascal.rb:24:in upto' from pascal.rb:24:inpascal’
from pascal.rb:41
It looks like you are defining–don’t remember the ruby term–java calls
it a static method. You want an instance method. Just declare it as
def self®
and not
def self.nPr®
because that is called like:
Integer.nPr(something)
and you want:
my_number.nPr®
Of course Ruby has Bignums, but you could make the program more
efficient by
not calculating such enormous intermediate values and then dividing
them.
I suggest you cancel out the terms which are common to the numerator and
denominator.
That is, 9C4 is 9!/5!/!4!, but 9!/5! is 9876, so the result is
9876/432*1. Also, you can swap r and n-r to minimise the
calculation.
Example:
def Math.nCr(n,r)
a, b = r, n-r
a, b = b, a if a < b # a is the larger
numer = (a+1…n).inject(1) { |t,v| tv } # n!/r!
denom = (2…b).inject(1) { |t,v| tv } # (n-r)!
numer/denom
end
(0…9).each { |r| puts Math.nCr(9,r) }
As for making these instance variables of Integer (without self.):
that’s
fine, but I’d suggest you make them class methods of Math or of your own
module. Whilst
Math.nCr(9,4)
is a bit more long-winded to type than 9.nCr(4), it avoids cluttering
Integer with more methods.
Regards,
Brian.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.