Knapsack problem/Continuous: Difference between revisions

Content added Content deleted
m (→‎{{header|Perl 6}}: fixed 'new' method)
mNo edit summary
Line 159: Line 159:
<lang APL>
<lang APL>
⍝ Data
⍝ Data
⊢Items←'beef' 'pork' 'ham' 'greaves' 'flitch' 'brawn' 'welt' 'salami' 'sausage'
Items←'beef' 'pork' 'ham' 'greaves' 'flitch' 'brawn' 'welt' 'salami' 'sausage'
⊢Weights←3.8 5.4 3.6 2.4 4 2.5 3.7 3 5.9
Weights←3.8 5.4 3.6 2.4 4 2.5 3.7 3 5.9
⊢Prices←36 43 90 45 30 56 67 95 98
Prices←36 43 90 45 30 56 67 95 98


⍝ Solution
⍝ Solution
⊢Order←⍒Worth←Prices÷Weights ⍝ 'Worth' is each item value for 1 kg.
Order←⍒Worth←Prices÷Weights ⍝ 'Worth' is each item value for 1 kg.
diff←{¯1↓(⍵,0)-0,⍵} ⍝ 'diff' between each item and the prev item (the inverse of '+\').
diff←{¯1↓(⍵,0)-0,⍵} ⍝ 'diff' between each item and the prev item (the inverse of '+\').
⊢Filter←×Selected←diff 15⌊+\Weights[Order] ⍝ 'Selected' weights totaling 15kg, others 0.
Filter←×Selected←diff 15⌊+\Weights[Order] ⍝ 'Selected' weights totaling 15kg, others 0.
⊢Table←⊃{⍺,⍪⍵}/Items Weights Selected[⍋Order]
Table←⊃{⍺,⍪⍵}/Items Weights Selected[⍋Order]
⊢Take←Filter[⍋Order]/[1]Table
Take←Filter[⍋Order]/[1]Table
⊢TotalCost←+/Prices×Selected[⍋Order]÷Weights
TotalCost←+/Prices×Selected[⍋Order]÷Weights
</lang>
</lang>