简体   繁体   English

使用递归Javascript的数组的总和

[英]sum of an array using recursion Javascript

Looking for a way to solve this problem by recursing sum() .通过递归sum()寻找解决此问题的方法。 Right now, the code works, but I am supposed to call sum() more than once, and it should not mutate the input array.现在,代码有效,但我应该不止一次调用sum() ,并且它不应该改变输入数组。

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

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.好吧,您可以将数组的总和建模为将第一个元素添加到数组其余部分的sum的结果 - 在某些时候,这些连续调用最终将导致调用sum([]) ,这是对你已经知道了。 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. array.slice(1) 从第一个元素开始创建数组的浅拷贝,并且原始数组上不会发生任何变化。 For conciseness, I have used a ternary expression .为简洁起见,我使用了三元表达式

Breakdown:细分:

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

You're on the right track, but consider that sum could take an optional second argument (that defaults to zero) that indicates the position to start summing from...您走在正确的轨道上,但请考虑 sum 可以采用可选的第二个参数(默认为零),指示从...开始求和的位置。

function sum(array, n) {
    n ||= 0;
    if (n === array.length) {
        return 0;
    } else {
        return array[n] + sum(array, n + 1);
    }
}

arr = [1,2,3,4] arr = [1,2,3,4]
sum = arr.reduce((acc, curr)=> acc+curr) sum = arr.reduce((acc, curr)=> acc+curr)

You don't really need the add function inside your sum function just inline the function and initiate with, 0 as a starting point, or optionally check the i variable for undefined and initialize it to 0!您实际上并不需要 sum 函数中的 add 函数,只需将函数内联并以 0 作为起点启动,或者可选地检查 i 变量是否为 undefined 并将其初始化为 0!

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

You have two solutions:您有两种解决方案:

  • you can use .reduce() method你可以使用.reduce()方法
  • or perform a simple tail recursion或执行简单的尾递归

With reduction :减少

function sum(a, b) {
  return a + b;
}

const array = [1, 2, 3, 4, 5, 6];

//In our reduce, we will apply our sum function, 
//and pass the result as the next value
const res = array.reduce(sum);

With recursion :递归

function sumRec(array, acc = 0, index) {
    //We will update our accumulator, and increment
  // the value of our current index
  return index === array.length
  ? acc
  : sumRec(array, acc += array[index], ++index);
}

console.log(sumRec(array, 0, 0));

Personally, I find the first solution more elegant.就个人而言,我发现第一个解决方案更优雅。

function sumArr(arr){
  if(arr.length>1){
    return arr.pop()+sumArr(arr);
  }else{
    return arr[0];
  }
}

 function sumNumbersRecursively(input){ if (input.length == 0){ return 0; } else{ return input.shift() + sumNumbersRecursively(input); } } console.log(sumNumbersRecursively([2,3,4]))

If you have to call sum more than once, then use the binary approach: split the array in half and recur on each piece.如果您必须多次调用sum ,则使用二元方法:将数组分成两半并在每一块上重复。 When you get to a length of 1, return the single value.当长度为 1 时,返回单个值。

Does this work for you?这对你有用吗? I'm afraid I don't recall the JS syntax for array slices, so my recursion statement may be wrong in the details.恐怕我不记得数组切片的JS语法,所以我的递归语句可能在细节上是错误的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM