Clearing A Counter After Each Function Call: Javascript Recursive Function
Solution 1:
You need to return the result of each recursive call and handle the else case.
Try this:
functionpersistence(num, counter = 0) {
if (num.toString().length != 1) {
num = num.toString().split("").filter(Number).reduce((a, b) => a * b);
returnpersistence(num, ++counter);
} else {
return counter;
}
}
Here are the results from console:
> persistence(25)
< 2
> persistence(999)
< 4
Solution 2:
I'm assuming you're trying to compute multiplicative digital root but that does not remove zeroes from the computation as you're doing with .filter(Number)
above. Below, we write multiplicativeRoot
which returns an array of the steps it takes to reduce a number to a single digit
Finally, the multiplicative persistence can be computed by simply counting the number of steps in the return value from multiplicativeRoot
and subtracting 1
(the first value in the result is always the input value)
The result is an implementation of multiplicativePersistence
that is made up of several functions, each with their distinct and clear purpose
constdigits = n =>
n < 10
? [ n ]
: digits (n / 10 >> 0) .concat ([ n % 10 ])
constmult = (x,y) =>
x * y
constproduct = xs =>
xs.reduce (mult, 1)
constmultiplicativeRoot = x =>
x < 10
? [ x ]
: [ x ] .concat (multiplicativeRoot (product (digits (x))))
constmultiplicativePersistence = x =>
multiplicativeRoot (x) .length - 1console.log (multiplicativeRoot (999)) // [ 999, 729, 126, 12, 2 ]console.log (multiplicativePersistence (999)) // 4console.log (multiplicativeRoot (25)) // [ 25, 10, 0 ]console.log (multiplicativePersistence (25)) // 2
Post a Comment for "Clearing A Counter After Each Function Call: Javascript Recursive Function"