Created
December 2, 2009 07:41
-
-
Save alg/247026 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Polynomial | |
def initialize(coefs) | |
if coefs.nil? || !coefs.kind_of?(Array) || coefs.size < 2 | |
raise ArgumentError, "Need at least 2 coefficients." | |
end | |
@coefs = coefs | |
end | |
def to_s | |
power = @coefs.size | |
parts = @coefs.map do |coef| | |
power -= 1 | |
coef = coef.to_i | |
unless coef == 0 | |
part = (power == 0 || coef.abs != 1) ? coef.to_s : (coef > 0 ? '' : '-') | |
part += (power == 0) ? '' : (power == 1) ? 'x' : "x^#{power}" | |
end | |
end.compact | |
return parts.empty? ? '0' : (parts.compact * '+').gsub('+-', '-') | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# assuming that your solution is polynomial.rb | |
require 'test/unit' | |
require 'test/unit/ui/console/testrunner' | |
require 'polynomial' | |
class PolynomialTest < Test::Unit::TestCase | |
def test_first_negative | |
assert_poly("-3x^4-4x^3+x^2+6", -3, -4, 1, 0, 6) | |
end | |
def test_simple | |
assert_poly("x^2+2", 1, 0, 2) | |
end | |
def test_first_minus_one | |
assert_poly("-x^3-2x^2+3x", -1, -2, 3, 0) | |
end | |
def test_all_zero | |
assert_poly("0", 0, 0, 0) | |
end | |
def test_last_one | |
assert_poly("x-1", 1, -1) | |
end | |
def test_error | |
e = assert_raise(ArgumentError) { Polynomial.new([1]) } | |
assert_match(/Need at least 2 coefficients/, e.message) | |
end | |
def assert_poly(result, *c) | |
assert_equal(result, Polynomial.new(c).to_s) | |
end | |
end | |
Test::Unit::UI::Console::TestRunner.run(PolynomialTest) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment