class Polymath::Nomial::Parser

Constants

AllowedCharacters

Public Class Methods

guess_variable(polynomial) click to toggle source

@brief guesses which variable the user meant by frequency

@return string of length 1

# File lib/polymath/nomial/parser.rb, line 50
def self.guess_variable(polynomial)
  variables = polynomial.monomials.select { |monomial|
    monomial.var != "?"
  }.map { |monomial| monomial.var }

  if variables.length == 0
    "x"
  else
    variables.uniq.map { |char|
      {
        count: variables.count(char),
        char:  char
      }
    }.sort_by { |c| -c[:count] }.first[:char]
  end
end
parse(exp) click to toggle source

@brief parses a string polynomial expression

@param exp the string polynomial expression

@return an array of monomials

# File lib/polymath/nomial/parser.rb, line 27
def self.parse(exp)
  self.strip(exp).split(/\+|(?=-)/).map { |monomial|
    monomial.split(/(?=[[:alpha:]])/).map { |token|
      if /[[:alpha:]]/.match?(token)
        Monomial.new(
          var: token.scan(/[[:alpha:]]/).join,
          deg: /\^/.match?(token) ? Integer(token.scan(/\^(.*)/).join) : 1,
          cof: /\-/.match?(token) ? -1 : nil
        )
      elsif /\d/.match?(token)
        Monomial.new(cof: Integer(token))
      elsif token == "-"
        Monomial.new(cof: -1)
      end
    }.compact.reduce(:merge!)
  }
end
sanitize(exp) click to toggle source
# File lib/polymath/nomial/parser.rb, line 8
def self.sanitize(exp)
  exp.gsub(/(?!#{AllowedCharacters})./, '')
end
set_variable(exp, variable) click to toggle source
# File lib/polymath/nomial/parser.rb, line 12
def self.set_variable(exp, variable)
  exp.gsub(/[[:alpha:]]/, variable)
end
strip(exp) click to toggle source
# File lib/polymath/nomial/parser.rb, line 16
def self.strip(exp)
  exp.gsub(/\s/, '')
end