每次函数调用后清除计数器:JavaScript递归函数 [英] Clearing a counter after each function call: JavaScript Recursive function

查看:134
本文介绍了每次函数调用后清除计数器:JavaScript递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于与乘法持久性有关的问题,我有以下解决方案.但是,我需要在每次函数调用后擦除计数器. 我尝试了不同的return语句,计数器和数组.

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.

此处的测试:

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

推荐答案

我假设您正在尝试计算

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

最后,可以通过简单地计算步骤中的步骤数来计算乘法持久性.从multiplicativeRoot返回值并减去1(结果中的第一个值始终是输入值)

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)

结果是multiplicativePersistence的实现,该实现由几个功能组成,每个功能都有其明确的目的

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

这篇关于每次函数调用后清除计数器:JavaScript递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆