- 论坛徽章:
- 89
|
3,千万别裸奔,这是北京,裸奔估计得进局子,到时一问你,说是我蹿跶的,我也得跟着进去。
背包问题吗,写一个吧,中午吃饭的时候弄了一个。不是求解固定背包问题的,因为我本来打算捎带着比较一下贪心算法和进化类算法的计算效果的,所以前面有几行是随机生成背包问题的。要不多生成几个,也没法比较啊。。。。
中午那会还打算用Perl、JavaScript、PHP各实现一个,显摆一下自己会的多,C/C++什么的就得下班回家去实现了,上班没环境,不方便。
下午忙点事,回来一看,3真要出去裸奔,这闹的有点大了。。。
本版是C/C++版,3虽然没说是用那种语言实现,但是我用Matlab实现,显示不算赢,所以3不算输。况且我写的可能还不怎么对,而且我也没写其他语言版本的,哈哈。
很简单的Matlab代码,对错都算了吧,3,你千万别出去裸奔,北京不是闹着玩的。
- % This is toy script. Just for fun!
- % For details about the Knapsack problem, check http://en.wikipedia.org/wiki/Knapsack_problem
- % There is no guarantee about the correctness of this script, as I only spent about 20 minutes to write it.
- clc; clear; close; % general things
- % generate a 0-1 knapsack problem
- problem_size = 40;
- w_constraint = 40;
- item_v = ceil(10 * rand(1, problem_size)); % prevent 0 and another way is to rand and plus 1
- item_w = ceil(10 * rand(1, problem_size));
- w = 0; % the initial weight
- v = 0; % the initial value
- % The following line are intend to check the problem validity
- disp(sum(item_w)); % If it is less equal w_constraint, the generated probem may be invalid.
- disp('--------------------------------------------------------------------------------');
- item_r_old = zeros(1, problem_size);
- result_array = zeros(1, problem_size);
- for index = 1:1:problem_size
- item_r_old(index) = item_v(index) / item_w(index);
- end
- [item_r_new, index_array] = sort(item_r_old, 'descend');
- disp(' v w item index item value item weight'); % show the computation process
- for index = 1:1:problem_size
- item_index = index_array(index);
- v = v + item_v(item_index);
- w = w + item_w(item_index);
-
- fprintf('\t%4g\t%4g\t\t%4g\t\t%4g\t\t%4g\n', v, w, item_index, item_v(item_index), item_w(item_index));
-
- if (w > w_constraint)
- result_array = result_array(result_array > 0);
- disp(result_array);
- break;
- else
- result_array(index) = item_index;
- end
- end
复制代码 |
|