Jump to content

Knapsack problem/Continuous: Difference between revisions

m
→‎version 1: added/changed whitespace and comments, made the program safe from NOVALUE errors.
(→‎{{header|Julia}}: A new entry for Julia)
m (→‎version 1: added/changed whitespace and comments, made the program safe from NOVALUE errors.)
Line 2,335:
===version 1===
Originally used the Fortran program as a prototype.
<br>Some amount of code was added to makeformat the output prettybetter.
<lang rexx>/*REXX program solves the (continuous) burglar's knapsack problem. */
@.= /*═══════ name weight value ══════*/
Line 2,358:
call sortD /*invoke sort (which sorts descending).*/
call hdr "burglar's knapsack contents"
do j=1 for # while totW<maxW; f=1 /*process items. */
if totW+w.j>=maxW then f=(maxW-totW)/w.j /*calculate fract.*/
totW=totW+w.j*f; totV=totV+v.j*f /*add ───► totals.*/
call syf left(word('{all}',1+(f\==1)),5) n.j, w.j*f, v.j*f
end /*j*/ /* [↑] show item.*/
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; !=w.s; u=v.s /* [↓] this is a descending sort.*/
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 /* ↑↑↑ sort algorithm is OK for small arrays.*/</lang>
/*──────────────────────────────────one─liner subroutines─────────────────────*/
hdr: say; say; say center(arg(1),50,'─'); say; call title; call sep; return
Line 2,374 ⟶ 2,380:
syf: call sy arg(1), $(format(arg(2),,d)), $(format(arg(3),,d)); return
title: call sy center('item',nL), center("weight",wL), center('value',vL);return
$: arg x=arg(1); if pos(.,x)>1 then x=left(strip(strip(x,t'T',0),,.),length(x));return x</lang>
/*──────────────────────────────────SORTD subroutine──────────────────────────*/
sortD: do s=2 to #; a=n.s; !=w.s; u=v.s /* [↓] this is a descending sort.*/
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 /* ↑↑↑ sort algorithm is OK for small arrays.*/</lang>
'''output''' using the default inputs of: &nbsp; <tt> 15 &nbsp; 3 </tt>
<pre>
Cookies help us deliver our services. By using our services, you agree to our use of cookies.