secret
Created — forked from /tony_chen.rb

  • Download Gist
tony_chen.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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
 
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.