secret
Last active — forked from rymai/remycoutable.rb

  • Download Gist
remycoutable.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 55 56 57 58 59 60 61 62
# Ruby Programming Challenge For Newbies
# Solution for RPCFN: Ruby**Fun (#4)
#
# Creator : Rémy COUTABLE 2009 (http://remycoutable.fr)
 
class Polynomial
attr_reader :coeffs
# coeffs should be an Array of relative integer
def initialize(coeffs)
raise ArgumentError, "Need at least 2 coefficients." if coeffs.size < 2
@coeffs = coeffs.reverse
end
def to_s
@result = ""
(@coeffs.size - 1).downto(0) do |power|
@result += print_coeff_and_power(@coeffs[power], power)
end
@result.empty? ? "0" : @result
end
private
def print_coeff_and_power(coeff, power)
"#{print_sign(coeff)}#{print_coeff(coeff, power)}#{print_power(power, coeff)}"
end
# only display "+" for a positive integer, and not for the first coeff
def print_sign(coeff)
"+" if coeff > 0 && !@result.empty?
end
# coeff is a relative integer
def print_coeff(coeff, power)
(coeff == -1 && power > 0) ? "-" : coeff if display_coeff?(coeff, power)
end
def display_coeff?(coeff, power)
return case coeff
when 0
false
when 1
power == 0
else
true
end
end
# power is an integer
def print_power(power, coeff)
"x#{"^#{power}" if power > 1}" if power > 0 && coeff != 0
end
end
 
puts Polynomial.new([-3,-4,1,0,6]).to_s
puts Polynomial.new([1,0,2]).to_s
puts Polynomial.new([-1,-2,3,0]).to_s
puts Polynomial.new([0,0,0]).to_s
puts Polynomial.new([0,1,2,3,4]).to_s
puts Polynomial.new([-5,-4,-3,-2,-1]).to_s
puts Polynomial.new([3,2,1]).to_s

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.