-
-
Save sriram/24e6da4f93c6a7cd5ebc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment