-
-
Save RLGGHC/5b8b7c511047805c9087 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 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 |
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment