Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Created November 28, 2009 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RLGGHC/dda5b5a613653a44218e to your computer and use it in GitHub Desktop.
Save RLGGHC/dda5b5a613653a44218e to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment