-
-
Save RLGGHC/01fe546d4e7e93323413 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
# | |
# Design Goal: strike a balance between terseness and readability | |
# | |
# I always hear Ruby developers saying Ruby code doesn't need commenting. But for | |
# me, no matter how well you might name those routines routines or or write | |
# your code, if you pair a comment clearly stating intent of the routine, | |
# it is always easier to quickly wrap one's head around what a block of code is | |
# *supposed* to be doing and you can answer the question, "does this code do what | |
# the author thinks its doing?" I'm still learning Ruby and I don't translate Ruby | |
# into a clear mental model instantly, but I generally do interpret comments quite quickly! | |
# | |
# Another readability enhancement is the use of parentheses to enhance readablity even when | |
# they're not strictly required, and the use of whitespace, such as blank line between | |
# guard statements that exit a routine early and the rest of the routine. Unlike other languages | |
# that might always require parentheses for conditionals or blocks, I've come to love | |
# the fact that Ruby can omit them because now when they're present, they have a semantic | |
# meaning to me, much like punctuation does in a sentence! | |
# | |
class Polynomial | |
## | |
# pair each given coefficient with its respective exponential as [coeff, exp], removing zeroes | |
def initialize(coefficients) | |
raise ArgumentError.new "Need at least 2 coefficients" if coefficients.size < 2 | |
@coefficients = coefficients.reverse | |
@coefficients.each_with_index{ |c, i| @coefficients[i] = (c == 0 ? nil : [c, i]) } | |
@coefficients.reverse!.compact! | |
end | |
## | |
# make 1 and -1 implicit | |
def multiplier_to_s(coefficient) | |
coefficient[0] == 1 ? "" : coefficient[0] == -1 ? "-" : coefficient[0].to_s | |
end | |
## | |
# only raise to power if exp is > 0 | |
def exp_to_s(coefficient) | |
coefficient[1] == 0 ? "" : coefficient[1] == 1 ? "x" : "x^#{coefficient[1]}" | |
end | |
## | |
# return "+" only when there is no prefix and the coefficient is positive | |
def sign_to_s(prefix, coefficient) | |
(prefix == '' || coefficient[0] < 0) ? '' : "+" | |
end | |
## | |
# output all coefficients for the polynominal in a human readable equation. | |
# Example: "-3x^4-4x^3+x^2+6" | |
def to_s | |
return "0" if @coefficients.empty? | |
@coefficients.inject("") do |str, c| | |
str << sign_to_s(str, c) << multiplier_to_s(c) << exp_to_s(c) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment