secret
anonymous / alialsahaf.rb
Created

  • Download Gist
alialsahaf.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
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.