secret
Created — forked from /polynomial_alech.rb

  • Download Gist
polynomial_alech.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
class Fixnum
# returns '+' for positive numbers, '-' for negative and '' for 0
def sign
case self <=> 0
when 0
then ''
when 1
then '+'
when -1
then '-'
end
end
end
 
class Polynomial
def initialize(coefficients)
if coefficients.size < 2 then
raise ArgumentError, "Need at least 2 coefficients."
end
@coefficients = coefficients
end
 
# String representation of the object
def to_s
result = ''
@coefficients.reverse.each_with_index do |c, exp|
# ignore the ones with 0 as coefficient
next if c == 0
result = c.sign + formatted_coeff_abs(c) + x_to_n(exp) + result
end
# if the result starts with a '+', we should strip it
result.sub!(/^\+/, '')
# if the result is empty, it is the constant 0 polynomial
result == "" ? "0" : result
end
 
private
# 'x^n' for n > 1, 'x' for n == 1 and '' for n == 0
def x_to_n(n)
case n
when 1
then "x"
when 0
then ""
else "x^#{n}"
end
end
 
# The absolute value of the coefficient as a string, the empty
# string if the coefficient is 1
def formatted_coeff_abs(coefficient)
coefficient.abs == 1 ? "" : coefficient.abs.to_s
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.