日期:2014-05-16  浏览次数:20442 次

求一算法,从数组中找出最佳的组合
求一算法,从数组中找出最佳的组合
如 从数组 [ 42.6,140.4,60.2,46.8,11.2,106.6,57,75,47.6,90.2,115.2] 中找到累计值 最接近 600 ( >=600 )的组合
------解决方案--------------------
先按从大到小排序,然后从大到小相加,如超出600则跳过加下一个数,如未超出则加上最小数,以此类推
------解决方案--------------------

var original_array = [42.6,140.4,60.2,46.8,11.2,106.6,57,75,47.6,90.2,115.2];
var result = [];
var condition = 600;

main(original_array);

console.log(result);
console.log(result[0]);

function main(array){
  for(var i =0; i < array.length; i++){
    process(0,array.slice(i,array.length),[]);
  }
  result.sort(function(a,b){
    return a.Total - b.Total;
  });
}

function process(num,array1,array2)
{
  if(num >= condition){
    result.push({Total:num,Array:array2});
    if(array1.length > 0){
      var value = array2[array2.length - 1];
      num -= value;
      process(num,array1,array2.slice(0,array2.length - 1));
    }
  }else{
    if(array1.length > 0){
      var value = array1[0];
      num += value;
      array2.push(value);
      process(num,array1.slice(1,array1.length),array2);
    }
  }
}

------解决方案--------------------
for(i=0; i<result.length; i++) 
  document.write(result[i].Total +':'+ result[i].Array + '<br>');
609.8000000000001:60.2,46.8,11.2,106.6,57,75,47.6,90.2,115.2
635.0000000000001:140.4,60.2,46.8,11.2,106.6,57,75,47.6,90.2
660.0000000000001:140.4,60.2,46.8,11.2,106.6,57,75,47.6,115.2
677.6:42.6,140.4,60.2,46.8,11.2,106.6,57,75,47.6,90.2
702.6:42.6,140.4,60.2,46.8,11.2,106.6,57,75,47.6,115.2

------解决方案--------------------
<script type="text/javascript">
    function fun(arr,top) {
        var temp = [arr];
        if (arr.length < 2)return temp;
        arr.sort(function (a, b) {return a < b});//先倒序排列
        while (arr[0] >= top) {
            arr[0] == top ? temp.push([arr.shift()]) : temp = [[arr.shift()]]; //筛选出所有top及超出top的元素
        }
        var l = arr.length;//总长度
        function arr_sum(t, n) {
            for (var a = n + 1; a < l; a++) {
&nbs