-
-
Save RLGGHC/6e3da17378733c89d41e 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
class Polynomial | |
attr_accessor :polynomial | |
def initialize(polynomial) | |
raise ArgumentError, 'Need at least 2 coefficients' if polynomial.size < 2 | |
@polynomial = polynomial.reverse | |
end | |
def to_s | |
join(terms) | |
end | |
private | |
# returns an array that contains the terms of the polynomial | |
def terms | |
degree = @polynomial.size - 1 | |
exponent = degree | |
terms = [] | |
degree.downto 0 do |position| | |
terms << term_at(position , exponent) | |
exponent -= 1 | |
end | |
return terms | |
end | |
# returns a string that contains the polynomial in a pretty format | |
def join(terms) | |
# checking if all the terms are zeros to display it as '0' | |
all_zeros = terms.all? {|coefficient| coefficient == '0'} | |
if all_zeros | |
'0' | |
else | |
# delete all terms with 0 as coefficient as away to omitting them form being displayed | |
terms.delete '0' | |
# joining all terms by '+' sign then omitting '+' sign in '+-' like in '+-10x' => '-10x' | |
terms.join('+').gsub(/\+\-/ , '-') | |
end | |
end | |
# making sure that the coefficients '1x' and '-1x' displayed as 'x' and '-x' | |
def pretty(coefficient) | |
if coefficient == '1' | |
'' | |
elsif coefficient == '-1' | |
'-' | |
else | |
coefficient | |
end | |
end | |
# returns a string that contains the term in pretty format | |
def term_at(position, exponent) | |
coefficient = @polynomial[position].to_s | |
# returning '1' instead of '1x^0' | |
if position == 0 | |
coefficient | |
# returning '0' instead of '0x^2' | |
elsif coefficient == '0' | |
'0' | |
# returning '10x' if the exponent is 1 or '10x^2' | |
else | |
exponent == 1 ? "#{pretty coefficient}x" : "#{pretty coefficient}x^#{exponent}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment