Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Forked from enkrates/polynomial.rb
Created November 29, 2009 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RLGGHC/244711 to your computer and use it in GitHub Desktop.
Save RLGGHC/244711 to your computer and use it in GitHub Desktop.
class Polynomial
def initialize array
if array.length <= 1
raise ArgumentError.new('Need at least 2 coefficients')
exit
else
@return_string = ''
@iterations = array.length - 1
array.each do |item|
if @iterations > 1
@this_iteration = "^#{@iterations}"
else
@this_iteration = ''
end
if item.abs > 0
if item > 1
if @return_string.empty?
@item_string = "#{item}"
else
@item_string = "+#{item}"
end
elsif item < -1
@item_string = "#{item}"
elsif (item == 1)
if @return_string.empty?
@item_string = ''
else
@item_string = '+'
end
elsif item == -1
@item_string = '-'
end
if @iterations > 0
@item_string = "#{@item_string}x"
end
@return_string << "#{@item_string}#{@this_iteration}"
end
@iterations = @iterations - 1
end
if @return_string.empty?
@return_string = '0'
end
end
end
def to_s
@return_string
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment