/polynomial_alech.rb Secret
Created
November 30, 2009 00:38
-
-
Save RLGGHC/2eb3e419c644fdf8814c 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
class Fixnum | |
# returns '+' for positive numbers, '-' for negative and '' for 0 | |
def sign | |
case self <=> 0 | |
when 0 | |
then '' | |
when 1 | |
then '+' | |
when -1 | |
then '-' | |
end | |
end | |
end | |
class Polynomial | |
def initialize(coefficients) | |
if coefficients.size < 2 then | |
raise ArgumentError, "Need at least 2 coefficients." | |
end | |
@coefficients = coefficients | |
end | |
# String representation of the object | |
def to_s | |
result = '' | |
@coefficients.reverse.each_with_index do |c, exp| | |
# ignore the ones with 0 as coefficient | |
next if c == 0 | |
result = c.sign + formatted_coeff_abs(c) + x_to_n(exp) + result | |
end | |
# if the result starts with a '+', we should strip it | |
result.sub!(/^\+/, '') | |
# if the result is empty, it is the constant 0 polynomial | |
result == "" ? "0" : result | |
end | |
private | |
# 'x^n' for n > 1, 'x' for n == 1 and '' for n == 0 | |
def x_to_n(n) | |
case n | |
when 1 | |
then "x" | |
when 0 | |
then "" | |
else "x^#{n}" | |
end | |
end | |
# The absolute value of the coefficient as a string, the empty | |
# string if the coefficient is 1 | |
def formatted_coeff_abs(coefficient) | |
coefficient.abs == 1 ? "" : coefficient.abs.to_s | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment