Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Forked from anonymous/tony_chen.rb
Created December 3, 2009 01:57
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/231eb7fac57d36870d66 to your computer and use it in GitHub Desktop.
Save RLGGHC/231eb7fac57d36870d66 to your computer and use it in GitHub Desktop.
# Loops through coefficient array in order
# => If the coefficent is 0, skip to next term
# => Get operator value and absoluete coefficent value
# => Appends the term <operator><coefficient>x^<term> to pretty print string
# => Return pretty print string or 0 if pretty print string is empty
class Polynomial
def initialize(coefficient_array)
raise ArgumentError, 'Need at least 2 coefficients' if coefficient_array.size < 2
@coefficient_array = coefficient_array
end
def pretty_print
print_string = ""
coefficient_array = @coefficient_array
current_coefficient = @coefficient_array.size
coefficient_array.each_with_index do |coefficient, term|
current_coefficient -= 1
next if coefficient == 0
operator = get_operator_by_coefficient_and_term(coefficient, term)
coefficient = coefficient.abs
coefficient = "" if coefficient.abs == 1
case current_coefficient
when 0
print_string << "#{operator}#{coefficient}"
when 1
print_string << "#{operator}#{coefficient}x"
else
print_string << "#{operator}#{coefficient}x^#{current_coefficient}"
end
end
# empty string if the array only passes in 0's
print_string == "" ? "0" : print_string
end
def get_operator_by_coefficient_and_term(coefficient, term)
if coefficient > 0
if first_term?(term)
""
else
"+"
end
elsif coefficient < 0
"-"
else
""
end
end
def first_term?(term)
term == 0
end
def to_s
pretty_print
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([-5]).to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment