Skip to content

Instantly share code, notes, and snippets.

@PedroDiogo
Created November 26, 2009 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PedroDiogo/e146009c5254054bf462 to your computer and use it in GitHub Desktop.
Save PedroDiogo/e146009c5254054bf462 to your computer and use it in GitHub Desktop.
RPCFN: Ruby**Fun (#4) submisson

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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment