HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Polynomial equation solver in Ruby

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
solverequationrubypolynomial

Problem

I've written a small function for solving simple quadratic equations:

class EquationSolver
  def solve(x, *args)
    args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.reduce { |result, element| result + element }
  end
end


To calculate f(3) for f(x)=3x3−2x2−x+5, one would write:

puts EquationSolver.new.solve(3, 3, -2, -1, 5)


However, is there a more elegant version of my function, more like reduce.with_index or something similar?

Solution

Yes, there is a more elegant version. Here it is:

class EquationSolver
  def solve(x, *args)
    args.reverse.each_with_index.reduce(0) { |result, (coefficient, index)| result + coefficient * x ** index }
  end
end


It's possible to do this because iterator methods like each_with_index, when called without a block, return an Enumerator object on which you can call all the methods of the Enumerable.

In fact, an even shorter solution is obtained by using a variation of reduce to use a symbolic operator:

class EquationSolver
  def solve(x, *args)
    args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.inject(:+)
  end
end

Code Snippets

class EquationSolver
  def solve(x, *args)
    args.reverse.each_with_index.reduce(0) { |result, (coefficient, index)| result + coefficient * x ** index }
  end
end
class EquationSolver
  def solve(x, *args)
    args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.inject(:+)
  end
end

Context

StackExchange Code Review Q#35810, answer score: 2

Revisions (0)

No revisions yet.