Skip to content

Instantly share code, notes, and snippets.

/alialsahaf.rb Secret

Created November 30, 2009 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/9ceb60fa43049089d3fd to your computer and use it in GitHub Desktop.
Save anonymous/9ceb60fa43049089d3fd to your computer and use it in GitHub Desktop.
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