secret
Created — forked from milandobrota/polynomial.rb

  • Download Gist
polynomial.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
class ArgumentError < StandardError; end
 
class Polynomial
def initialize(coefficients)
raise ArgumentError.new("Need at least 2 coefficients") if coefficients.size < 2
@addends = []
size = coefficients.size
coefficients.each_with_index do |coef, index|
unless coef == 0
if index == size-1
@addends << "#{coef}"
elsif index == size -2
@addends << "#{coef}x"
elsif coef == 1
@addends << "x^#{size-index-1}"
elsif coef == -1
@addends << "-x^#{size-index-1}"
else
@addends << "#{coef}x^#{size-index-1}"
end
end
end
end
 
def to_s
@addends.empty? ? 0.to_s : @addends.join("+").gsub("+-", "-")
end
end
polynomial_spec.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
require 'polynomial'
 
describe Polynomial do
before do
@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
it "should test first negative" do
@p1.to_s.should == "-3x^4-4x^3+x^2+6"
end
it "should test simple" do
@p2.to_s.should == "x^2+2"
end
it "should test first minus one" do
@p3.to_s.should == "-x^3-2x^2+3x"
end
it "should test all zero" do
@p4.to_s.should == "0"
end
it "should test error" do
lambda{ Polynomial.new([1])}.should raise_error(ArgumentError, /Need at least 2 coefficients/)
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.