Class: Polymath::Nomial::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/polymath/nomial/parser.rb

Class Method Summary collapse

Class Method Details

.guess_variable(polynomial) ⇒ Object

Returns string of length 1.

Returns:

  • string of length 1



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 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) ⇒ Object

Returns an array of monomials.

Parameters:

  • exp

    the string polynomial expression

Returns:

  • an array of monomials



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 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) ⇒ Object



8
9
10
# File 'lib/polymath/nomial/parser.rb', line 8

def self.sanitize(exp)
  exp.gsub(/(?!#{AllowedCharacters})./, '')
end

.set_variable(exp, variable) ⇒ Object



12
13
14
# File 'lib/polymath/nomial/parser.rb', line 12

def self.set_variable(exp, variable)
  exp.gsub(/[[:alpha:]]/, variable)
end

.strip(exp) ⇒ Object



16
17
18
# File 'lib/polymath/nomial/parser.rb', line 16

def self.strip(exp)
  exp.gsub(/\s/, '')
end