Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何得到数组中数和的组合_Javascript_Algorithm_Combinations - Fatal编程技术网

Javascript 如何得到数组中数和的组合

Javascript 如何得到数组中数和的组合,javascript,algorithm,combinations,Javascript,Algorithm,Combinations,我有一个数组,我想得到它的所有和的组合 let arr=[1,2,3,4,5]; 1st iteration : 1+2=3,1+3=4, 1+4=5, 1+5=6 and array becomes arr[1,2,3,4,5,6] 2nd iteration : 2+1=3,2+3=5, 2+4=6, 2+5=7 and array becomes arr[1,2,3,4,5,6,7]...... and 1+2+3=6, 1+2+4=7 . . . and 1+2+3+4=10 . .

我有一个数组,我想得到它的所有和的组合

let arr=[1,2,3,4,5];
1st iteration : 1+2=3,1+3=4, 1+4=5, 1+5=6
and array becomes arr[1,2,3,4,5,6]
2nd iteration : 2+1=3,2+3=5, 2+4=6, 2+5=7
and array becomes arr[1,2,3,4,5,6,7]......

and 1+2+3=6, 1+2+4=7
.
.
.
and 1+2+3+4=10
.
. 
. 
and 1+2+3+4+5=15
and final array becomes =[1,2,3,4,5,6,7,8,9,10,11,15]
有人能帮我建立一个算法吗

这是我迄今为止所做的尝试,我试图准备arr的可能子数组数组,但无法得到所有的组合

let arr=[1,2,3,4,5];
    let a=[];
    for(let i=0; i < arr.length; i++){
        for(let j=0; j < arr.length; j++){
            let b=[];
            for( let k=i; k<=j; k++ ){
                b.push(arr[k]);
            }
            a.push(b);

        }
    }
    console.log(a);

您可以使用字典或关联数组(JavaScript的数组用于存储可以生成的和),方法是使用和作为索引,并将元素设置为“true”,类似于创建筛子;然后,可以使用for in高效地迭代此稀疏数组

函数求和值{ var字典=[]; 对于值中的var i{ var temp=[values[i]];//从值本身开始 对于字典中的var j{ temp.pushvalues[i]+Numberj;//值与字典中已有值之和 } 对于温度中的var k{ dictionary[temp[k]]=true;//将值传输到dictionary } } var输出=[]; 字典中的vari{ output.pushNumberi;//将字典转换为值数组 } 返回输出; }
文件.书面文件[2,5,11,16];请添加您尝试过的代码。请提供您迄今为止尝试过的代码示例,以便社区可以帮助您获得其数字总和的所有组合。您的迭代并没有执行所有的组合,它们只是将数组的第一个元素与第n个元素相加。StackOverflow的一个6岁活跃成员必须知道,您应该提供一些代码,说明您试图实现期望的结果。您是如何得到15的?在那之前,事情似乎很简单。