Instantly share code, notes, and snippets.

# RLGGHC/polynomial.rbSecret forked from felipeelias/polynomial.rb Created Nov 27, 2009

What would you like to do?
 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