secret
Last active — forked from sriram/sriramvarahan.rb

  • Download Gist
sriramvarahan.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
=begin
Title: Ruby Challenge #4
Program Description: Constructing a polynomial given the coefficients
Submitted By: Sriram Varahan
=end
 
class Polynomial
##
# Initialize the coefficients instance variable.
# raise "ArgumentError" Exception in case the number of coefficients are less than two/
#
def initialize(args)
raise ArgumentError, "Need at least two coefficients!", caller[1..-1] if args.length < 2
@coefficients = args
end
 
##
# This is the method where the polynomial is constructed.
# The way the method works is as follows:
# The output variable is an array which holds each term for e.g. "3x^5"
# The coefficients array is reversed so that the index value would give the number to be raised to.
# For example: consider input as [2,5,6,7]
# Reversing this would give us : [7,6,5,2]
# Now we just need to raise x to the index corresponding to the numbers.
# 7x^0(illustration), 6x^1 and so on...
# Now for each value we calculate the sign and the variable part keeping in mind values of 1 and 0.
# We don't assign a "+" sign in case the number is negative.
# Now the output holds the terms in the reverse order.
# We return the output after reversing it, removing the "+" from the first term and converting it to string.
#
def construct_polynomial
output = []
@coefficients.reverse!
 
@coefficients.each_with_index do |coefficient,index|
# In case of a negative number the sign is already present.
sign = (coefficient.to_i < 0) ? "" : "+"
unless coefficient.to_i == 0
variable_part = index != 0 ? (index == 1 ? "x" : "x^#{index}") : ""
case
when coefficient.to_i == -1 then coefficient = "-"
# Remove 1 form places where there is no variable part.
# Example : 3x^2 + (remove 1)x + 1(keep 1)
when (coefficient.to_i == 1 && index != 0) then coefficient = ""
end
output << "#{sign}#{coefficient}#{variable_part}"
end
end
 
output = output.reverse
output << "0" if output.empty?
# Remove "+" from the first term
output[0] = output[0].gsub("+","")
output = output.join("")
output
end
end
 
# Usage
puts Polynomial.new([-3,-4,1,0,6]).construct_polynomial
puts Polynomial.new([1,0,2]).construct_polynomial
puts Polynomial.new([0,0,0]).construct_polynomial
puts Polynomial.new([-1,-2,3,0]).construct_polynomial

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.