【问题标题】:How get combination of sums of numbers in Array如何获得数组中数字总和的组合
【发布时间】:2018-10-15 12:17:09
【问题描述】:

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

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);

【问题讨论】:

  • 请添加代码,你试过了。
  • 请提供您迄今为止尝试过的代码示例,以便社区可以帮助您
  • to get all combination of sums of its number. 您的迭代不会执行所有组合,它们只是将第一个元素与数组的第 n 个元素相加。
  • 一个 6 岁 的 StackOverflow 活跃成员必须知道,您应该提供一些代码来说明您为达到预期结果所做的尝试。
  • 你是怎么得到 15 的?在那之前它似乎很简单。

标签: javascript algorithm combinations


【解决方案1】:

您可以使用字典或关联数组(JavaScript 的数组)来存储可以得出的总和,方法是使用总和作为索引并将元素设置为“真”,类似于创建筛子;然后,您可以使用for in 有效地迭代这个稀疏数组。

function sums(values) {
    var dictionary = [];
    for (var i in values) {
        var temp = [values[i]];               // start with value by itself
        for (var j in dictionary) {
            temp.push(values[i] + Number(j)); // sum of value and values already in dictionary
        }
        for (var k in temp) {
            dictionary[temp[k]] = true;       // transfer values to dictionary
        }
    }
    var output = [];
    for (var i in dictionary) {
        output.push(Number(i));               // convert dictionary to array of values
    }
    return output;
}
document.write(sums([2,5,11,16]));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2021-07-18
    相关资源
    最近更新 更多