Instantly share code, notes, and snippets.

# jamesdaniels/polynomial.rb Created Nov 26, 2009

What would you like to do?
 class Polynomial def initialize(coefficients) @coefficients = coefficients.reverse # reverse so the index equates to the exponent of each coefficient raise ArgumentError, 'Need at least 2 coefficients' if coefficients.size < 2 end def to_s # Build an array of sprintfs, LIFO to get most significant order @coefficients.inject([]) {|builder, coefficient| ["%+ix^%i" % [coefficient, builder.size]] + builder}.to_s. gsub(/(\+0x\^\d+|x\^0|\^1\d{0})/, ''). # Clean out 0x^y, x^0, ^1 gsub(/\d{0}1x/, 'x'). # Replace 1x with just x sub(/^\+/, ''). # Remove leading + sub(/^\$/, '0') # 0 when blank 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([6,5,4,3,2,1]) @p6 = Polynomial.new([0,5,4,3,2,1]) @p7 = Polynomial.new([1,0]) @p8 = Polynomial.new([1,0,0]) @p9 = Polynomial.new([1,1,1,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_last_is_one assert_equal("6x^5+5x^4+4x^3+3x^2+2x+1", @p5.to_s) end def test_zero_up_front assert_equal("5x^4+4x^3+3x^2+2x+1", @p6.to_s) end def test_lots_of_ones assert_equal("x^4+x^3+x^2+x", @p9.to_s) end def test_short assert_equal("x", @p7.to_s) end def test_all_zero assert_equal("0", @p4.to_s) end def test_last_two_zero assert_equal("x^2", @p8.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)