<html>
<head>
<title>找最接近的数</title>
<meta charset="utf-8"> 
 
 
 
</head>
<body >
<p>
问题描述:有一堆若干金条,从中任选几条,使其重量之和与另一给定的数量最接近。
     
</p>
<br>
   <script>
   
   var v=new Array();
   var a=new Array();
   var r_value=new Array();
   var n=parseInt(prompt("总共的金块条数有:",""));
    
   for (ii=0; ii<n; ii++){
    var t=parseInt((prompt("请依次输入每一块金的重量(克).(最多保留二位小数)", "")*100));
    v.push(t);
   }
   var jj=parseInt(prompt("请指定要求最接近的金块重量:","")*100);
    
   function maintest(i,j){ //动态规划函数
        var left,right;
        if(i==-1 || j==0){
        return 0;
        }
    
   else{
        left=maintest(i-1,j);
        right =maintest(i-1,j-v[i])+v[i]; 
        if(Math.abs(left-j)<Math.abs(right-j)){
        return left;
        }
    
        else{
        a.push(v[i]);
        r_value.push(right);
        return right;
        }
    }
    
   }
    
    
    
   function  select_value(a,r_value){  ////找具体的数
        var val_weight=maintest(n-1,jj);
        var find_a=new Array();
        var len_a=a.length;
        while(val_weight){
            len_a=len_a-1;
            if(val_weight==r_value[len_a]){
                find_a.push(a[len_a]);
                val_weight=val_weight-a[len_a];
             
            }
        }
    
        return find_a;
   }
    
    
   var v_view=new Array();
   for (n1=0; n1<v.length; n1++){
    v_view[n1]=v[n1]/100;
    }
    document.write("现有金块明细重量数如下(克):" + v_view);
    document.write("<br>");
     
    document.write("要求最接近的金数是:"+ jj/100);
    document.write("<br>");
     
    document.write("现实最佳组合总数是:" +maintest(n-1,jj)/100);
    document.write("<br>");
     
     
    var ttt_view=select_value(a,r_value);
    for (n2=0; n2<ttt_view.length; n2++){
     
        ttt_view[n2]=ttt_view[n2]/100;
    }
     
        document.write("选择如下金块可达到要求:" +ttt_view);
         
        document.write("<br>");
    
   
   
   </script>
 
</body>
</html>