Skip to content

Instantly share code, notes, and snippets.

@srps
Created December 11, 2009 07:18
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 srps/8a3c28f2907ccffb8cc8 to your computer and use it in GitHub Desktop.
Save srps/8a3c28f2907ccffb8cc8 to your computer and use it in GitHub Desktop.
RPCFN #4 entry
# I've attached the tests to the bottom of this class also, might come in handy
class Polynomial
def initialize(poly)
coef, @result= poly.length, "" # let's create some vars we'll need
raise ArgumentError, "Need at least 2 coefficients" if coef < 2 # if you try to make a monomial...boom!
poly.each do |item| # let's treat the array with a nice block encasing
coef -= 1
@result << ("#{'+' unless item < 1 || @result == ""}" << # puts '+' when number isn't negative or leading
"#{item == -1 ? "-" : "" }#{item.to_s if item.abs > 1}" << # negatives already come with sign
(item.zero? ? "" : "#{case coef when 1 then "x" when 0 then "" else "x^" end}" << # eliminate zero coeffs' x, zero multipliers, write only needed stuff
"#{coef.to_s unless coef < 2}")) # puts the coefficient when applicable (above 1)
end
@result = "0" if @result.eql? "" # Could've been done in the poly block, but it's cleaner & faster this way
end
def to_s
@result # result already comes nicely formatted in a string, let's display it
end
end
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([-1,0,12,0,-2,0,0,1,-9])
@p6 = Polynomial.new([0,0,1,5,6])
@p7 = Polynomial.new([-4.1,0,-5.45])
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_lots_of_zeros
assert_equal("-x^8+12x^6-2x^4+x-9", @p5.to_s)
end
def test_leading_zeros
assert_equal("x^2+5x+6", @p6.to_s)
end
def test_non_integers
assert_equal("-4.1x^2-5.45", @p7.to_s)
end
def test_error_coef_number
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