Created
January 23, 2010 01:27
-
-
Save adamlum/284365 to your computer and use it in GitHub Desktop.
Adam Lum's solution to RPCFN #4 (Ruby**Fun)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Adam Lum's solution to RPCFN #4 | |
# http://rubylearning.com/blog/2009/11/26/rpcfn-rubyfun-4/ | |
class Polynomial | |
attr_accessor :coefficient_array | |
def initialize(in_coefficient_array) | |
if (in_coefficient_array.size < 2) | |
raise ArgumentError, "Need at least 2 coefficients." | |
end | |
@coefficient_array = in_coefficient_array | |
end | |
def to_str | |
to_s | |
end | |
def to_s | |
return_string = "" | |
coefficient_count = @coefficient_array.size - 1 | |
@coefficient_array.each do |c| | |
if (c != 0) | |
if (c > 1) | |
return_string += "+#{c.to_s}" | |
elsif (c == 1) | |
if (coefficient_count != @coefficient_array.size - 1) | |
return_string += "+" | |
end | |
elsif (c == -1) | |
return_string += "-" | |
else | |
return_string += c.to_s | |
end | |
if (coefficient_count > 1) | |
return_string += "x^#{coefficient_count}" | |
elsif (coefficient_count == 1) | |
return_string += "x" | |
end | |
end | |
coefficient_count -= 1 | |
end | |
if (return_string.length <= 0) | |
return_string = "0" | |
end | |
return_string | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment