【问题标题】:How can I declare a counter inside of my recursive function? (Additive Persistence: Coderbyte)如何在递归函数中声明一个计数器? (附加持久性:Coderbyte)
【发布时间】:2015-06-16 18:16:21
【问题描述】:

在解决一些 Coderbyte 挑战时,我能够递归地解决以下问题,但希望获得一些关于如何改进它的反馈。

让函数 AdditivePersistence(num) 接受传递的 num 参数,该参数始终为正整数,并返回其加法持久性,即您必须在 num 中添加数字直到达到单个数字的次数。

例如:如果 num 是 2718,那么您的程序应该返回 2,因为 2 + 7 + 1 + 8 = 18 和 1 + 8 = 9,然后你在 9 点停止。

我提交的有效递归解决方案如下。如何在每次递归时将“计数”放入我的函数中而不让它“重置”?

var count = 0;
function AdditivePersistence(num) {
  count = 0;
  if (num < 10) {
    return count;
  }
  if (num > 10) {
    count++;
    AdditivePersistence('' + num.split("").reduce(function(a,b) {
      return parseInt(a) + parseInt(b)
    }));
  }
}

这是我在函数内移动计数器的失败尝试......希望为我的初学者自己提供任何指点。除了修复代码之外,如果还有其他解决这个难题的好方法,我会很高兴!

function AdditivePersistence(num) {
  var count = 0;
  (function recurse(num) {
      if (num < 10) {
      return count;
      }
      if (num > 10) {
        count++;
        recurse('' + num.split("").reduce(function(a,b) {
        return parseInt(a) + parseInt(b);
        }));
      }
    })();
  return count;
}

编辑:我刚刚尝试了下面的 while 循环

function AdditivePersistence(num) {
  var count = 0;
  while (num >= 10) {
    count++
    num = num.toString().split('').reduce(function(a,b) {
      return parseInt(a) + parseInt(b);
    })}
  return count;          
}

提前非常感谢!

【问题讨论】:

  • 使用尾递归(即,将“累加器”变量作为递归函数的最后一个参数传递)。
  • 在您的第一个代码块中,您通过重新声明它来隐藏外部计数变量。
  • 你的问题是var count = 0; 的范围,你以某种方式期望它是全球性的。
  • 请注意num &lt; 10num &gt; 10 并未涵盖num 的所有可能值。
  • 大家好 - 很抱歉,我的实际代码没有在函数(第一个代码块)中声明计数 - 这是我转移到这里的错误,抱歉。

标签: javascript algorithm recursion


【解决方案1】:

想法很简单

AdditivePersistence(n):
   if n < 10
      return 0
   else
      return 1 + AdditivePersistence(sum-of-digits(n))

严格来说,这里不需要递归 - 这本质上是一个普通的 while 循环。

【讨论】:

  • 严格来说,我认为你永远需要递归。任何带有递归的东西都应该可以作为迭代循环重写。
  • 谢谢,我实现了一个 while 循环并编辑了我的原始帖子。我想我想了解如何在递归情况下“保护”计数器。
【解决方案2】:

我将扩展@georg 的答案并提供完整的实现

var additivePersistance = (function () {
    function sumOfDigits (n) {
        var ret = 0;
        n.toString().split('').forEach(function (i) {
            ret += parseInt(i, 10);
        });
        return ret;
    }
    return function additivePersistance (n) {
        if (n < 10) {
            return 0;
        }
        return additivePersistance(sumOfDigits(n)) + 1;
    }
}());

此实现使用闭包将 sumOfDigits 隐藏为辅助方法。

additivePersistance(2718); // 2

这个闭包思想也可以用来在递归函数中创建一个伪静态变量。按照这个表格。

var func = (function () {
    var staticCounter = 0;
    return function func() {
        if (staticCounter++ > 20) {
            return 0;
        }
        return func() + 1;
    };
}());

这里内部 func 方法的主体在对外部 func 的所有调用中使用变量 staticCounter。

【讨论】:

    【解决方案3】:
    var count = 0;
    
    function AdditivePersistence(num)
    {
        // make the number into a string so that each digit can be taken
        var num_string = num.toString();
        // this will hold each digit
        var numbers = [];
        // iterate through each digit as a character
        for(var i = 0; i < num_string.length; ++i)
        {
            // add the character converted to a number into the numbers array
            numbers.push(parseInt(num_string[i]));   
        }
        // this will hold the value of all the digits added together
        var total = 0;
        // iterate through the digits
        for(var i = 0; i < numbers.length; ++i)
        {
            // add each digit to the total
            total += numbers[i];
        }
        // if larger than the total
        if(total > 10)
        {
            // increase the count
            ++count;
            // redo it again
            AdditivePersistence(total);
        }
        else
        {
            // return the total amount of tries
            return (++count);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      相关资源
      最近更新 更多