Anonymous user
Knapsack problem/Continuous: Difference between revisions
→version 1: displayed the numbers better, increased precision to three digits, added comments, created a descending sort subroutine (instead of in-line code), indicated {all} when items were taken in entirety.
(→version 1: displayed the numbers better, increased precision to three digits, added comments, created a descending sort subroutine (instead of in-line code), indicated {all} when items were taken in entirety.) |
|||
Line 1,975:
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
@.=
parse arg maxW
if maxW=='' | maxW==',' then maxW=15 /*burglar's knapsack max weight. */
if
wL=d+length('
totW=0; totV=0
call show 'unsorted item list' /*display
call
end /*k*/▼
kp=k+1; n.kp=_n; w.kp=_w; v.kp=_v▼
call sep; say
▲call hdr "burglar's knapsack contents"
▲ do j=1 for items while totW < maxW; f=1
▲ call syf n.j, w.j*f, v.j*f
▲ end /*j*/
▲call sy left('total weight',nL,'─'), format(totW,,ddig)
▲call sy left('total value',nL,'─'), , format(totV,,ddig)
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────one─liner
hdr: say; say; say center(arg(1),50,'─');
sep: call sy copies('═',nL), copies("═",wL), copies('═',vL); return
show: call hdr arg(1); do j=1 for
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),,
title: call sy center('item',nL), center("weight",wL), center('value',vL); return
$:x=arg(1);if pos(.,x)>1 then x=left(strip(strip(x,'T',0),,.),length(x));return x
'''output''' using the default inputs of: <tt> 15 2 </tt>▼
/*──────────────────────────────────SORTD subroutine───────────────────────────*/
sortD: do sort=2 to #; _n=n.sort; _w=w.sort; _v=v.sort /*descending. */
do k=sort-1 by -1 to 1 while v.k/w.k<_v/_w /*order items.*/
p=k+1; n.p=n.k; w.p=w.k; v.p=v.k /*shuffle 'em.*/
end /*k*/ /*[↓] last one*/
return /* ↑ ↑ ↑ algorithm is OK for smallish arrays.*/</lang>
<pre>
────────────────unsorted item list────────────────
item weight value
═══════════════ ═════════ ════════
flitch 4
beef 3.
pork 5.
greaves 2.
brawn 2.
welt 3.
ham 3.
salami 3
sausage 5.
───────────burglar's knapsack contents────────────
item weight value
═══════════════ ═════════ ════════
{all} salami 3
{all} ham 3.6
{all} brawn 2.5
{all} greaves 2.4
═══════════════ ═════════ ════════
total weight───
total value─── 349.378
</pre>
|