使用递归Javascript的数组总和 [英] sum of an array using recursion Javascript

查看:178
本文介绍了使用递归Javascript的数组总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一种通过递归sum()解决此问题的方法.现在,该代码可以正常工作,但是我应该多次调用sum(),并且它不应使输入数组发生变化.

Looking for a way to solve this problem by recursing sum(). Right now, the code works, but I am supposed to call sum() more than once, and it should not mutate the input array.

var sum = function(array) {
    if(array.length === 0){
        return 0;
    }
    function add(array, i){
        console.log(array[i]);
        if(i === array.length-1){
            return array[i];
        }
        return array[i] + add(array, i+1);
    }
    return add(array, 0);
};
sum([1, 2, 3, 4, 5, 6]) //21

推荐答案

满足您所有要求的单缸套:

A one-liner that meets all your requirements:

var sum = function(array) {
    return (array.length === 0) ? 0 : array[0] + sum(array.slice(1));
}

// or in ES6

var sum = (array) => (array.length === 0) ? 0 : array[0] + sum(array.slice(1));

// Test cases
sum([1,2,3]); // 6

var s = [1,2,3];
sum(s); // 6
sum(s); // 6

推理

  • 在递归调用中,您需要将任务建模为基本情况的 reduction .在这种情况下,最简单的基本情况是空数组-此时,您的函数应返回零.
  • 减少步骤应该是什么?好吧,您可以为数组的总和建模,作为将 first 元素添加到数组其余部分的sum的结果-在某些时候,这些连续的调用最终将导致对sum([]),您已经知道的答案.上面的代码正是这样做的.
  • array.slice(1) 创建以下内容的浅表副本:从第一个元素开始的数组,并且在原始数组上从未发生过任何突变.为简洁起见,我使用了三元表达式
  • Reasoning

    • In a recursive call, you need to model your task as reduction to a base case. The simplest base case in this case is the empty array - at that point, your function should return zero.
    • What should the reduction step be? Well you can model a sum of an array as the result of adding the first element to the sum of the remainder of the array - at some point, these successive calls will eventually result in a call to sum([]), the answer to which you already know. That is exactly what the code above does.
    • array.slice(1) creates a shallow copy of the array starting from the first element onwards, and no mutation ever occurs on the original array. For conciseness, I have used a ternary expression.
    • 故障:

      sum([1,2,3])
      -> 1 + sum([2,3])
      -> 1 + 2 + sum([3])
      -> 1 + 2 + 3 + sum([])
      -> 1 + 2 + 3 + 0
      -> 6
      

      这篇关于使用递归Javascript的数组总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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