Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@RLGGHC
Forked from eregon/benoitdaloze.rb
Created December 6, 2009 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RLGGHC/400492a2e4a4a966497f to your computer and use it in GitHub Desktop.
Save RLGGHC/400492a2e4a4a966497f to your computer and use it in GitHub Desktop.
# Benoit Daloze
# Ruby Programming Challenge For Newbies #4
# pretty-print polynomials
#
# My solution use Enumerable#inject to build the String,
# with every "monomial" splitted in 3 parts : sign, coefficient and variable
class Polynomial
def initialize(coef)
raise ArgumentError, "Need at least 2 coefficients" if coef.size < 2
@coef = coef
end
def to_s
return '0' if @coef.all? { |c| c == 0 }
(0...@coef.length).inject("") { |s, i|
coef, pow = @coef[i], @coef.length-1-i
if coef == 0
s
else
s +
(coef > 0 ? '+' : '-') + # sign
(coef.abs == 1 && pow != 0 ? '' : coef.abs.to_s) + # coef
(pow < 2 ? 'x'*pow : "x^#{pow}") # var
end
}.sub(/^\+/, "")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment