secret
Last active

  • Download Gist
gistfile1.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
# 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])
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_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)
marcminneman.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
class Polynomial < String
def initialize(coefficient_array)
raise ArgumentError, "Need at least 2 coefficients." if coefficient_array.length < 2 #minimum term count
expression = ''; coefficient_array.each_with_index {|c,i| expression += build_term(c,coefficient_array.length-(i+1))} #build expression one term at a time
super(expression.sub(/^\+/,'').sub(/^$/,'0')) # tidy up: (1) remove starting plus sign (2) handle empty expression.
end
private
def build_term(c,e) # c = coefficient : e = current exponent
# build the term only if coefficient is no equal to zero
c != 0 ? "#{build_sign(c)}#{build_coefficient(c)}#{build_variable(e)}#{build_exponent(e)}" : ''
end
def build_sign(c)
c > 0 ? '+' : '-'
end
def build_coefficient(c)
# coefficient is supressed if 1 or -1
c.abs!=1 ? c.abs : ''
end
def build_variable(e)
# variable is supressed if exponent is 0
e>0 ? 'x' : ''
end
def build_exponent(e)
# exponent is supressed if 1 or 0
e>1 ? "^#{e}" : ''
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.