Knapsack problem/Continuous: Difference between revisions
Content added Content deleted
m (→version 1: added/changed whitespace and comments, shorted the SORTD subroutine.) |
|||
Line 2,248:
Originally used the Fortran program as a prototype.
<br>Some amount of code was added to make the output pretty.
<lang rexx>/*REXX program solves the (continuous) burglar's knapsack problem. */
@.=
parse arg maxW d . /*get possible
if maxW=='' | maxW==',' then maxW=15 /*the burglar's knapsack
if d=='' | d==',' then d= 3 /*
wL=d+length('weight'); nL=d+length('total weight'); vL=d+length('value')
totW=0; totV=0
do #=1 while @.#\==''; parse var @.# n.# w.# v.# .
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
call hdr "burglar's knapsack contents"
do j=1 for # while totW<maxW; f=1 /*
if totW+w.j>=maxW then f=(maxW-totW)/w.j /*
totW=totW+w.j*f; totV=totV+v.j*f /*
call syf left(word('{all}',1+(f\==1)),5) n.j, w.j*f, v.j*f
end /*j*/ /*
call sep; say;
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. */
/*──────────────────────────────────one─liner
hdr: say; say;
sep: call sy copies('═',nL), copies("═",wL), copies('═',vL);
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);
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);
$: x=arg(1);if pos(.,x)>1 then x=left(strip(strip(x,
/*──────────────────────────────────SORTD
sortD: do
return
'''output''' using the default inputs of: <tt> 15 3 </tt>▼
▲'''output''' using the default inputs of: <tt> 15 3 </tt>
<pre>
────────────────unsorted item list────────────────
|