本文介绍了的Javascript,阵列成员的所有可能的和(最多4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何编写一个函数,将计算数组中的元素的所有可能的总和,具有最大,每增加4元。

由于

  X = [1,32,921,9213,97,23,97,81,965,82,965,823]
 

我需要从去(1 + 32)〜(965 + 823)(1 + 32 + 921 + 9213)〜( 965 + 82 + 965 + 823),计算所有可能的总和。

输出应该是这样的一个数组:

{33:1,32],922:1,921] ... 2835:965,82,965,823]}

填补了所有可能的总和。

这不是功课,我一直在寻找的解释出现了下滑特拉维斯记者:它是关于置换。谢谢大家,我希望这可以也是有用的给别人。

解决方案

的jsfiddle演示

您可以使用置换子集递归算法找到集中的所有款项,以及它们的组合的。

变种X = [1,32,921,9213,97,23,97 ,81,965,82,965,823]。VAR金额= [];VAR套= [];功能子集(读取,队列){ 如果(read.length == 4 ||(read.length&其中; = 4和;&安培; queued.length == 0)){  如果(read.length大于0){   变种总= read.reduce(功能(A,B){返回A + B;},0);   如果(sums.indexOf(总)== - 1){    sums.push(总);    sets.push(read.slice()排序());   }  } }其他{  子集(read.concat(排队[0]),queued.slice(1));  子集(读,queued.slice(1)); }}子集([],X);的console.log(sums.sort(功能(A,B){回报AB;}));//登录款项没有排序,让他们排队套或修改previous结构执行console.log(套);

I am unable to figure out how to write a function that will calculate all possible sums of of the elements of an array, with a max of 4 elements per addition.

Given

x = [1, 32, 921, 9213, 97, 23, 97, 81, 965, 82, 965, 823]

I need to go from (1+32) ~ (965+823) to (1+32+921+9213) ~ (965+82+965+823), calculating all the possible sums.

The output should be an array like this:

{33: [1, 32], 922: [1, 921], .... 2835: [965, 82, 965, 823]}

filled by all the possible sums.

It's not for homework, and what I was looking for is explained down there by Travis J: it was about permutations. Thanks everybody, I hope this could be useful also to someone else.

解决方案

jsFiddle Demo

You can use a permutation subset recursive algorithm to find the set of all of the sums and also their combinations.

var x = [1, 32, 921, 9213, 97, 23, 97, 81, 965, 82, 965, 823];
var sums = [];
var sets = [];
function SubSets(read, queued){
 if( read.length == 4 || (read.length <= 4 && queued.length == 0) ){
  if( read.length > 0 ){
   var total = read.reduce(function(a,b){return a+b;},0);
   if(sums.indexOf(total)==-1){
    sums.push(total);
    sets.push(read.slice().sort());
   }
  }
 }else{
  SubSets(read.concat(queued[0]),queued.slice(1));
  SubSets(read,queued.slice(1));
 }
}
SubSets([],x);
console.log(sums.sort(function(a,b){return a-b;}));
//log sums without sort to have them line up to sets or modify previous structure
console.log(sets);

这篇关于的Javascript,阵列成员的所有可能的和(最多4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 22:23