secret
Last active

RPCFN: Ruby**Fun (#4) submisson

  • Download Gist
README.rdoc
RDoc

RPCFN: Ruby**Fun (#4)

This is my submission for the RPCFN: Ruby**Fun (#4)

rubylearning.com/blog/2009/11/26/rpcfn-rubyfun-4/

Explanation

The algorithm implemented is trying to be as simple yet readable as possible

  • Iterates every coefficient in the input array. If the coefficient is non zero, performs a number of actions on it.

Usage

>> require 'Polynomial'
>> puts Polynomial.new([-2,-3,-4,-5])
   -2x^3-3x^2-4x-5
pedrodiogo.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
class Polynomial
def initialize(input)
raise ArgumentError, "Need at least 2 coefficients" if input.size < 2
 
@input, @output = input, String.new
process
end
 
def to_s
@output
end
def process
@input.each_index do |n|
unless @input[n] == 0
degree = @input.size - n - 1 # degree of the coefficient
@output << '+' if @input[n] > 0 && !@output.empty? # Prevents adding '+' in the begginning
@output << '-' if @input[n] < 0
@output << @input[n].abs.to_s if @input[n].abs != 1 || degree == 0 # Prevents adding '1' unless the degree is 0
@output << 'x' if degree > 0
@output << '^' + degree.to_s if degree > 1
end
end
# If the output string is still empty, it means the polynomial is 0
@output = "0" if @output.empty?
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.