Knapsack problem/Continuous: Difference between revisions
Content added Content deleted
Underscore (talk | contribs) (→{{header|Haskell}}: Then again, if we're going to use exact arithmetic, we might as well give exact answers.) |
(J) |
||
Line 79: | Line 79: | ||
where a = floor q |
where a = floor q |
||
b = q - toEnum a</lang> |
b = q - toEnum a</lang> |
||
=={{header|J}}== |
|||
We take as much as we can of the most valuable items first, and continue until we run out of space. Only one item needs to be cut. |
|||
<lang J>'names numbers'=:|:;:;._2]0 :0 |
|||
beef 3.8 36 |
|||
pork 5.4 43 |
|||
ham 3.6 90 |
|||
greaves 2.4 45 |
|||
flitch 4.0 30 |
|||
brawn 2.5 56 |
|||
welt 3.7 67 |
|||
salami 3.0 95 |
|||
sausage 5.9 98 |
|||
) |
|||
'weights prices'=:|:".numbers |
|||
order=: \:price%weight |
|||
take=: 15&<.&.(+/\) order{weights |
|||
result=: (*take)#(order{names),.' ',.":,.take</lang> |
|||
This gives the result: |
|||
beef 3.8 |
|||
pork 5.4 |
|||
ham 3.6 |
|||
greaves 2.2 |
|||
For a total value of: |
|||
<lang J> +/take*order{prices |
|||
792</lang> |
|||
=={{header|Java}}== |
=={{header|Java}}== |