猿问

给定一个值,如100,给定一个数组,从数组中挑选出N个元素,用javascript怎么实现呢

如数组:

var arr = [99.1, 92.2, 60, 50,           49.5, 45.7, 25.1, 20, 
           17.4, 13, 10, 7, 2.1, 2, 1];

找到和为100的数组元素,或者结果最接近100的组合:

[60,20,10,7,2,1]


米脂
浏览 707回答 1
1回答

森栏

&nbsp; &nbsp; var arr = [99.1, 92.2, 60, 50,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 49.5, 45.7, 25.1, 20,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 17.4, 13, 10, 7, 2.1, 2, 1&nbsp; &nbsp; &nbsp; &nbsp; ];&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; function combinations(array, n) {&nbsp; &nbsp; var lists = [],&nbsp; &nbsp; &nbsp; &nbsp; M = 1 << array.length;&nbsp; &nbsp; for (var i = 1; i < M; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; var sublist = array.filter(function(c, k) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return i >> k & 1&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; if (sublist.reduce(function(p, c) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return p + c&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, 0) === n)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lists.push(sublist);&nbsp; &nbsp; }&nbsp; &nbsp; return lists;}&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;console.log(combinations(arr, 100))//[[60,20,13,7],[50,20,13,10,7],[49.5,25.1,17.4,7,1],[60,20,10,7,2,1],[49.5,20,17.4,10,2.1,1],[49.5,17.4,13,10,7,2.1,1]]
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答