Skip to content

@RLGGHC /fabio_kreusch.rb secret forked from fabiokr/fabio_kreusch.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
class Polynomial
def initialize(values)
raise ArgumentError.new('Need at least 2 coefficients') unless !values.nil? && values.compact.size >= 2
@terms = to_terms(values.compact)
end
def to_s
return "0" if all_zero
@terms.reject { |t| t.value == 0 }.collect { |t| t.value < 0 || t == @terms.first ? t.to_s : "+#{t.to_s}" }.to_s
end
private
def to_terms(values)
power = values.size
@terms = values.collect {|v| Term.new(v, power-=1)}
end
def all_zero
@terms.each {|t| return false if t.value != 0}
return true
end
end
class Term
attr_reader :value, :power
def initialize(value, power, isFirstTerm = false)
@value, @power = value, power
end
def to_s
"#{format_value}#{format_power}"
end
private
def format_value
return "-" if value == -1
return "" if value == 1
return value
end
def format_power
return "" if power == 0
return "x" if power == 1
return "x^#{power}"
end
end
# 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.