Skip to content

Instantly share code, notes, and snippets.

@enkrates
Created November 28, 2009 14:52
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 enkrates/244539 to your computer and use it in GitHub Desktop.
Save enkrates/244539 to your computer and use it in GitHub Desktop.
class Polynomial
def initialize array
if array.length < 2
raise ArgumentError.new('Need at least 2 coefficients')
exit
end
@result = ''
@iterations = 1
array.each do |item|
if item.abs > 0
@result << "+#{item}x^#{array.length - @iterations}"
end
@iterations += 1
end
@result.gsub!(/1x/, 'x')
@result.gsub!(/x\^0/, '')
@result.gsub!(/x\^1$|x\^1((\+|\-)\d)/, 'x\1')
@result.gsub!(/\+\-/, '-')
@result.gsub!(/\A\+/, '')
end
def to_s
@result != '' ? @result : '0'
end
end
# assuming that your solution is polynomial.rb
require 'test/unit'
require 'test/unit/ui/console/testrunner'
require 'polynomial'
class Polynomial_Test < Test::Unit::TestCase
def setup
@p1 = Polynomial.new([-3,-4,1,0,6])
@p2 = Polynomial.new([1,0,2])
@p3 = Polynomial.new([-1,-2,3,0])
@p4 = Polynomial.new([0,0,0])
@p5 = Polynomial.new([2,0,-1,-6,0,0,0,3,12])
@p6 = Polynomial.new([0, 0, 0, 0, 100])
@p7 = Polynomial.new([1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0])
end
def test_first_negative
assert_equal("-3x^4-4x^3+x^2+6", @p1.to_s)
end
def test_simple
assert_equal("x^2+2", @p2.to_s)
end
def test_first_minus_one
assert_equal("-x^3-2x^2+3x", @p3.to_s)
end
def test_all_zero
assert_equal("0", @p4.to_s)
end
def test_a_longer_polynomial_with_an_initial_positive_two
assert_equal("2x^8-x^6-6x^5+3x+12", @p5.to_s)
end
def test_one_hundred
assert_equal("100", @p6.to_s)
end
def test_fifteen
assert_equal("x^15+x", @p7.to_s)
end
def test_error
e = assert_raise(ArgumentError) { Polynomial.new([1]) }
assert_match(/Need at least 2 coefficients/, e.message)
end
end
Test::Unit::UI::Console::TestRunner.run(Polynomial_Test)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment