Instantly share code, notes, and snippets.

anonymous /isleyaardvark2.rb Secret
Created Dec 17, 2009

What would you like to do?
# This class prepares a pretty-print version of a polynomial with a minimum of 2 coefficients
class Polynomial
# Create the polynomial object and store the coefficients
def initialize(coefficients)
raise ArgumentError, "Need at least 2 coefficients" if coefficients.length < 2
@coefficients = coefficients
# Returns a string version of the polynomial, simplifies coefficients of 1x^n to x^n,
# simplifies x^1 to x and ax^0 to a. Doesn't include elements with a coefficient of 0.
# If all coefficients = 0, returns "0".
def to_s
polynomial = []
@coefficients.each_with_index do |coefficient, index|
polynomial << coefficient.to_s + "x^" + (@coefficients.length - 1 - index).to_s
if @coefficients.all? { |coefficient| }
polynomial_string = "0"
polynomial_string = polynomial.join("+")\
.gsub(/\+\-/, '-')\
.gsub(/(^|[\+\-])[1]x/, '\1x')\
.gsub(/(^|[\+\-])[0]x\^[(0-9)+]/, '')\
.gsub(/x\^1([\+\-]|$)/, 'x')\
.gsub(/x\^0/, '')
# ^| in regex handles case where 1x is at beginning of line, otherwise it's -1x and is covered by rest of regex
return polynomial_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment