1. 程式人生 > >揹包問題的 javascript和java 實現

揹包問題的 javascript和java 實現

簡述:

一個揹包,總載重量限定

提供各種質量及相應價值的物品, 提供一個價值最優的裝包選擇

參考:  http://www.importnew.com/13072.html


<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script type = "text/javascript">

var total = 10;
var OBJ_NUM = 4;
var weights = [];
var values = [];
var matrix = [];

/**** init weights ****/
weights.push(0); // defualt 0
weights.push(5);
weights.push(4);
weights.push(6);
weights.push(3);

/**** init values ****/
values.push(0); // default 0
values.push(10);
values.push(40);
values.push(30);
values.push(50);


/** init row 0 value as ZERO **/
for(var i=0; i<(OBJ_NUM+1)*(total+1); i++)
    matrix.push(0);
	
var X_WIDTH = total + 1;

/****  calculate  ****/
for(var y=1; y<=OBJ_NUM; y++){
    for(var x=1; x<=total; x++){
        if(x >= weights[y]){
            // 添加了當前物品的價值
            var addedValue = matrix[(y - 1) * X_WIDTH + (x - weights[y])] + values[y];        
			matrix[y*X_WIDTH + x] = Math.max(addedValue, 
								    	matrix[(y - 1) * X_WIDTH + x]);
        }else{
		    matrix[y*X_WIDTH + x] = matrix[(y-1) * X_WIDTH + x];
		}
    }
}
 

for(var y=1; y<=OBJ_NUM; y++){	
    for(var x=1; x<=total; x++){
        document.write(matrix[y*X_WIDTH + x] + "\t");
    }
    document.write("</br>");
}

document.write("最優解(揹包的總value值最大)為: " + matrix[(OBJ_NUM+1)*X_WIDTH - 1]);

</script>


</head>
</html>



輸出:




下面是Java的實現

package com.anialy.test.packnage;
/**
 * Package: com.anialy.test.packnage
 * 參考: http://www.importnew.com/13072.html
 *
 */
public class PackageProblem {
	// 物品數量
	private static final int NUM = 4;
	
	// 物品質量, 0為佔位符
	private static int wt[] = new int[]{0, 5, 4, 6, 3}; 
	
	// 物品價值, 0為佔位符
	private static int val[] = new int[]{0, 10, 40, 30, 50};
	
	// 揹包容量
	private static final int TOTAL = 10;
	private static final int X_WIDTH = TOTAL + 1;
	
	private static int process(){
		int calc[] = new int[X_WIDTH * (NUM + 1)];
		
		for(int y=0; y<=NUM; y++)
			for(int x=0; x<=TOTAL; x++)
				calc[y*X_WIDTH + x] = 0;
		
		for(int y=1; y<=NUM; y++){
			for(int x=1; x<=TOTAL; x++){
				if(x >= wt[y]){
					calc[y*X_WIDTH + x] = Math.max(
							val[y] + calc[(y-1)*X_WIDTH + (x-wt[y])]
		        		   , calc[(y-1)*X_WIDTH + x]);
				}else{
					calc[y*X_WIDTH + x] = calc[(y-1)*X_WIDTH + x];
				}
			}
		}
		
		for(int y=1; y<=NUM; y++){
			for(int x=1; x<=TOTAL; x++){
				System.out.format("%3d ", calc[y*X_WIDTH + x]);
			}
			System.out.printf("\n");
		}
		
		// 返回最後一個
		return calc[(NUM+1)*X_WIDTH - 1];
	}
	
	public static void main(String[] args) {
		System.out.printf("\n optimum value: %d", process());
	}
}