需要帮助以了解递归示例 [英] Need help to understand an example of recursion

查看:71
本文介绍了需要帮助以了解递归示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解一个用JavaScript编写的示例.实际上,我正在阅读 Eloquent JavaScript 这本书,但在阅读有关递归的主题时却陷入困境.

I was trying to understand an example written in JavaScript. Actually, I'm reading the book Eloquent JavaScript, but got stuck while reading a topic about recursion.

这是该示例的语句:

从数字1开始,反复添加5或乘以3,可以生成无穷多个数字.如何您会写一个给定数字的函数,试图找到一个这种加法和乘法的顺序产生了数字?

By starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite set of numbers can be produced. How would you write a function that, given a number, tries to find a sequence of such additions and multiplications that produces that number?

这是示例代码:

function findSolution(target) {
  function find(current, history) {
    if (current == target) {
      return history;
    } else if (current > target) {
      return null;
    } else {
      return find(current + 5, `(${history} + 5)`) || 
             find(current * 3, `(${history} * 3)`);
    }
  }
  return find(1, "1");
}

推荐答案

递归函数将自行调用,直到分支满足不自行调用的条件为止.

A recursive function calls itself until the branch meets a condition where it doesn't call itself.

在这种情况下,当当前值等于或大于初始目标值时,链停止.

In this case the chain stops when the current value equals or is higher than the initial target value.

但是我认为当电流等于目标值时,它应该返回null.

But I think that it should return null when the current equals the target.

使用一些额外的日志记录,可以更好地跟踪发生的情况.

With some extra logging one can follow better what happens.

在下面的代码段中,当达到目标11时,它以null退出.
并且由于结果为空,因此将其乘以3得到最终解.

In the snippet below, it exits with null when it meets the target of 11.
And because the result is null, it multiplies by 3 to get the final solution.

function findSolution(target) {

  function find(current, step, action) {
    console.log('step: '+step, '\taction: '+action, '\tcurrent: '+current);
    step++;
    if (current == target) {
       console.log(current+'='+target+' so exit with null')
       return null;
    } else if (current > target) {
       return current;
    } else {
      return find(current + 5, step, '+ 5') || find(current * 3, step, '* 3');
    }
  }

  return find(1, 0, 'start');
}

console.log(findSolution(11));

这篇关于需要帮助以了解递归示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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