secret
Created

  • 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
class Polynomial
def initialize(coefficients)
raise(ArgumentError, "Need at least 2 coefficients") if coefficients.size < 2
@coefficients = coefficients
end
def to_s
return "0" if @coefficients.all? { |c| c == 0 }
polynomial = ""
@coefficients.each_with_index do |coefficient, index|
unless coefficient.zero?
operator = coefficient > 0 ? "+" : "-"
absolute = coefficient.abs
exponential = @coefficients.size - index - 1
polynomial << operator if index > 0 or operator == "-"
polynomial << "#{absolute}" if (absolute > 1) or (exponential == 0 and absolute == 1)
polynomial << "x" if exponential >= 1
polynomial << "^#{exponential}" if exponential > 1
end
end
polynomial
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 31 32 33 34 35 36 37 38 39
require 'rubygems'
require 'spec'
require 'polynomial'
 
describe Polynomial do
context "creating a polynomial" do
it "should raise an error if arguments size < 2" do
lambda { Polynomial.new([1]) }.should raise_error("Need at least 2 coefficients")
end
it "should return 0 if all coefficients are 0" do
Polynomial.new([0, 0, 0]).to_s.should == "0"
end
it "should create a simple positive polynomial" do
Polynomial.new([2, 2]).to_s.should == "2x+2"
Polynomial.new([2, 2, 2]).to_s.should == "2x^2+2x+2"
Polynomial.new([4, 2, 2, 5]).to_s.should == "4x^3+2x^2+2x+5"
end
 
it "should ommit exponential 1 unless last" do
Polynomial.new([1, 2, 2]).to_s.should == "x^2+2x+2"
Polynomial.new([2, 1, 2]).to_s.should == "2x^2+x+2"
Polynomial.new([2, 2, 1]).to_s.should == "2x^2+2x+1"
end
it "should not print if coefficient is 0" do
Polynomial.new([2, 0, 2]).to_s.should == "2x^2+2"
Polynomial.new([2, 2, 0]).to_s.should == "2x^2+2x"
end
it "should print negative coefficients correctly" do
Polynomial.new([-5, 3, 1]).to_s.should == "-5x^2+3x+1"
Polynomial.new([ 5, -3, 1]).to_s.should == "5x^2-3x+1"
Polynomial.new([ 5, 3, -1]).to_s.should == "5x^2+3x-1"
Polynomial.new([-1, 3, -1]).to_s.should == "-x^2+3x-1"
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.