patternrubyMinor
Polynomial equation solver in Ruby
Viewed 0 times
solverequationrubypolynomial
Problem
I've written a small function for solving simple quadratic equations:
To calculate
However, is there a more elegant version of my function, more like
class EquationSolver
def solve(x, *args)
args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.reduce { |result, element| result + element }
end
endTo 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:
It's possible to do this because iterator methods like
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.each_with_index.reduce(0) { |result, (coefficient, index)| result + coefficient * x ** index }
end
endIt'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
endCode Snippets
class EquationSolver
def solve(x, *args)
args.reverse.each_with_index.reduce(0) { |result, (coefficient, index)| result + coefficient * x ** index }
end
endclass EquationSolver
def solve(x, *args)
args.reverse.map.with_index { |coefficient, index| coefficient * x ** index }.inject(:+)
end
endContext
StackExchange Code Review Q#35810, answer score: 2
Revisions (0)
No revisions yet.