Clearing a counter after each function call: JavaScript Recursive function

核能气质少年 提交于 2019-12-31 05:43:06

问题


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);
    });

回答1:


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



回答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

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


来源:https://stackoverflow.com/questions/43690023/clearing-a-counter-after-each-function-call-javascript-recursive-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!