public
Last active — forked from jamesdaniels/polynomial.rb

  • Download Gist
polynomial.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Polynomial
def initialize(coefficients)
@coefficients = coefficients
@highest_exponent = coefficients.size-1
raise ArgumentError, 'Need at least 2 coefficients' if @highest_exponent < 1
@sprintf = ['%ix^%i'] + ['%+ix^%i']*(coefficients.size-2) << '%+i'
end
def to_s
@coefficients.to_enum(:each_with_index).inject([]) {|builder, (coefficient, index)|
builder.push coefficient == 0 ?
builder.compact.size == 0 && index == @highest_exponent && '0' || nil : # Push zero at the end, if empty
(@sprintf[index] % [coefficient, @highest_exponent-index]) # Use the format specified in @sprintf
}.join.
gsub(/(^|\+|-)1{1}x/, '\1x'). # Clean out 1x
gsub(/x\^1{1}($|\+|-)/, 'x\1') # Clean out x^1
end
end
polynomial_test.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
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])
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 zero_up_front
assert_equal("5x^4+4x^3+3x^2+2x+1", @p6.to_s)
end
def testing_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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.