Clearing a counter after each function call: JavaScript Recursive function

I have the folllowing solution to a problem relating to multiplicative persistence. However, I need to wipe the counter after each function call. I have tried different return statements, counters and arrays.

I don't seem to be able to clear the counter after each function call AND get the correct answer. It is adding all the answers from multiple function calls.

function persistence(num, counter = 0) {
        if (num.toString().length != 1) {
            num = num.toString().split("").filter(Number).reduce((a, b) => a * b);
            persistence(num, ++counter);
        }
return counter;
}


persistence(999) // Answer should be 4.
persistence(25)// Answer should be 2 not 6 or 1.

The tests here:

describe('Initial Tests', function () {
      Test.assertEquals(persistence(39),3);
      Test.assertEquals(persistence(4),0);
      Test.assertEquals(persistence(25),2);
      Test.assertEquals(persistence(999),4);
    });

Answers:

Answer

You need to return the result of each recursive call and handle the else case.

Try this:

function persistence(num, counter = 0) {
  if (num.toString().length != 1) {
    num = num.toString().split("").filter(Number).reduce((a, b) => a * b);
    return persistence(num, ++counter);
  } else {
    return counter;
  }
}

Here are the results from console:

> persistence(25)
< 2
> persistence(999)
< 4
Answer

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

const digits = n =>
  n < 10
    ? [ n ]
    : digits (n / 10 >> 0) .concat ([ n % 10 ])

const mult = (x,y) =>
  x * y

const product = xs =>
  xs.reduce (mult, 1)

const multiplicativeRoot = x =>
  x < 10
    ? [ x ]
    : [ x ] .concat (multiplicativeRoot (product (digits (x))))
  
const multiplicativePersistence = x =>
  multiplicativeRoot (x) .length - 1
  
console.log (multiplicativeRoot (999))        // [ 999, 729, 126, 12, 2 ]
console.log (multiplicativePersistence (999)) // 4


console.log (multiplicativeRoot (25))         // [ 25, 10, 0 ]
console.log (multiplicativePersistence (25))  // 2

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.