Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Forked from amrnt/amrtamimi.rb
Created December 19, 2009 03:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save RLGGHC/fa90d1cee66e05d6d261 to your computer and use it in GitHub Desktop.
class Polynomial
attr_reader :vars
def initialize(vars)
raise ArgumentError, 'Need at least 2 coefficients' if vars.size <2
number_of_terms ||= vars.size - 1
final_output = []
i=0
vars.each do |var|
if var == 0
final_output << ("")
else
if var == 1 || var == -1
final_output << ("+" if var == 1) unless i == 0
final_output << ("-" if var == -1)
final_output << "x"
final_output << "^#{number_of_terms}" unless number_of_terms == 1
else
final_output << ("+" if var > 0) unless i == 0
final_output << ("-" if var < 0)
final_output << (var.to_i * -1 if var < 0)
final_output << (var.to_i if var > 0)
final_output << "x" unless number_of_terms == 0
final_output << "^#{number_of_terms}" unless number_of_terms == 0 || number_of_terms == 1
end
end
i=i+1
number_of_terms = number_of_terms.to_i - 1
end
@final_output = final_output.to_s
@final_output = "0" if final_output.to_s.empty?
end
def to_s
@final_output
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment