Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Forked from felipeelias/polynomial.rb
Created November 27, 2009 02:13
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save RLGGHC/4a4faf8e984208025ac6 to your computer and use it in GitHub Desktop.
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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment