Anonymous user
Knapsack problem/Continuous: Difference between revisions
m
→version 1: added/changed comments, indentations, and whitespace.
(→{{header|Elixir}}: add Alternate Version) |
m (→version 1: added/changed comments, indentations, and whitespace.) |
||
Line 2,566:
Originally used the Fortran program as a prototype.
<br>Some amount of code was added to format the output better.
<lang rexx>/*REXX
@.=
parse arg maxW d . /*get possible arguments from the C.L. */
if maxW=='' | maxW==
if d=='' | d==
wL=d+length('weight'); nL=d+length(
totW=0; totV=0
do #=1 while @.#\==''; parse var @.#
end /*#*/ /* [↑] assign item to separate lists. */
#=#-1 /*#: is the number of items in @ list.*/
call show 'unsorted item list' /*display the header and the @ list.*/
call sortD /*invoke sort (which sorts descending).*/
call hdr "burglar's knapsack contents"
do j=1 for # while totW<maxW; f=1 /*process the items. */
if totW+w.j>=maxW then f=(maxW-totW)/w.j /*calculate
totW=totW+w.j*f; totV=totV+v.j*f /*add it ───► totals. */
call syf left(word('{all}',1+(f\==1)),5) n.j, w.j*f, v.j*f
end /*j*/ /* [↑]
call sep; say; t='t' /* [↓] $ suppresses trailing zeroes.*/
call sy left('total weight',nL,'─'), $(format(totW,,d))
call sy left('total value',nL,'─'), , $(format(totV,,d))
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sortD: do s=2 to #; a=n.s;
do k=s-1 by -1 to 1 while v.k/w.k<u/!; ?=k+1; n.?=n.k; w.?=w.k;v.?=v.k;end
?=k+1; n.?=a; w.?=!; v.?=u
end /*s*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
hdr: say; say; say center(arg(1),50,'─'); say; call title; call sep; return
sep: call sy copies('═', nL), copies("═", wL), copies('═', vL); return
show: call hdr arg(1); do j=1 for #; call syf n.j, w.j, v.j; end;
sy: say left('',9) left(arg(1),nL) right(arg(2),wL) right(arg(3),vL); return
syf: call sy arg(1), $(format(arg(2), , d)), $(format(arg(3), , d));
title: call sy center('item',nL), center("weight", wL), center('value', vL); return
$: parse arg x;
'''output''' using the default inputs of: <tt> 15 3 </tt>
<pre>
|