secret
Created

  • Download Gist
jeffersonsouza.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
# This class solves the polynomial problem on the RPCFN #4
# Created by: Jefferson Mariano de Souza
# E-mail: jefmsouza@gmail.com
 
class Polynomial
def initialize (aArray)
@array = aArray
# raises exception if there are less than 2 items in the array
if @array.size == 1
raise ArgumentError.new("Need at least 2 coefficients")
end
end
 
@ prints the string with the polynomial
def to_s
if all_zero?
puts "0"
exit
end
text = String.new
amount = @array.size # stores the amount to guide the exponents
 
#iteration
for item in @array
(amount == @array.size)?(item>0?sig="":sig="-"):(item>0?sig="+":sig="-")
if amount > 2 and item != 0
text << "#{sig}#{item.abs==1?"":item.abs}x^#{amount - 1}"
elsif amount == 2 and item != 0
text << "#{sig}#{item.abs==1?"":item.abs}x"
elsif amount == 1 and item != 0
text << "#{sig}#{item.abs}"
end
 
amount -= 1
end
 
puts text
end
# checks if all the items in the array are zeroed
def all_zero?
c_zero = 0
for item in @array
if item == 0
c_zero += 1
end
end
(c_zero==@array.size)?true:false
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.