-
-
Save RLGGHC/231eb7fac57d36870d66 to your computer and use it in GitHub Desktop.
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
# 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