secret
anonymous / rohitsasikumar.rb
Created

  • Download Gist
rohitsasikumar.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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
require 'test/unit'
 
# Class for printing the polynomial in string form given the coefficients in an array.
# Assumptions: Coefficents are whole numbers only.
class Polynomial
def initialize (arg)
raise ArgumentError, "Need at least 2 coefficients" if arg.size < 2
@coefficients = arg
end
# Function for printing the polynomial
def to_s
# create an array of the variable and degrees. For eg, if the number of coefficients is 3, then the array of is ["x^3", "x^2", "x", ""]
variable_degree = Array.new(@coefficients.size) {|i| i}
variable_degree.reverse!.collect! do|i|
if i == 1
"x"
elsif i >= 1
"x^#{i}"
end
end
variable_degree.compact!
variable_degree << ""
# make a sum of the terms of the polynomial using the coefficients and the variable_degree array
expr = @coefficients.inject('') do |sum,obj|
if obj == 0
variable_degree.shift
next sum
elsif obj == 1
asd = '+'
elsif obj == -1
asd = '-'
elsif obj > 1
asd = '+' + obj.to_s
else
asd = obj.to_s
end
sum + asd + variable_degree.shift
end
expr = "0" if expr.eql? "" # If result is "" string then make it "0"
expr.sub!(/^\+/,'') # remove the leading '+' sign
expr
end
end
 
# unit tests for testing the Polynomial class
class Polynomial_Test < Test::Unit::TestCase
def setup
@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
def test_first_negative
assert_equal("-3x^4-4x^3+x^2+6", @p1.to_s)
end
def test_simple
assert_equal("x^2+2", @p2.to_s)
end
def test_first_minus_one
assert_equal("-x^3-2x^2+3x", @p3.to_s)
end
def test_all_zero
assert_equal("0", @p4.to_s)
end
def test_error
e = assert_raise(ArgumentError) { Polynomial.new([1]) }
assert_match(/Need at least 2 coefficients/, e.message)
end
def test_misc
assert_equal("-x^3+2x^2-3x-4", Polynomial.new([-1,2,-3,-4]).to_s)
assert_equal("x^4+3x^2+5", Polynomial.new([0,1,0,3,0,5]).to_s)
assert_equal("9x^5", Polynomial.new([9,0,0,0,0,0]).to_s)
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.