背包问题的 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());
	}
}































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值