سؤال

I am writing Pascal's triangle in Ruby, but keep getting the error message:

pascalsTriangle.rb:3:in 'triangle': undefined method `each' for 4:Fixnum (NoMethodError)
from pascalsTriangle.rb:18

def triangle(n)
  for r in n:
    lst=[1]
    term=1
    k=0
    (0..r+1).step(1){ |index|
      term=term*(r-k+1)/k
      lst.append(term)
      k+=1
    }
    print lst
  end
end

triangle(4)
هل كانت مفيدة؟

المحلول 2

the final source code:

def triangle(n)
    (0..n).each{|r|
            lst=[1]
            term=1
            k=1
            (0..r-1).step(1){|index|
                    term=term*(r-k+1)/k
                    lst.push term 
                    k+=1
            }
            p lst
    }
end
triangle(4)

changes:

  1. you have syntax error on for r in n:.
  2. a logical error on k=0 that causes Division by zero.
  3. (0..r+1) is changed to (0..r-1)
  4. there is no append method for array. changed to push
  5. p is used instead of print

نصائح أخرى

Why code C style in Ruby? :-)

Breaking the problem down would allow you to concentrate on one problem at a time and iterators would make the code more readable. I'm using the binomial theorem to calculate the values in the triangle. If you don't need a super large value from the triangle, this will be fast enough.

Calculating the 1000th line took 2.9 seconds on my virtual linux:

# factorial method
def fact(n)
  (1..n).reduce(:*)
end

# binomial theorem, n choose k
def binomial(n,k)
  return 1 if n-k <= 0
  return 1 if k <= 0
  fact(n) / ( fact(k) * fact( n - k ) )
end

def triangle(nth_line)
  (0..nth_line).map { |e| binomial(nth_line, e) }
end

p triangle(5)
  • Factorial(num), takes a number and return the factorial of it.
  • find_num(n, k), is the mathmatical formula of pascales triangle. !n/ !k * !(n - k) ---- '!' = factorial of number
  • Lastly pascale(num), this iterates a new row of the triangle by maping the index numbers or (k) for each row of (n).

  • If you want to truly understand how this works comment out the pascale, and simply run numbers through find_num((row number), (index number)). Then compare to a picture of the triangle to see the magic for your self

-

def find_num(n, k)
  result = factorial(n) / (factorial(k) * factorial(n - k))
end

def pascale(num)
i = 0
scale = 75
  while i <= num
    new_arr = []
   (0..i).map {|x| new_arr << find_num(i, x)}
    p new_arr.to_s.rjust(50 + scale)
    i += 1
    scale += 1
  end

def factorial(num)
 if num == 0
  return 1
 else
  num *= factorial(num - 1)
 end
end

end

pascale(12)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top