lua---线性规划---最佳收益

本文介绍了如何使用Lua解决线性规划问题,以达到最大化投资收益的目标。通过给出的资金和不同基金的价格、年收益,计算出最优的购买方案,以确保在限制条件下获得最高收益。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如:

资金: 10000

基金:2种

                        价格           年收益

基金1            4000            400

基金2            3000            250


计算最佳收益

输入 资金  基金数  基金1价格 基金1年收益  基金2价格 基金2年收益 ...

输出购买方案和最佳收益


function GreatestReturnSolution(m, y, num, bonds)
	if num == 1 then
		local buy = math.floor(m/bonds[1][1]);
		return {buy*bonds[1][2] * y, buy}
	end
	local bestbuy = 0;
	local bestreturn = {0};
	local idx = 0;
    while(idx * bonds[num][1] < m) do
		local ret = GreatestReturnSolution(m - idx*bonds[num][1], y, num-1,bonds)
 		if idx*bonds[num][2] + ret[1] > bestreturn[1] then
			bestreturn = ret
			bestreturn[1] = idx*bonds[num][2] + ret[1]
			bestreturn[num + 1] = idx
		end
			
		idx = idx + 1
	end
	return bestreturn;
end


print("Input money: ")
money = 10000 --io.read();
print("Input years: ")
years = 1 --io.read();
print("Input bond count: ")
num = 2--io.read();
bond  = {
	{4000, 400},
	{3000, 250}
}

--[[for i=1, num do
	print("Input bond prize and return: ")
	local p = io.read()
	local r = io.read()
	bond[i] = {p, r}
end --]]

function printinput()
	print("---------------------")
	print("money: "..money.."\tyears: "..years)
	print("bond count:"..num)
	for i=1, num do
		print(bond[i][1].."\t"..bond[i][2])
	end
	print("---------------------")
end

printinput();

suo = GreatestReturnSolution(money, years, num, bond)
print("Best return: "..suo[1])
for i=2,#suo do
	print(suo[i].." ")
end



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值