Knapsack problem/Continuous: Difference between revisions
Content added Content deleted
m (→version 1: re-aligned comment boundaries.) |
m (→version 1: reduced clutter in some variable names, simplified the algorithm.) |
||
Line 1,917: | Line 1,917: | ||
===version 1=== |
===version 1=== |
||
Any resemblance to the Fortran code is 120% coincidental. |
Any resemblance to the Fortran code is 120% coincidental. |
||
<br>Some amount of code was added to make the output pretty. |
|||
<lang rexx>/*REXX program solves the burglar's knapsack (continuous) problem. */ |
<lang rexx>/*REXX program solves the burglar's knapsack (continuous) problem. */ |
||
@.= /*═══════ name weight value ══════*/ |
@.= /*═══════ name weight value ══════*/ |
||
Line 1,945: | Line 1,946: | ||
call show 'unsorted item list' /*display a header and the @ list*/ |
call show 'unsorted item list' /*display a header and the @ list*/ |
||
/*for short lists, method is ok. */ |
/*for short lists, method is ok. */ |
||
do sorts=2 to items /*sort |
do sorts=2 to items /*sort by desending value/unit wt*/ |
||
_n=n.sorts; _w=w.sorts; _v=v.sorts /*calc. placeholders for DO loop.*/ |
_n=n.sorts; _w=w.sorts; _v=v.sorts /*calc. placeholders for DO loop.*/ |
||
do k=sorts-1 by -1 to 1 while v.k/w.k < _v/_w /*order it*/ |
do k=sorts-1 by -1 to 1 while v.k/w.k < _v/_w /*order it*/ |
||
kp=k+1; n.kp=n.k; w.kp=w.k; v.kp=v.k /*shuffle.*/ |
|||
end /*k*/ |
end /*k*/ |
||
kp=k+1; n.kp=_n; w.kp=_w; v.kp=_v |
|||
end /*sorts*/ |
end /*sorts*/ |
||
call hdr "burglar's knapsack contents" |
call hdr "burglar's knapsack contents" |
||
do j=1 for items while totW < maxW |
do j=1 for items while totW < maxW; f=1 |
||
if totW+w.j |
if totW+w.j>=maxW then f=(maxW-totW)/w.j |
||
totW=totW+w.j*f; totV=totV+v.j*f |
|||
call syf n.j, w.j*f, v.j*f |
|||
end /*j*/ |
|||
call sep |
|||
else do |
|||
f=(maxW-totW) / w.j |
|||
totW=totW + w.j*f; totV=totV + v.j*f |
|||
call syf n.j, w.j*f, v.j*f |
|||
end |
|||
end /*j*/ |
|||
call sep /* ddig = # FORMAT decimal digits*/ |
|||
call sy left('total weight',nL,'─'), format(totW,,ddig) |
call sy left('total weight',nL,'─'), format(totW,,ddig) |
||
call sy left('total value',nL,'─'), , format(totV,,ddig) |
call sy left('total value',nL,'─'), , format(totV,,ddig) |